PackageManagerService.java revision 1bd064f04b77f2f1ba5edd487372887753a49ac6
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 35import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 55import static android.content.pm.PackageManager.INSTALL_INTERNAL; 56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 62import static android.content.pm.PackageManager.MATCH_ALL; 63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 67import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 68import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 69import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 70import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 71import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 72import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 73import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 74import static android.content.pm.PackageManager.PERMISSION_DENIED; 75import static android.content.pm.PackageManager.PERMISSION_GRANTED; 76import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 77import static android.content.pm.PackageParser.isApkFile; 78import static android.os.Process.PACKAGE_INFO_GID; 79import static android.os.Process.SYSTEM_UID; 80import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 81import static android.system.OsConstants.O_CREAT; 82import static android.system.OsConstants.O_RDWR; 83 84import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 86import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 87import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 88import static com.android.internal.util.ArrayUtils.appendInt; 89import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 90import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 91import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 93import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 94import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 95import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 97import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 100 101import android.Manifest; 102import android.annotation.NonNull; 103import android.annotation.Nullable; 104import android.app.ActivityManager; 105import android.app.ActivityManagerNative; 106import android.app.IActivityManager; 107import android.app.admin.DevicePolicyManagerInternal; 108import android.app.admin.IDevicePolicyManager; 109import android.app.admin.SecurityLog; 110import android.app.backup.IBackupManager; 111import android.content.BroadcastReceiver; 112import android.content.ComponentName; 113import android.content.Context; 114import android.content.IIntentReceiver; 115import android.content.Intent; 116import android.content.IntentFilter; 117import android.content.IntentSender; 118import android.content.IntentSender.SendIntentException; 119import android.content.ServiceConnection; 120import android.content.pm.ActivityInfo; 121import android.content.pm.ApplicationInfo; 122import android.content.pm.AppsQueryHelper; 123import android.content.pm.ComponentInfo; 124import android.content.pm.EphemeralApplicationInfo; 125import android.content.pm.EphemeralResolveInfo; 126import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 127import android.content.pm.FeatureInfo; 128import android.content.pm.IOnPermissionsChangeListener; 129import android.content.pm.IPackageDataObserver; 130import android.content.pm.IPackageDeleteObserver; 131import android.content.pm.IPackageDeleteObserver2; 132import android.content.pm.IPackageInstallObserver2; 133import android.content.pm.IPackageInstaller; 134import android.content.pm.IPackageManager; 135import android.content.pm.IPackageMoveObserver; 136import android.content.pm.IPackageStatsObserver; 137import android.content.pm.InstrumentationInfo; 138import android.content.pm.IntentFilterVerificationInfo; 139import android.content.pm.KeySet; 140import android.content.pm.PackageCleanItem; 141import android.content.pm.PackageInfo; 142import android.content.pm.PackageInfoLite; 143import android.content.pm.PackageInstaller; 144import android.content.pm.PackageManager; 145import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 146import android.content.pm.PackageManagerInternal; 147import android.content.pm.PackageParser; 148import android.content.pm.PackageParser.ActivityIntentInfo; 149import android.content.pm.PackageParser.PackageLite; 150import android.content.pm.PackageParser.PackageParserException; 151import android.content.pm.PackageStats; 152import android.content.pm.PackageUserState; 153import android.content.pm.ParceledListSlice; 154import android.content.pm.PermissionGroupInfo; 155import android.content.pm.PermissionInfo; 156import android.content.pm.ProviderInfo; 157import android.content.pm.ResolveInfo; 158import android.content.pm.ServiceInfo; 159import android.content.pm.Signature; 160import android.content.pm.UserInfo; 161import android.content.pm.VerifierDeviceIdentity; 162import android.content.pm.VerifierInfo; 163import android.content.res.Resources; 164import android.graphics.Bitmap; 165import android.hardware.display.DisplayManager; 166import android.net.Uri; 167import android.os.Binder; 168import android.os.Build; 169import android.os.Bundle; 170import android.os.Debug; 171import android.os.Environment; 172import android.os.Environment.UserEnvironment; 173import android.os.FileUtils; 174import android.os.Handler; 175import android.os.IBinder; 176import android.os.Looper; 177import android.os.Message; 178import android.os.Parcel; 179import android.os.ParcelFileDescriptor; 180import android.os.Process; 181import android.os.RemoteCallbackList; 182import android.os.RemoteException; 183import android.os.ResultReceiver; 184import android.os.SELinux; 185import android.os.ServiceManager; 186import android.os.SystemClock; 187import android.os.SystemProperties; 188import android.os.Trace; 189import android.os.UserHandle; 190import android.os.UserManager; 191import android.os.storage.IMountService; 192import android.os.storage.MountServiceInternal; 193import android.os.storage.StorageEventListener; 194import android.os.storage.StorageManager; 195import android.os.storage.VolumeInfo; 196import android.os.storage.VolumeRecord; 197import android.security.KeyStore; 198import android.security.SystemKeyStore; 199import android.system.ErrnoException; 200import android.system.Os; 201import android.text.TextUtils; 202import android.text.format.DateUtils; 203import android.util.ArrayMap; 204import android.util.ArraySet; 205import android.util.AtomicFile; 206import android.util.DisplayMetrics; 207import android.util.EventLog; 208import android.util.ExceptionUtils; 209import android.util.Log; 210import android.util.LogPrinter; 211import android.util.MathUtils; 212import android.util.PrintStreamPrinter; 213import android.util.Slog; 214import android.util.SparseArray; 215import android.util.SparseBooleanArray; 216import android.util.SparseIntArray; 217import android.util.Xml; 218import android.view.Display; 219 220import com.android.internal.R; 221import com.android.internal.annotations.GuardedBy; 222import com.android.internal.app.IMediaContainerService; 223import com.android.internal.app.ResolverActivity; 224import com.android.internal.content.NativeLibraryHelper; 225import com.android.internal.content.PackageHelper; 226import com.android.internal.os.IParcelFileDescriptorFactory; 227import com.android.internal.os.InstallerConnection.InstallerException; 228import com.android.internal.os.SomeArgs; 229import com.android.internal.os.Zygote; 230import com.android.internal.util.ArrayUtils; 231import com.android.internal.util.FastPrintWriter; 232import com.android.internal.util.FastXmlSerializer; 233import com.android.internal.util.IndentingPrintWriter; 234import com.android.internal.util.Preconditions; 235import com.android.internal.util.XmlUtils; 236import com.android.server.EventLogTags; 237import com.android.server.FgThread; 238import com.android.server.IntentResolver; 239import com.android.server.LocalServices; 240import com.android.server.ServiceThread; 241import com.android.server.SystemConfig; 242import com.android.server.Watchdog; 243import com.android.server.pm.PermissionsState.PermissionState; 244import com.android.server.pm.Settings.DatabaseVersion; 245import com.android.server.pm.Settings.VersionInfo; 246import com.android.server.storage.DeviceStorageMonitorInternal; 247 248import dalvik.system.DexFile; 249import dalvik.system.VMRuntime; 250 251import libcore.io.IoUtils; 252import libcore.util.EmptyArray; 253 254import org.xmlpull.v1.XmlPullParser; 255import org.xmlpull.v1.XmlPullParserException; 256import org.xmlpull.v1.XmlSerializer; 257 258import java.io.BufferedInputStream; 259import java.io.BufferedOutputStream; 260import java.io.BufferedReader; 261import java.io.ByteArrayInputStream; 262import java.io.ByteArrayOutputStream; 263import java.io.File; 264import java.io.FileDescriptor; 265import java.io.FileNotFoundException; 266import java.io.FileOutputStream; 267import java.io.FileReader; 268import java.io.FilenameFilter; 269import java.io.IOException; 270import java.io.InputStream; 271import java.io.PrintWriter; 272import java.nio.charset.StandardCharsets; 273import java.security.MessageDigest; 274import java.security.NoSuchAlgorithmException; 275import java.security.PublicKey; 276import java.security.cert.CertificateEncodingException; 277import java.security.cert.CertificateException; 278import java.text.SimpleDateFormat; 279import java.util.ArrayList; 280import java.util.Arrays; 281import java.util.Collection; 282import java.util.Collections; 283import java.util.Comparator; 284import java.util.Date; 285import java.util.HashSet; 286import java.util.Iterator; 287import java.util.List; 288import java.util.Map; 289import java.util.Objects; 290import java.util.Set; 291import java.util.concurrent.CountDownLatch; 292import java.util.concurrent.TimeUnit; 293import java.util.concurrent.atomic.AtomicBoolean; 294import java.util.concurrent.atomic.AtomicInteger; 295import java.util.concurrent.atomic.AtomicLong; 296 297/** 298 * Keep track of all those .apks everywhere. 299 * 300 * This is very central to the platform's security; please run the unit 301 * tests whenever making modifications here: 302 * 303runtest -c android.content.pm.PackageManagerTests frameworks-core 304 * 305 * {@hide} 306 */ 307public class PackageManagerService extends IPackageManager.Stub { 308 static final String TAG = "PackageManager"; 309 static final boolean DEBUG_SETTINGS = false; 310 static final boolean DEBUG_PREFERRED = false; 311 static final boolean DEBUG_UPGRADE = false; 312 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 313 private static final boolean DEBUG_BACKUP = false; 314 private static final boolean DEBUG_INSTALL = false; 315 private static final boolean DEBUG_REMOVE = false; 316 private static final boolean DEBUG_BROADCASTS = false; 317 private static final boolean DEBUG_SHOW_INFO = false; 318 private static final boolean DEBUG_PACKAGE_INFO = false; 319 private static final boolean DEBUG_INTENT_MATCHING = false; 320 private static final boolean DEBUG_PACKAGE_SCANNING = false; 321 private static final boolean DEBUG_VERIFY = false; 322 323 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 324 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 325 // user, but by default initialize to this. 326 static final boolean DEBUG_DEXOPT = false; 327 328 private static final boolean DEBUG_ABI_SELECTION = false; 329 private static final boolean DEBUG_EPHEMERAL = false; 330 private static final boolean DEBUG_TRIAGED_MISSING = false; 331 private static final boolean DEBUG_APP_DATA = false; 332 333 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 334 335 private static final boolean DISABLE_EPHEMERAL_APPS = true; 336 337 private static final int RADIO_UID = Process.PHONE_UID; 338 private static final int LOG_UID = Process.LOG_UID; 339 private static final int NFC_UID = Process.NFC_UID; 340 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 341 private static final int SHELL_UID = Process.SHELL_UID; 342 343 // Cap the size of permission trees that 3rd party apps can define 344 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 345 346 // Suffix used during package installation when copying/moving 347 // package apks to install directory. 348 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 349 350 static final int SCAN_NO_DEX = 1<<1; 351 static final int SCAN_FORCE_DEX = 1<<2; 352 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 353 static final int SCAN_NEW_INSTALL = 1<<4; 354 static final int SCAN_NO_PATHS = 1<<5; 355 static final int SCAN_UPDATE_TIME = 1<<6; 356 static final int SCAN_DEFER_DEX = 1<<7; 357 static final int SCAN_BOOTING = 1<<8; 358 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 359 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 360 static final int SCAN_REPLACING = 1<<11; 361 static final int SCAN_REQUIRE_KNOWN = 1<<12; 362 static final int SCAN_MOVE = 1<<13; 363 static final int SCAN_INITIAL = 1<<14; 364 static final int SCAN_CHECK_ONLY = 1<<15; 365 static final int SCAN_DONT_KILL_APP = 1<<17; 366 367 static final int REMOVE_CHATTY = 1<<16; 368 369 private static final int[] EMPTY_INT_ARRAY = new int[0]; 370 371 /** 372 * Timeout (in milliseconds) after which the watchdog should declare that 373 * our handler thread is wedged. The usual default for such things is one 374 * minute but we sometimes do very lengthy I/O operations on this thread, 375 * such as installing multi-gigabyte applications, so ours needs to be longer. 376 */ 377 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 378 379 /** 380 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 381 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 382 * settings entry if available, otherwise we use the hardcoded default. If it's been 383 * more than this long since the last fstrim, we force one during the boot sequence. 384 * 385 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 386 * one gets run at the next available charging+idle time. This final mandatory 387 * no-fstrim check kicks in only of the other scheduling criteria is never met. 388 */ 389 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 390 391 /** 392 * Whether verification is enabled by default. 393 */ 394 private static final boolean DEFAULT_VERIFY_ENABLE = true; 395 396 /** 397 * The default maximum time to wait for the verification agent to return in 398 * milliseconds. 399 */ 400 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 401 402 /** 403 * The default response for package verification timeout. 404 * 405 * This can be either PackageManager.VERIFICATION_ALLOW or 406 * PackageManager.VERIFICATION_REJECT. 407 */ 408 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 409 410 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 411 412 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 413 DEFAULT_CONTAINER_PACKAGE, 414 "com.android.defcontainer.DefaultContainerService"); 415 416 private static final String KILL_APP_REASON_GIDS_CHANGED = 417 "permission grant or revoke changed gids"; 418 419 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 420 "permissions revoked"; 421 422 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 423 424 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 425 426 /** Permission grant: not grant the permission. */ 427 private static final int GRANT_DENIED = 1; 428 429 /** Permission grant: grant the permission as an install permission. */ 430 private static final int GRANT_INSTALL = 2; 431 432 /** Permission grant: grant the permission as a runtime one. */ 433 private static final int GRANT_RUNTIME = 3; 434 435 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 436 private static final int GRANT_UPGRADE = 4; 437 438 /** Canonical intent used to identify what counts as a "web browser" app */ 439 private static final Intent sBrowserIntent; 440 static { 441 sBrowserIntent = new Intent(); 442 sBrowserIntent.setAction(Intent.ACTION_VIEW); 443 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 444 sBrowserIntent.setData(Uri.parse("http:")); 445 } 446 447 // Compilation reasons. 448 public static final int REASON_FIRST_BOOT = 0; 449 public static final int REASON_BOOT = 1; 450 public static final int REASON_INSTALL = 2; 451 public static final int REASON_BACKGROUND_DEXOPT = 3; 452 public static final int REASON_AB_OTA = 4; 453 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 454 public static final int REASON_SHARED_APK = 6; 455 public static final int REASON_FORCED_DEXOPT = 7; 456 457 public static final int REASON_LAST = REASON_FORCED_DEXOPT; 458 459 final ServiceThread mHandlerThread; 460 461 final PackageHandler mHandler; 462 463 private final ProcessLoggingHandler mProcessLoggingHandler; 464 465 /** 466 * Messages for {@link #mHandler} that need to wait for system ready before 467 * being dispatched. 468 */ 469 private ArrayList<Message> mPostSystemReadyMessages; 470 471 final int mSdkVersion = Build.VERSION.SDK_INT; 472 473 final Context mContext; 474 final boolean mFactoryTest; 475 final boolean mOnlyCore; 476 final DisplayMetrics mMetrics; 477 final int mDefParseFlags; 478 final String[] mSeparateProcesses; 479 final boolean mIsUpgrade; 480 final boolean mIsPreNUpgrade; 481 482 /** The location for ASEC container files on internal storage. */ 483 final String mAsecInternalPath; 484 485 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 486 // LOCK HELD. Can be called with mInstallLock held. 487 @GuardedBy("mInstallLock") 488 final Installer mInstaller; 489 490 /** Directory where installed third-party apps stored */ 491 final File mAppInstallDir; 492 final File mEphemeralInstallDir; 493 494 /** 495 * Directory to which applications installed internally have their 496 * 32 bit native libraries copied. 497 */ 498 private File mAppLib32InstallDir; 499 500 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 501 // apps. 502 final File mDrmAppPrivateInstallDir; 503 504 // ---------------------------------------------------------------- 505 506 // Lock for state used when installing and doing other long running 507 // operations. Methods that must be called with this lock held have 508 // the suffix "LI". 509 final Object mInstallLock = new Object(); 510 511 // ---------------------------------------------------------------- 512 513 // Keys are String (package name), values are Package. This also serves 514 // as the lock for the global state. Methods that must be called with 515 // this lock held have the prefix "LP". 516 @GuardedBy("mPackages") 517 final ArrayMap<String, PackageParser.Package> mPackages = 518 new ArrayMap<String, PackageParser.Package>(); 519 520 final ArrayMap<String, Set<String>> mKnownCodebase = 521 new ArrayMap<String, Set<String>>(); 522 523 // Tracks available target package names -> overlay package paths. 524 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 525 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 526 527 /** 528 * Tracks new system packages [received in an OTA] that we expect to 529 * find updated user-installed versions. Keys are package name, values 530 * are package location. 531 */ 532 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 533 534 /** 535 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 536 */ 537 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 538 /** 539 * Whether or not system app permissions should be promoted from install to runtime. 540 */ 541 boolean mPromoteSystemApps; 542 543 final Settings mSettings; 544 boolean mRestoredSettings; 545 546 // System configuration read by SystemConfig. 547 final int[] mGlobalGids; 548 final SparseArray<ArraySet<String>> mSystemPermissions; 549 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 550 551 // If mac_permissions.xml was found for seinfo labeling. 552 boolean mFoundPolicyFile; 553 554 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 555 556 public static final class SharedLibraryEntry { 557 public final String path; 558 public final String apk; 559 560 SharedLibraryEntry(String _path, String _apk) { 561 path = _path; 562 apk = _apk; 563 } 564 } 565 566 // Currently known shared libraries. 567 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 568 new ArrayMap<String, SharedLibraryEntry>(); 569 570 // All available activities, for your resolving pleasure. 571 final ActivityIntentResolver mActivities = 572 new ActivityIntentResolver(); 573 574 // All available receivers, for your resolving pleasure. 575 final ActivityIntentResolver mReceivers = 576 new ActivityIntentResolver(); 577 578 // All available services, for your resolving pleasure. 579 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 580 581 // All available providers, for your resolving pleasure. 582 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 583 584 // Mapping from provider base names (first directory in content URI codePath) 585 // to the provider information. 586 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 587 new ArrayMap<String, PackageParser.Provider>(); 588 589 // Mapping from instrumentation class names to info about them. 590 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 591 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 592 593 // Mapping from permission names to info about them. 594 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 595 new ArrayMap<String, PackageParser.PermissionGroup>(); 596 597 // Packages whose data we have transfered into another package, thus 598 // should no longer exist. 599 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 600 601 // Broadcast actions that are only available to the system. 602 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 603 604 /** List of packages waiting for verification. */ 605 final SparseArray<PackageVerificationState> mPendingVerification 606 = new SparseArray<PackageVerificationState>(); 607 608 /** Set of packages associated with each app op permission. */ 609 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 610 611 final PackageInstallerService mInstallerService; 612 613 private final PackageDexOptimizer mPackageDexOptimizer; 614 615 private AtomicInteger mNextMoveId = new AtomicInteger(); 616 private final MoveCallbacks mMoveCallbacks; 617 618 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 619 620 // Cache of users who need badging. 621 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 622 623 /** Token for keys in mPendingVerification. */ 624 private int mPendingVerificationToken = 0; 625 626 volatile boolean mSystemReady; 627 volatile boolean mSafeMode; 628 volatile boolean mHasSystemUidErrors; 629 630 ApplicationInfo mAndroidApplication; 631 final ActivityInfo mResolveActivity = new ActivityInfo(); 632 final ResolveInfo mResolveInfo = new ResolveInfo(); 633 ComponentName mResolveComponentName; 634 PackageParser.Package mPlatformPackage; 635 ComponentName mCustomResolverComponentName; 636 637 boolean mResolverReplaced = false; 638 639 private final @Nullable ComponentName mIntentFilterVerifierComponent; 640 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 641 642 private int mIntentFilterVerificationToken = 0; 643 644 /** Component that knows whether or not an ephemeral application exists */ 645 final ComponentName mEphemeralResolverComponent; 646 /** The service connection to the ephemeral resolver */ 647 final EphemeralResolverConnection mEphemeralResolverConnection; 648 649 /** Component used to install ephemeral applications */ 650 final ComponentName mEphemeralInstallerComponent; 651 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 652 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 653 654 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 655 = new SparseArray<IntentFilterVerificationState>(); 656 657 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 658 new DefaultPermissionGrantPolicy(this); 659 660 // List of packages names to keep cached, even if they are uninstalled for all users 661 private List<String> mKeepUninstalledPackages; 662 663 private static class IFVerificationParams { 664 PackageParser.Package pkg; 665 boolean replacing; 666 int userId; 667 int verifierUid; 668 669 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 670 int _userId, int _verifierUid) { 671 pkg = _pkg; 672 replacing = _replacing; 673 userId = _userId; 674 replacing = _replacing; 675 verifierUid = _verifierUid; 676 } 677 } 678 679 private interface IntentFilterVerifier<T extends IntentFilter> { 680 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 681 T filter, String packageName); 682 void startVerifications(int userId); 683 void receiveVerificationResponse(int verificationId); 684 } 685 686 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 687 private Context mContext; 688 private ComponentName mIntentFilterVerifierComponent; 689 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 690 691 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 692 mContext = context; 693 mIntentFilterVerifierComponent = verifierComponent; 694 } 695 696 private String getDefaultScheme() { 697 return IntentFilter.SCHEME_HTTPS; 698 } 699 700 @Override 701 public void startVerifications(int userId) { 702 // Launch verifications requests 703 int count = mCurrentIntentFilterVerifications.size(); 704 for (int n=0; n<count; n++) { 705 int verificationId = mCurrentIntentFilterVerifications.get(n); 706 final IntentFilterVerificationState ivs = 707 mIntentFilterVerificationStates.get(verificationId); 708 709 String packageName = ivs.getPackageName(); 710 711 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 712 final int filterCount = filters.size(); 713 ArraySet<String> domainsSet = new ArraySet<>(); 714 for (int m=0; m<filterCount; m++) { 715 PackageParser.ActivityIntentInfo filter = filters.get(m); 716 domainsSet.addAll(filter.getHostsList()); 717 } 718 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 719 synchronized (mPackages) { 720 if (mSettings.createIntentFilterVerificationIfNeededLPw( 721 packageName, domainsList) != null) { 722 scheduleWriteSettingsLocked(); 723 } 724 } 725 sendVerificationRequest(userId, verificationId, ivs); 726 } 727 mCurrentIntentFilterVerifications.clear(); 728 } 729 730 private void sendVerificationRequest(int userId, int verificationId, 731 IntentFilterVerificationState ivs) { 732 733 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 734 verificationIntent.putExtra( 735 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 736 verificationId); 737 verificationIntent.putExtra( 738 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 739 getDefaultScheme()); 740 verificationIntent.putExtra( 741 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 742 ivs.getHostsString()); 743 verificationIntent.putExtra( 744 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 745 ivs.getPackageName()); 746 verificationIntent.setComponent(mIntentFilterVerifierComponent); 747 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 748 749 UserHandle user = new UserHandle(userId); 750 mContext.sendBroadcastAsUser(verificationIntent, user); 751 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 752 "Sending IntentFilter verification broadcast"); 753 } 754 755 public void receiveVerificationResponse(int verificationId) { 756 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 757 758 final boolean verified = ivs.isVerified(); 759 760 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 761 final int count = filters.size(); 762 if (DEBUG_DOMAIN_VERIFICATION) { 763 Slog.i(TAG, "Received verification response " + verificationId 764 + " for " + count + " filters, verified=" + verified); 765 } 766 for (int n=0; n<count; n++) { 767 PackageParser.ActivityIntentInfo filter = filters.get(n); 768 filter.setVerified(verified); 769 770 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 771 + " verified with result:" + verified + " and hosts:" 772 + ivs.getHostsString()); 773 } 774 775 mIntentFilterVerificationStates.remove(verificationId); 776 777 final String packageName = ivs.getPackageName(); 778 IntentFilterVerificationInfo ivi = null; 779 780 synchronized (mPackages) { 781 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 782 } 783 if (ivi == null) { 784 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 785 + verificationId + " packageName:" + packageName); 786 return; 787 } 788 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 789 "Updating IntentFilterVerificationInfo for package " + packageName 790 +" verificationId:" + verificationId); 791 792 synchronized (mPackages) { 793 if (verified) { 794 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 795 } else { 796 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 797 } 798 scheduleWriteSettingsLocked(); 799 800 final int userId = ivs.getUserId(); 801 if (userId != UserHandle.USER_ALL) { 802 final int userStatus = 803 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 804 805 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 806 boolean needUpdate = false; 807 808 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 809 // already been set by the User thru the Disambiguation dialog 810 switch (userStatus) { 811 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 812 if (verified) { 813 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 814 } else { 815 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 816 } 817 needUpdate = true; 818 break; 819 820 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 821 if (verified) { 822 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 823 needUpdate = true; 824 } 825 break; 826 827 default: 828 // Nothing to do 829 } 830 831 if (needUpdate) { 832 mSettings.updateIntentFilterVerificationStatusLPw( 833 packageName, updatedStatus, userId); 834 scheduleWritePackageRestrictionsLocked(userId); 835 } 836 } 837 } 838 } 839 840 @Override 841 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 842 ActivityIntentInfo filter, String packageName) { 843 if (!hasValidDomains(filter)) { 844 return false; 845 } 846 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 847 if (ivs == null) { 848 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 849 packageName); 850 } 851 if (DEBUG_DOMAIN_VERIFICATION) { 852 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 853 } 854 ivs.addFilter(filter); 855 return true; 856 } 857 858 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 859 int userId, int verificationId, String packageName) { 860 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 861 verifierUid, userId, packageName); 862 ivs.setPendingState(); 863 synchronized (mPackages) { 864 mIntentFilterVerificationStates.append(verificationId, ivs); 865 mCurrentIntentFilterVerifications.add(verificationId); 866 } 867 return ivs; 868 } 869 } 870 871 private static boolean hasValidDomains(ActivityIntentInfo filter) { 872 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 873 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 874 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 875 } 876 877 // Set of pending broadcasts for aggregating enable/disable of components. 878 static class PendingPackageBroadcasts { 879 // for each user id, a map of <package name -> components within that package> 880 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 881 882 public PendingPackageBroadcasts() { 883 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 884 } 885 886 public ArrayList<String> get(int userId, String packageName) { 887 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 888 return packages.get(packageName); 889 } 890 891 public void put(int userId, String packageName, ArrayList<String> components) { 892 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 893 packages.put(packageName, components); 894 } 895 896 public void remove(int userId, String packageName) { 897 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 898 if (packages != null) { 899 packages.remove(packageName); 900 } 901 } 902 903 public void remove(int userId) { 904 mUidMap.remove(userId); 905 } 906 907 public int userIdCount() { 908 return mUidMap.size(); 909 } 910 911 public int userIdAt(int n) { 912 return mUidMap.keyAt(n); 913 } 914 915 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 916 return mUidMap.get(userId); 917 } 918 919 public int size() { 920 // total number of pending broadcast entries across all userIds 921 int num = 0; 922 for (int i = 0; i< mUidMap.size(); i++) { 923 num += mUidMap.valueAt(i).size(); 924 } 925 return num; 926 } 927 928 public void clear() { 929 mUidMap.clear(); 930 } 931 932 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 933 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 934 if (map == null) { 935 map = new ArrayMap<String, ArrayList<String>>(); 936 mUidMap.put(userId, map); 937 } 938 return map; 939 } 940 } 941 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 942 943 // Service Connection to remote media container service to copy 944 // package uri's from external media onto secure containers 945 // or internal storage. 946 private IMediaContainerService mContainerService = null; 947 948 static final int SEND_PENDING_BROADCAST = 1; 949 static final int MCS_BOUND = 3; 950 static final int END_COPY = 4; 951 static final int INIT_COPY = 5; 952 static final int MCS_UNBIND = 6; 953 static final int START_CLEANING_PACKAGE = 7; 954 static final int FIND_INSTALL_LOC = 8; 955 static final int POST_INSTALL = 9; 956 static final int MCS_RECONNECT = 10; 957 static final int MCS_GIVE_UP = 11; 958 static final int UPDATED_MEDIA_STATUS = 12; 959 static final int WRITE_SETTINGS = 13; 960 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 961 static final int PACKAGE_VERIFIED = 15; 962 static final int CHECK_PENDING_VERIFICATION = 16; 963 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 964 static final int INTENT_FILTER_VERIFIED = 18; 965 966 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 967 968 // Delay time in millisecs 969 static final int BROADCAST_DELAY = 10 * 1000; 970 971 static UserManagerService sUserManager; 972 973 // Stores a list of users whose package restrictions file needs to be updated 974 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 975 976 final private DefaultContainerConnection mDefContainerConn = 977 new DefaultContainerConnection(); 978 class DefaultContainerConnection implements ServiceConnection { 979 public void onServiceConnected(ComponentName name, IBinder service) { 980 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 981 IMediaContainerService imcs = 982 IMediaContainerService.Stub.asInterface(service); 983 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 984 } 985 986 public void onServiceDisconnected(ComponentName name) { 987 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 988 } 989 } 990 991 // Recordkeeping of restore-after-install operations that are currently in flight 992 // between the Package Manager and the Backup Manager 993 static class PostInstallData { 994 public InstallArgs args; 995 public PackageInstalledInfo res; 996 997 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 998 args = _a; 999 res = _r; 1000 } 1001 } 1002 1003 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1004 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1005 1006 // XML tags for backup/restore of various bits of state 1007 private static final String TAG_PREFERRED_BACKUP = "pa"; 1008 private static final String TAG_DEFAULT_APPS = "da"; 1009 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1010 1011 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1012 private static final String TAG_ALL_GRANTS = "rt-grants"; 1013 private static final String TAG_GRANT = "grant"; 1014 private static final String ATTR_PACKAGE_NAME = "pkg"; 1015 1016 private static final String TAG_PERMISSION = "perm"; 1017 private static final String ATTR_PERMISSION_NAME = "name"; 1018 private static final String ATTR_IS_GRANTED = "g"; 1019 private static final String ATTR_USER_SET = "set"; 1020 private static final String ATTR_USER_FIXED = "fixed"; 1021 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1022 1023 // System/policy permission grants are not backed up 1024 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1025 FLAG_PERMISSION_POLICY_FIXED 1026 | FLAG_PERMISSION_SYSTEM_FIXED 1027 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1028 1029 // And we back up these user-adjusted states 1030 private static final int USER_RUNTIME_GRANT_MASK = 1031 FLAG_PERMISSION_USER_SET 1032 | FLAG_PERMISSION_USER_FIXED 1033 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1034 1035 final @Nullable String mRequiredVerifierPackage; 1036 final @Nullable String mRequiredInstallerPackage; 1037 1038 private final PackageUsage mPackageUsage = new PackageUsage(); 1039 1040 private class PackageUsage { 1041 private static final int WRITE_INTERVAL 1042 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1043 1044 private final Object mFileLock = new Object(); 1045 private final AtomicLong mLastWritten = new AtomicLong(0); 1046 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1047 1048 private boolean mIsHistoricalPackageUsageAvailable = true; 1049 1050 boolean isHistoricalPackageUsageAvailable() { 1051 return mIsHistoricalPackageUsageAvailable; 1052 } 1053 1054 void write(boolean force) { 1055 if (force) { 1056 writeInternal(); 1057 return; 1058 } 1059 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1060 && !DEBUG_DEXOPT) { 1061 return; 1062 } 1063 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1064 new Thread("PackageUsage_DiskWriter") { 1065 @Override 1066 public void run() { 1067 try { 1068 writeInternal(); 1069 } finally { 1070 mBackgroundWriteRunning.set(false); 1071 } 1072 } 1073 }.start(); 1074 } 1075 } 1076 1077 private void writeInternal() { 1078 synchronized (mPackages) { 1079 synchronized (mFileLock) { 1080 AtomicFile file = getFile(); 1081 FileOutputStream f = null; 1082 try { 1083 f = file.startWrite(); 1084 BufferedOutputStream out = new BufferedOutputStream(f); 1085 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1086 StringBuilder sb = new StringBuilder(); 1087 for (PackageParser.Package pkg : mPackages.values()) { 1088 if (pkg.mLastPackageUsageTimeInMills == 0) { 1089 continue; 1090 } 1091 sb.setLength(0); 1092 sb.append(pkg.packageName); 1093 sb.append(' '); 1094 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1095 sb.append('\n'); 1096 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1097 } 1098 out.flush(); 1099 file.finishWrite(f); 1100 } catch (IOException e) { 1101 if (f != null) { 1102 file.failWrite(f); 1103 } 1104 Log.e(TAG, "Failed to write package usage times", e); 1105 } 1106 } 1107 } 1108 mLastWritten.set(SystemClock.elapsedRealtime()); 1109 } 1110 1111 void readLP() { 1112 synchronized (mFileLock) { 1113 AtomicFile file = getFile(); 1114 BufferedInputStream in = null; 1115 try { 1116 in = new BufferedInputStream(file.openRead()); 1117 StringBuffer sb = new StringBuffer(); 1118 while (true) { 1119 String packageName = readToken(in, sb, ' '); 1120 if (packageName == null) { 1121 break; 1122 } 1123 String timeInMillisString = readToken(in, sb, '\n'); 1124 if (timeInMillisString == null) { 1125 throw new IOException("Failed to find last usage time for package " 1126 + packageName); 1127 } 1128 PackageParser.Package pkg = mPackages.get(packageName); 1129 if (pkg == null) { 1130 continue; 1131 } 1132 long timeInMillis; 1133 try { 1134 timeInMillis = Long.parseLong(timeInMillisString); 1135 } catch (NumberFormatException e) { 1136 throw new IOException("Failed to parse " + timeInMillisString 1137 + " as a long.", e); 1138 } 1139 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1140 } 1141 } catch (FileNotFoundException expected) { 1142 mIsHistoricalPackageUsageAvailable = false; 1143 } catch (IOException e) { 1144 Log.w(TAG, "Failed to read package usage times", e); 1145 } finally { 1146 IoUtils.closeQuietly(in); 1147 } 1148 } 1149 mLastWritten.set(SystemClock.elapsedRealtime()); 1150 } 1151 1152 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1153 throws IOException { 1154 sb.setLength(0); 1155 while (true) { 1156 int ch = in.read(); 1157 if (ch == -1) { 1158 if (sb.length() == 0) { 1159 return null; 1160 } 1161 throw new IOException("Unexpected EOF"); 1162 } 1163 if (ch == endOfToken) { 1164 return sb.toString(); 1165 } 1166 sb.append((char)ch); 1167 } 1168 } 1169 1170 private AtomicFile getFile() { 1171 File dataDir = Environment.getDataDirectory(); 1172 File systemDir = new File(dataDir, "system"); 1173 File fname = new File(systemDir, "package-usage.list"); 1174 return new AtomicFile(fname); 1175 } 1176 } 1177 1178 class PackageHandler extends Handler { 1179 private boolean mBound = false; 1180 final ArrayList<HandlerParams> mPendingInstalls = 1181 new ArrayList<HandlerParams>(); 1182 1183 private boolean connectToService() { 1184 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1185 " DefaultContainerService"); 1186 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1187 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1188 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1189 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1190 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1191 mBound = true; 1192 return true; 1193 } 1194 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1195 return false; 1196 } 1197 1198 private void disconnectService() { 1199 mContainerService = null; 1200 mBound = false; 1201 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1202 mContext.unbindService(mDefContainerConn); 1203 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1204 } 1205 1206 PackageHandler(Looper looper) { 1207 super(looper); 1208 } 1209 1210 public void handleMessage(Message msg) { 1211 try { 1212 doHandleMessage(msg); 1213 } finally { 1214 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1215 } 1216 } 1217 1218 void doHandleMessage(Message msg) { 1219 switch (msg.what) { 1220 case INIT_COPY: { 1221 HandlerParams params = (HandlerParams) msg.obj; 1222 int idx = mPendingInstalls.size(); 1223 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1224 // If a bind was already initiated we dont really 1225 // need to do anything. The pending install 1226 // will be processed later on. 1227 if (!mBound) { 1228 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1229 System.identityHashCode(mHandler)); 1230 // If this is the only one pending we might 1231 // have to bind to the service again. 1232 if (!connectToService()) { 1233 Slog.e(TAG, "Failed to bind to media container service"); 1234 params.serviceError(); 1235 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1236 System.identityHashCode(mHandler)); 1237 if (params.traceMethod != null) { 1238 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1239 params.traceCookie); 1240 } 1241 return; 1242 } else { 1243 // Once we bind to the service, the first 1244 // pending request will be processed. 1245 mPendingInstalls.add(idx, params); 1246 } 1247 } else { 1248 mPendingInstalls.add(idx, params); 1249 // Already bound to the service. Just make 1250 // sure we trigger off processing the first request. 1251 if (idx == 0) { 1252 mHandler.sendEmptyMessage(MCS_BOUND); 1253 } 1254 } 1255 break; 1256 } 1257 case MCS_BOUND: { 1258 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1259 if (msg.obj != null) { 1260 mContainerService = (IMediaContainerService) msg.obj; 1261 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1262 System.identityHashCode(mHandler)); 1263 } 1264 if (mContainerService == null) { 1265 if (!mBound) { 1266 // Something seriously wrong since we are not bound and we are not 1267 // waiting for connection. Bail out. 1268 Slog.e(TAG, "Cannot bind to media container service"); 1269 for (HandlerParams params : mPendingInstalls) { 1270 // Indicate service bind error 1271 params.serviceError(); 1272 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1273 System.identityHashCode(params)); 1274 if (params.traceMethod != null) { 1275 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1276 params.traceMethod, params.traceCookie); 1277 } 1278 return; 1279 } 1280 mPendingInstalls.clear(); 1281 } else { 1282 Slog.w(TAG, "Waiting to connect to media container service"); 1283 } 1284 } else if (mPendingInstalls.size() > 0) { 1285 HandlerParams params = mPendingInstalls.get(0); 1286 if (params != null) { 1287 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1288 System.identityHashCode(params)); 1289 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1290 if (params.startCopy()) { 1291 // We are done... look for more work or to 1292 // go idle. 1293 if (DEBUG_SD_INSTALL) Log.i(TAG, 1294 "Checking for more work or unbind..."); 1295 // Delete pending install 1296 if (mPendingInstalls.size() > 0) { 1297 mPendingInstalls.remove(0); 1298 } 1299 if (mPendingInstalls.size() == 0) { 1300 if (mBound) { 1301 if (DEBUG_SD_INSTALL) Log.i(TAG, 1302 "Posting delayed MCS_UNBIND"); 1303 removeMessages(MCS_UNBIND); 1304 Message ubmsg = obtainMessage(MCS_UNBIND); 1305 // Unbind after a little delay, to avoid 1306 // continual thrashing. 1307 sendMessageDelayed(ubmsg, 10000); 1308 } 1309 } else { 1310 // There are more pending requests in queue. 1311 // Just post MCS_BOUND message to trigger processing 1312 // of next pending install. 1313 if (DEBUG_SD_INSTALL) Log.i(TAG, 1314 "Posting MCS_BOUND for next work"); 1315 mHandler.sendEmptyMessage(MCS_BOUND); 1316 } 1317 } 1318 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1319 } 1320 } else { 1321 // Should never happen ideally. 1322 Slog.w(TAG, "Empty queue"); 1323 } 1324 break; 1325 } 1326 case MCS_RECONNECT: { 1327 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1328 if (mPendingInstalls.size() > 0) { 1329 if (mBound) { 1330 disconnectService(); 1331 } 1332 if (!connectToService()) { 1333 Slog.e(TAG, "Failed to bind to media container service"); 1334 for (HandlerParams params : mPendingInstalls) { 1335 // Indicate service bind error 1336 params.serviceError(); 1337 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1338 System.identityHashCode(params)); 1339 } 1340 mPendingInstalls.clear(); 1341 } 1342 } 1343 break; 1344 } 1345 case MCS_UNBIND: { 1346 // If there is no actual work left, then time to unbind. 1347 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1348 1349 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1350 if (mBound) { 1351 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1352 1353 disconnectService(); 1354 } 1355 } else if (mPendingInstalls.size() > 0) { 1356 // There are more pending requests in queue. 1357 // Just post MCS_BOUND message to trigger processing 1358 // of next pending install. 1359 mHandler.sendEmptyMessage(MCS_BOUND); 1360 } 1361 1362 break; 1363 } 1364 case MCS_GIVE_UP: { 1365 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1366 HandlerParams params = mPendingInstalls.remove(0); 1367 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1368 System.identityHashCode(params)); 1369 break; 1370 } 1371 case SEND_PENDING_BROADCAST: { 1372 String packages[]; 1373 ArrayList<String> components[]; 1374 int size = 0; 1375 int uids[]; 1376 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1377 synchronized (mPackages) { 1378 if (mPendingBroadcasts == null) { 1379 return; 1380 } 1381 size = mPendingBroadcasts.size(); 1382 if (size <= 0) { 1383 // Nothing to be done. Just return 1384 return; 1385 } 1386 packages = new String[size]; 1387 components = new ArrayList[size]; 1388 uids = new int[size]; 1389 int i = 0; // filling out the above arrays 1390 1391 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1392 int packageUserId = mPendingBroadcasts.userIdAt(n); 1393 Iterator<Map.Entry<String, ArrayList<String>>> it 1394 = mPendingBroadcasts.packagesForUserId(packageUserId) 1395 .entrySet().iterator(); 1396 while (it.hasNext() && i < size) { 1397 Map.Entry<String, ArrayList<String>> ent = it.next(); 1398 packages[i] = ent.getKey(); 1399 components[i] = ent.getValue(); 1400 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1401 uids[i] = (ps != null) 1402 ? UserHandle.getUid(packageUserId, ps.appId) 1403 : -1; 1404 i++; 1405 } 1406 } 1407 size = i; 1408 mPendingBroadcasts.clear(); 1409 } 1410 // Send broadcasts 1411 for (int i = 0; i < size; i++) { 1412 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1413 } 1414 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1415 break; 1416 } 1417 case START_CLEANING_PACKAGE: { 1418 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1419 final String packageName = (String)msg.obj; 1420 final int userId = msg.arg1; 1421 final boolean andCode = msg.arg2 != 0; 1422 synchronized (mPackages) { 1423 if (userId == UserHandle.USER_ALL) { 1424 int[] users = sUserManager.getUserIds(); 1425 for (int user : users) { 1426 mSettings.addPackageToCleanLPw( 1427 new PackageCleanItem(user, packageName, andCode)); 1428 } 1429 } else { 1430 mSettings.addPackageToCleanLPw( 1431 new PackageCleanItem(userId, packageName, andCode)); 1432 } 1433 } 1434 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1435 startCleaningPackages(); 1436 } break; 1437 case POST_INSTALL: { 1438 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1439 1440 PostInstallData data = mRunningInstalls.get(msg.arg1); 1441 mRunningInstalls.delete(msg.arg1); 1442 1443 if (data != null) { 1444 InstallArgs args = data.args; 1445 PackageInstalledInfo parentRes = data.res; 1446 1447 final boolean grantPermissions = (args.installFlags 1448 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1449 final boolean killApp = (args.installFlags 1450 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1451 final String[] grantedPermissions = args.installGrantPermissions; 1452 1453 // Handle the parent package 1454 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1455 grantedPermissions, args.observer); 1456 1457 // Handle the child packages 1458 final int childCount = (parentRes.addedChildPackages != null) 1459 ? parentRes.addedChildPackages.size() : 0; 1460 for (int i = 0; i < childCount; i++) { 1461 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1462 handlePackagePostInstall(childRes, grantPermissions, killApp, 1463 grantedPermissions, args.observer); 1464 } 1465 1466 // Log tracing if needed 1467 if (args.traceMethod != null) { 1468 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1469 args.traceCookie); 1470 } 1471 } else { 1472 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1473 } 1474 1475 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1476 } break; 1477 case UPDATED_MEDIA_STATUS: { 1478 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1479 boolean reportStatus = msg.arg1 == 1; 1480 boolean doGc = msg.arg2 == 1; 1481 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1482 if (doGc) { 1483 // Force a gc to clear up stale containers. 1484 Runtime.getRuntime().gc(); 1485 } 1486 if (msg.obj != null) { 1487 @SuppressWarnings("unchecked") 1488 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1489 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1490 // Unload containers 1491 unloadAllContainers(args); 1492 } 1493 if (reportStatus) { 1494 try { 1495 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1496 PackageHelper.getMountService().finishMediaUpdate(); 1497 } catch (RemoteException e) { 1498 Log.e(TAG, "MountService not running?"); 1499 } 1500 } 1501 } break; 1502 case WRITE_SETTINGS: { 1503 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1504 synchronized (mPackages) { 1505 removeMessages(WRITE_SETTINGS); 1506 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1507 mSettings.writeLPr(); 1508 mDirtyUsers.clear(); 1509 } 1510 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1511 } break; 1512 case WRITE_PACKAGE_RESTRICTIONS: { 1513 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1514 synchronized (mPackages) { 1515 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1516 for (int userId : mDirtyUsers) { 1517 mSettings.writePackageRestrictionsLPr(userId); 1518 } 1519 mDirtyUsers.clear(); 1520 } 1521 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1522 } break; 1523 case CHECK_PENDING_VERIFICATION: { 1524 final int verificationId = msg.arg1; 1525 final PackageVerificationState state = mPendingVerification.get(verificationId); 1526 1527 if ((state != null) && !state.timeoutExtended()) { 1528 final InstallArgs args = state.getInstallArgs(); 1529 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1530 1531 Slog.i(TAG, "Verification timed out for " + originUri); 1532 mPendingVerification.remove(verificationId); 1533 1534 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1535 1536 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1537 Slog.i(TAG, "Continuing with installation of " + originUri); 1538 state.setVerifierResponse(Binder.getCallingUid(), 1539 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1540 broadcastPackageVerified(verificationId, originUri, 1541 PackageManager.VERIFICATION_ALLOW, 1542 state.getInstallArgs().getUser()); 1543 try { 1544 ret = args.copyApk(mContainerService, true); 1545 } catch (RemoteException e) { 1546 Slog.e(TAG, "Could not contact the ContainerService"); 1547 } 1548 } else { 1549 broadcastPackageVerified(verificationId, originUri, 1550 PackageManager.VERIFICATION_REJECT, 1551 state.getInstallArgs().getUser()); 1552 } 1553 1554 Trace.asyncTraceEnd( 1555 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1556 1557 processPendingInstall(args, ret); 1558 mHandler.sendEmptyMessage(MCS_UNBIND); 1559 } 1560 break; 1561 } 1562 case PACKAGE_VERIFIED: { 1563 final int verificationId = msg.arg1; 1564 1565 final PackageVerificationState state = mPendingVerification.get(verificationId); 1566 if (state == null) { 1567 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1568 break; 1569 } 1570 1571 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1572 1573 state.setVerifierResponse(response.callerUid, response.code); 1574 1575 if (state.isVerificationComplete()) { 1576 mPendingVerification.remove(verificationId); 1577 1578 final InstallArgs args = state.getInstallArgs(); 1579 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1580 1581 int ret; 1582 if (state.isInstallAllowed()) { 1583 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1584 broadcastPackageVerified(verificationId, originUri, 1585 response.code, state.getInstallArgs().getUser()); 1586 try { 1587 ret = args.copyApk(mContainerService, true); 1588 } catch (RemoteException e) { 1589 Slog.e(TAG, "Could not contact the ContainerService"); 1590 } 1591 } else { 1592 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1593 } 1594 1595 Trace.asyncTraceEnd( 1596 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1597 1598 processPendingInstall(args, ret); 1599 mHandler.sendEmptyMessage(MCS_UNBIND); 1600 } 1601 1602 break; 1603 } 1604 case START_INTENT_FILTER_VERIFICATIONS: { 1605 IFVerificationParams params = (IFVerificationParams) msg.obj; 1606 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1607 params.replacing, params.pkg); 1608 break; 1609 } 1610 case INTENT_FILTER_VERIFIED: { 1611 final int verificationId = msg.arg1; 1612 1613 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1614 verificationId); 1615 if (state == null) { 1616 Slog.w(TAG, "Invalid IntentFilter verification token " 1617 + verificationId + " received"); 1618 break; 1619 } 1620 1621 final int userId = state.getUserId(); 1622 1623 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1624 "Processing IntentFilter verification with token:" 1625 + verificationId + " and userId:" + userId); 1626 1627 final IntentFilterVerificationResponse response = 1628 (IntentFilterVerificationResponse) msg.obj; 1629 1630 state.setVerifierResponse(response.callerUid, response.code); 1631 1632 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1633 "IntentFilter verification with token:" + verificationId 1634 + " and userId:" + userId 1635 + " is settings verifier response with response code:" 1636 + response.code); 1637 1638 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1639 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1640 + response.getFailedDomainsString()); 1641 } 1642 1643 if (state.isVerificationComplete()) { 1644 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1645 } else { 1646 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1647 "IntentFilter verification with token:" + verificationId 1648 + " was not said to be complete"); 1649 } 1650 1651 break; 1652 } 1653 } 1654 } 1655 } 1656 1657 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1658 boolean killApp, String[] grantedPermissions, 1659 IPackageInstallObserver2 installObserver) { 1660 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1661 // Send the removed broadcasts 1662 if (res.removedInfo != null) { 1663 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1664 } 1665 1666 // Now that we successfully installed the package, grant runtime 1667 // permissions if requested before broadcasting the install. 1668 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1669 >= Build.VERSION_CODES.M) { 1670 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1671 } 1672 1673 final boolean update = res.removedInfo != null 1674 && res.removedInfo.removedPackage != null; 1675 1676 // If this is the first time we have child packages for a disabled privileged 1677 // app that had no children, we grant requested runtime permissions to the new 1678 // children if the parent on the system image had them already granted. 1679 if (res.pkg.parentPackage != null) { 1680 synchronized (mPackages) { 1681 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1682 } 1683 } 1684 1685 synchronized (mPackages) { 1686 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1687 } 1688 1689 final String packageName = res.pkg.applicationInfo.packageName; 1690 Bundle extras = new Bundle(1); 1691 extras.putInt(Intent.EXTRA_UID, res.uid); 1692 1693 // Determine the set of users who are adding this package for 1694 // the first time vs. those who are seeing an update. 1695 int[] firstUsers = EMPTY_INT_ARRAY; 1696 int[] updateUsers = EMPTY_INT_ARRAY; 1697 if (res.origUsers == null || res.origUsers.length == 0) { 1698 firstUsers = res.newUsers; 1699 } else { 1700 for (int newUser : res.newUsers) { 1701 boolean isNew = true; 1702 for (int origUser : res.origUsers) { 1703 if (origUser == newUser) { 1704 isNew = false; 1705 break; 1706 } 1707 } 1708 if (isNew) { 1709 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1710 } else { 1711 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1712 } 1713 } 1714 } 1715 1716 // Send installed broadcasts if the install/update is not ephemeral 1717 if (!isEphemeral(res.pkg)) { 1718 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1719 1720 // Send added for users that see the package for the first time 1721 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1722 extras, 0 /*flags*/, null /*targetPackage*/, 1723 null /*finishedReceiver*/, firstUsers); 1724 1725 // Send added for users that don't see the package for the first time 1726 if (update) { 1727 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1728 } 1729 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1730 extras, 0 /*flags*/, null /*targetPackage*/, 1731 null /*finishedReceiver*/, updateUsers); 1732 1733 // Send replaced for users that don't see the package for the first time 1734 if (update) { 1735 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1736 packageName, extras, 0 /*flags*/, 1737 null /*targetPackage*/, null /*finishedReceiver*/, 1738 updateUsers); 1739 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1740 null /*package*/, null /*extras*/, 0 /*flags*/, 1741 packageName /*targetPackage*/, 1742 null /*finishedReceiver*/, updateUsers); 1743 } 1744 1745 // Send broadcast package appeared if forward locked/external for all users 1746 // treat asec-hosted packages like removable media on upgrade 1747 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1748 if (DEBUG_INSTALL) { 1749 Slog.i(TAG, "upgrading pkg " + res.pkg 1750 + " is ASEC-hosted -> AVAILABLE"); 1751 } 1752 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1753 ArrayList<String> pkgList = new ArrayList<>(1); 1754 pkgList.add(packageName); 1755 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1756 } 1757 } 1758 1759 // Work that needs to happen on first install within each user 1760 if (firstUsers != null && firstUsers.length > 0) { 1761 synchronized (mPackages) { 1762 for (int userId : firstUsers) { 1763 // If this app is a browser and it's newly-installed for some 1764 // users, clear any default-browser state in those users. The 1765 // app's nature doesn't depend on the user, so we can just check 1766 // its browser nature in any user and generalize. 1767 if (packageIsBrowser(packageName, userId)) { 1768 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1769 } 1770 1771 // We may also need to apply pending (restored) runtime 1772 // permission grants within these users. 1773 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1774 } 1775 } 1776 } 1777 1778 // Log current value of "unknown sources" setting 1779 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1780 getUnknownSourcesSettings()); 1781 1782 // Force a gc to clear up things 1783 Runtime.getRuntime().gc(); 1784 1785 // Remove the replaced package's older resources safely now 1786 // We delete after a gc for applications on sdcard. 1787 if (res.removedInfo != null && res.removedInfo.args != null) { 1788 synchronized (mInstallLock) { 1789 res.removedInfo.args.doPostDeleteLI(true); 1790 } 1791 } 1792 } 1793 1794 // If someone is watching installs - notify them 1795 if (installObserver != null) { 1796 try { 1797 Bundle extras = extrasForInstallResult(res); 1798 installObserver.onPackageInstalled(res.name, res.returnCode, 1799 res.returnMsg, extras); 1800 } catch (RemoteException e) { 1801 Slog.i(TAG, "Observer no longer exists."); 1802 } 1803 } 1804 } 1805 1806 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1807 PackageParser.Package pkg) { 1808 if (pkg.parentPackage == null) { 1809 return; 1810 } 1811 if (pkg.requestedPermissions == null) { 1812 return; 1813 } 1814 final PackageSetting disabledSysParentPs = mSettings 1815 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1816 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1817 || !disabledSysParentPs.isPrivileged() 1818 || (disabledSysParentPs.childPackageNames != null 1819 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1820 return; 1821 } 1822 final int[] allUserIds = sUserManager.getUserIds(); 1823 final int permCount = pkg.requestedPermissions.size(); 1824 for (int i = 0; i < permCount; i++) { 1825 String permission = pkg.requestedPermissions.get(i); 1826 BasePermission bp = mSettings.mPermissions.get(permission); 1827 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1828 continue; 1829 } 1830 for (int userId : allUserIds) { 1831 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1832 permission, userId)) { 1833 grantRuntimePermission(pkg.packageName, permission, userId); 1834 } 1835 } 1836 } 1837 } 1838 1839 private StorageEventListener mStorageListener = new StorageEventListener() { 1840 @Override 1841 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1842 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1843 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1844 final String volumeUuid = vol.getFsUuid(); 1845 1846 // Clean up any users or apps that were removed or recreated 1847 // while this volume was missing 1848 reconcileUsers(volumeUuid); 1849 reconcileApps(volumeUuid); 1850 1851 // Clean up any install sessions that expired or were 1852 // cancelled while this volume was missing 1853 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1854 1855 loadPrivatePackages(vol); 1856 1857 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1858 unloadPrivatePackages(vol); 1859 } 1860 } 1861 1862 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1863 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1864 updateExternalMediaStatus(true, false); 1865 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1866 updateExternalMediaStatus(false, false); 1867 } 1868 } 1869 } 1870 1871 @Override 1872 public void onVolumeForgotten(String fsUuid) { 1873 if (TextUtils.isEmpty(fsUuid)) { 1874 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1875 return; 1876 } 1877 1878 // Remove any apps installed on the forgotten volume 1879 synchronized (mPackages) { 1880 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1881 for (PackageSetting ps : packages) { 1882 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1883 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1884 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1885 } 1886 1887 mSettings.onVolumeForgotten(fsUuid); 1888 mSettings.writeLPr(); 1889 } 1890 } 1891 }; 1892 1893 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1894 String[] grantedPermissions) { 1895 for (int userId : userIds) { 1896 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1897 } 1898 1899 // We could have touched GID membership, so flush out packages.list 1900 synchronized (mPackages) { 1901 mSettings.writePackageListLPr(); 1902 } 1903 } 1904 1905 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1906 String[] grantedPermissions) { 1907 SettingBase sb = (SettingBase) pkg.mExtras; 1908 if (sb == null) { 1909 return; 1910 } 1911 1912 PermissionsState permissionsState = sb.getPermissionsState(); 1913 1914 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1915 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1916 1917 synchronized (mPackages) { 1918 for (String permission : pkg.requestedPermissions) { 1919 BasePermission bp = mSettings.mPermissions.get(permission); 1920 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1921 && (grantedPermissions == null 1922 || ArrayUtils.contains(grantedPermissions, permission))) { 1923 final int flags = permissionsState.getPermissionFlags(permission, userId); 1924 // Installer cannot change immutable permissions. 1925 if ((flags & immutableFlags) == 0) { 1926 grantRuntimePermission(pkg.packageName, permission, userId); 1927 } 1928 } 1929 } 1930 } 1931 } 1932 1933 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1934 Bundle extras = null; 1935 switch (res.returnCode) { 1936 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1937 extras = new Bundle(); 1938 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1939 res.origPermission); 1940 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1941 res.origPackage); 1942 break; 1943 } 1944 case PackageManager.INSTALL_SUCCEEDED: { 1945 extras = new Bundle(); 1946 extras.putBoolean(Intent.EXTRA_REPLACING, 1947 res.removedInfo != null && res.removedInfo.removedPackage != null); 1948 break; 1949 } 1950 } 1951 return extras; 1952 } 1953 1954 void scheduleWriteSettingsLocked() { 1955 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1956 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1957 } 1958 } 1959 1960 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 1961 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 1962 scheduleWritePackageRestrictionsLocked(userId); 1963 } 1964 1965 void scheduleWritePackageRestrictionsLocked(int userId) { 1966 final int[] userIds = (userId == UserHandle.USER_ALL) 1967 ? sUserManager.getUserIds() : new int[]{userId}; 1968 for (int nextUserId : userIds) { 1969 if (!sUserManager.exists(nextUserId)) return; 1970 mDirtyUsers.add(nextUserId); 1971 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1972 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1973 } 1974 } 1975 } 1976 1977 public static PackageManagerService main(Context context, Installer installer, 1978 boolean factoryTest, boolean onlyCore) { 1979 // Self-check for initial settings. 1980 PackageManagerServiceCompilerMapping.checkProperties(); 1981 1982 PackageManagerService m = new PackageManagerService(context, installer, 1983 factoryTest, onlyCore); 1984 m.enableSystemUserPackages(); 1985 ServiceManager.addService("package", m); 1986 return m; 1987 } 1988 1989 private void enableSystemUserPackages() { 1990 if (!UserManager.isSplitSystemUser()) { 1991 return; 1992 } 1993 // For system user, enable apps based on the following conditions: 1994 // - app is whitelisted or belong to one of these groups: 1995 // -- system app which has no launcher icons 1996 // -- system app which has INTERACT_ACROSS_USERS permission 1997 // -- system IME app 1998 // - app is not in the blacklist 1999 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2000 Set<String> enableApps = new ArraySet<>(); 2001 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2002 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2003 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2004 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2005 enableApps.addAll(wlApps); 2006 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2007 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2008 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2009 enableApps.removeAll(blApps); 2010 Log.i(TAG, "Applications installed for system user: " + enableApps); 2011 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2012 UserHandle.SYSTEM); 2013 final int allAppsSize = allAps.size(); 2014 synchronized (mPackages) { 2015 for (int i = 0; i < allAppsSize; i++) { 2016 String pName = allAps.get(i); 2017 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2018 // Should not happen, but we shouldn't be failing if it does 2019 if (pkgSetting == null) { 2020 continue; 2021 } 2022 boolean install = enableApps.contains(pName); 2023 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2024 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2025 + " for system user"); 2026 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2027 } 2028 } 2029 } 2030 } 2031 2032 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2033 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2034 Context.DISPLAY_SERVICE); 2035 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2036 } 2037 2038 public PackageManagerService(Context context, Installer installer, 2039 boolean factoryTest, boolean onlyCore) { 2040 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2041 SystemClock.uptimeMillis()); 2042 2043 if (mSdkVersion <= 0) { 2044 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2045 } 2046 2047 mContext = context; 2048 mFactoryTest = factoryTest; 2049 mOnlyCore = onlyCore; 2050 mMetrics = new DisplayMetrics(); 2051 mSettings = new Settings(mPackages); 2052 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2053 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2054 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2055 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2056 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2057 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2058 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2059 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2060 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2061 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2062 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2063 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2064 2065 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2066 if (separateProcesses != null && separateProcesses.length() > 0) { 2067 if ("*".equals(separateProcesses)) { 2068 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2069 mSeparateProcesses = null; 2070 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2071 } else { 2072 mDefParseFlags = 0; 2073 mSeparateProcesses = separateProcesses.split(","); 2074 Slog.w(TAG, "Running with debug.separate_processes: " 2075 + separateProcesses); 2076 } 2077 } else { 2078 mDefParseFlags = 0; 2079 mSeparateProcesses = null; 2080 } 2081 2082 mInstaller = installer; 2083 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2084 "*dexopt*"); 2085 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2086 2087 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2088 FgThread.get().getLooper()); 2089 2090 getDefaultDisplayMetrics(context, mMetrics); 2091 2092 SystemConfig systemConfig = SystemConfig.getInstance(); 2093 mGlobalGids = systemConfig.getGlobalGids(); 2094 mSystemPermissions = systemConfig.getSystemPermissions(); 2095 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2096 2097 synchronized (mInstallLock) { 2098 // writer 2099 synchronized (mPackages) { 2100 mHandlerThread = new ServiceThread(TAG, 2101 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2102 mHandlerThread.start(); 2103 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2104 mProcessLoggingHandler = new ProcessLoggingHandler(); 2105 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2106 2107 File dataDir = Environment.getDataDirectory(); 2108 mAppInstallDir = new File(dataDir, "app"); 2109 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2110 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2111 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2112 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2113 2114 sUserManager = new UserManagerService(context, this, mPackages); 2115 2116 // Propagate permission configuration in to package manager. 2117 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2118 = systemConfig.getPermissions(); 2119 for (int i=0; i<permConfig.size(); i++) { 2120 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2121 BasePermission bp = mSettings.mPermissions.get(perm.name); 2122 if (bp == null) { 2123 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2124 mSettings.mPermissions.put(perm.name, bp); 2125 } 2126 if (perm.gids != null) { 2127 bp.setGids(perm.gids, perm.perUser); 2128 } 2129 } 2130 2131 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2132 for (int i=0; i<libConfig.size(); i++) { 2133 mSharedLibraries.put(libConfig.keyAt(i), 2134 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2135 } 2136 2137 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2138 2139 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2140 2141 String customResolverActivity = Resources.getSystem().getString( 2142 R.string.config_customResolverActivity); 2143 if (TextUtils.isEmpty(customResolverActivity)) { 2144 customResolverActivity = null; 2145 } else { 2146 mCustomResolverComponentName = ComponentName.unflattenFromString( 2147 customResolverActivity); 2148 } 2149 2150 long startTime = SystemClock.uptimeMillis(); 2151 2152 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2153 startTime); 2154 2155 // Set flag to monitor and not change apk file paths when 2156 // scanning install directories. 2157 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2158 2159 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2160 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2161 2162 if (bootClassPath == null) { 2163 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2164 } 2165 2166 if (systemServerClassPath == null) { 2167 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2168 } 2169 2170 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2171 final String[] dexCodeInstructionSets = 2172 getDexCodeInstructionSets( 2173 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2174 2175 /** 2176 * Ensure all external libraries have had dexopt run on them. 2177 */ 2178 if (mSharedLibraries.size() > 0) { 2179 // NOTE: For now, we're compiling these system "shared libraries" 2180 // (and framework jars) into all available architectures. It's possible 2181 // to compile them only when we come across an app that uses them (there's 2182 // already logic for that in scanPackageLI) but that adds some complexity. 2183 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2184 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2185 final String lib = libEntry.path; 2186 if (lib == null) { 2187 continue; 2188 } 2189 2190 try { 2191 // Shared libraries do not have profiles so we perform a full 2192 // AOT compilation (if needed). 2193 int dexoptNeeded = DexFile.getDexOptNeeded( 2194 lib, dexCodeInstructionSet, 2195 getCompilerFilterForReason(REASON_SHARED_APK), 2196 false /* newProfile */); 2197 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2198 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2199 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2200 getCompilerFilterForReason(REASON_SHARED_APK), 2201 StorageManager.UUID_PRIVATE_INTERNAL); 2202 } 2203 } catch (FileNotFoundException e) { 2204 Slog.w(TAG, "Library not found: " + lib); 2205 } catch (IOException | InstallerException e) { 2206 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2207 + e.getMessage()); 2208 } 2209 } 2210 } 2211 } 2212 2213 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2214 2215 final VersionInfo ver = mSettings.getInternalVersion(); 2216 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2217 2218 // when upgrading from pre-M, promote system app permissions from install to runtime 2219 mPromoteSystemApps = 2220 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2221 2222 // save off the names of pre-existing system packages prior to scanning; we don't 2223 // want to automatically grant runtime permissions for new system apps 2224 if (mPromoteSystemApps) { 2225 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2226 while (pkgSettingIter.hasNext()) { 2227 PackageSetting ps = pkgSettingIter.next(); 2228 if (isSystemApp(ps)) { 2229 mExistingSystemPackages.add(ps.name); 2230 } 2231 } 2232 } 2233 2234 // When upgrading from pre-N, we need to handle package extraction like first boot, 2235 // as there is no profiling data available. 2236 mIsPreNUpgrade = !mSettings.isNWorkDone(); 2237 mSettings.setNWorkDone(); 2238 2239 // Collect vendor overlay packages. 2240 // (Do this before scanning any apps.) 2241 // For security and version matching reason, only consider 2242 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2243 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2244 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2245 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2246 2247 // Find base frameworks (resource packages without code). 2248 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2249 | PackageParser.PARSE_IS_SYSTEM_DIR 2250 | PackageParser.PARSE_IS_PRIVILEGED, 2251 scanFlags | SCAN_NO_DEX, 0); 2252 2253 // Collected privileged system packages. 2254 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2255 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2256 | PackageParser.PARSE_IS_SYSTEM_DIR 2257 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2258 2259 // Collect ordinary system packages. 2260 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2261 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2262 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2263 2264 // Collect all vendor packages. 2265 File vendorAppDir = new File("/vendor/app"); 2266 try { 2267 vendorAppDir = vendorAppDir.getCanonicalFile(); 2268 } catch (IOException e) { 2269 // failed to look up canonical path, continue with original one 2270 } 2271 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2272 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2273 2274 // Collect all OEM packages. 2275 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2276 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2277 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2278 2279 // Prune any system packages that no longer exist. 2280 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2281 if (!mOnlyCore) { 2282 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2283 while (psit.hasNext()) { 2284 PackageSetting ps = psit.next(); 2285 2286 /* 2287 * If this is not a system app, it can't be a 2288 * disable system app. 2289 */ 2290 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2291 continue; 2292 } 2293 2294 /* 2295 * If the package is scanned, it's not erased. 2296 */ 2297 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2298 if (scannedPkg != null) { 2299 /* 2300 * If the system app is both scanned and in the 2301 * disabled packages list, then it must have been 2302 * added via OTA. Remove it from the currently 2303 * scanned package so the previously user-installed 2304 * application can be scanned. 2305 */ 2306 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2307 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2308 + ps.name + "; removing system app. Last known codePath=" 2309 + ps.codePathString + ", installStatus=" + ps.installStatus 2310 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2311 + scannedPkg.mVersionCode); 2312 removePackageLI(scannedPkg, true); 2313 mExpectingBetter.put(ps.name, ps.codePath); 2314 } 2315 2316 continue; 2317 } 2318 2319 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2320 psit.remove(); 2321 logCriticalInfo(Log.WARN, "System package " + ps.name 2322 + " no longer exists; wiping its data"); 2323 removeDataDirsLI(null, ps.name); 2324 } else { 2325 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2326 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2327 possiblyDeletedUpdatedSystemApps.add(ps.name); 2328 } 2329 } 2330 } 2331 } 2332 2333 //look for any incomplete package installations 2334 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2335 //clean up list 2336 for(int i = 0; i < deletePkgsList.size(); i++) { 2337 //clean up here 2338 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2339 } 2340 //delete tmp files 2341 deleteTempPackageFiles(); 2342 2343 // Remove any shared userIDs that have no associated packages 2344 mSettings.pruneSharedUsersLPw(); 2345 2346 if (!mOnlyCore) { 2347 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2348 SystemClock.uptimeMillis()); 2349 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2350 2351 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2352 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2353 2354 scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL, 2355 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2356 2357 /** 2358 * Remove disable package settings for any updated system 2359 * apps that were removed via an OTA. If they're not a 2360 * previously-updated app, remove them completely. 2361 * Otherwise, just revoke their system-level permissions. 2362 */ 2363 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2364 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2365 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2366 2367 String msg; 2368 if (deletedPkg == null) { 2369 msg = "Updated system package " + deletedAppName 2370 + " no longer exists; wiping its data"; 2371 removeDataDirsLI(null, deletedAppName); 2372 } else { 2373 msg = "Updated system app + " + deletedAppName 2374 + " no longer present; removing system privileges for " 2375 + deletedAppName; 2376 2377 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2378 2379 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2380 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2381 } 2382 logCriticalInfo(Log.WARN, msg); 2383 } 2384 2385 /** 2386 * Make sure all system apps that we expected to appear on 2387 * the userdata partition actually showed up. If they never 2388 * appeared, crawl back and revive the system version. 2389 */ 2390 for (int i = 0; i < mExpectingBetter.size(); i++) { 2391 final String packageName = mExpectingBetter.keyAt(i); 2392 if (!mPackages.containsKey(packageName)) { 2393 final File scanFile = mExpectingBetter.valueAt(i); 2394 2395 logCriticalInfo(Log.WARN, "Expected better " + packageName 2396 + " but never showed up; reverting to system"); 2397 2398 final int reparseFlags; 2399 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2400 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2401 | PackageParser.PARSE_IS_SYSTEM_DIR 2402 | PackageParser.PARSE_IS_PRIVILEGED; 2403 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2404 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2405 | PackageParser.PARSE_IS_SYSTEM_DIR; 2406 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2407 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2408 | PackageParser.PARSE_IS_SYSTEM_DIR; 2409 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2410 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2411 | PackageParser.PARSE_IS_SYSTEM_DIR; 2412 } else { 2413 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2414 continue; 2415 } 2416 2417 mSettings.enableSystemPackageLPw(packageName); 2418 2419 try { 2420 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2421 } catch (PackageManagerException e) { 2422 Slog.e(TAG, "Failed to parse original system package: " 2423 + e.getMessage()); 2424 } 2425 } 2426 } 2427 } 2428 mExpectingBetter.clear(); 2429 2430 // Now that we know all of the shared libraries, update all clients to have 2431 // the correct library paths. 2432 updateAllSharedLibrariesLPw(); 2433 2434 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2435 // NOTE: We ignore potential failures here during a system scan (like 2436 // the rest of the commands above) because there's precious little we 2437 // can do about it. A settings error is reported, though. 2438 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2439 false /* boot complete */); 2440 } 2441 2442 // Now that we know all the packages we are keeping, 2443 // read and update their last usage times. 2444 mPackageUsage.readLP(); 2445 2446 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2447 SystemClock.uptimeMillis()); 2448 Slog.i(TAG, "Time to scan packages: " 2449 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2450 + " seconds"); 2451 2452 // If the platform SDK has changed since the last time we booted, 2453 // we need to re-grant app permission to catch any new ones that 2454 // appear. This is really a hack, and means that apps can in some 2455 // cases get permissions that the user didn't initially explicitly 2456 // allow... it would be nice to have some better way to handle 2457 // this situation. 2458 int updateFlags = UPDATE_PERMISSIONS_ALL; 2459 if (ver.sdkVersion != mSdkVersion) { 2460 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2461 + mSdkVersion + "; regranting permissions for internal storage"); 2462 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2463 } 2464 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2465 ver.sdkVersion = mSdkVersion; 2466 2467 // If this is the first boot or an update from pre-M, and it is a normal 2468 // boot, then we need to initialize the default preferred apps across 2469 // all defined users. 2470 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2471 for (UserInfo user : sUserManager.getUsers(true)) { 2472 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2473 applyFactoryDefaultBrowserLPw(user.id); 2474 primeDomainVerificationsLPw(user.id); 2475 } 2476 } 2477 2478 // Prepare storage for system user really early during boot, 2479 // since core system apps like SettingsProvider and SystemUI 2480 // can't wait for user to start 2481 final int storageFlags; 2482 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2483 storageFlags = StorageManager.FLAG_STORAGE_DE; 2484 } else { 2485 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2486 } 2487 reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2488 storageFlags); 2489 2490 // If this is first boot after an OTA, and a normal boot, then 2491 // we need to clear code cache directories. 2492 if (mIsUpgrade && !onlyCore) { 2493 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2494 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2495 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2496 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2497 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2498 } 2499 } 2500 ver.fingerprint = Build.FINGERPRINT; 2501 } 2502 2503 checkDefaultBrowser(); 2504 2505 // clear only after permissions and other defaults have been updated 2506 mExistingSystemPackages.clear(); 2507 mPromoteSystemApps = false; 2508 2509 // All the changes are done during package scanning. 2510 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2511 2512 // can downgrade to reader 2513 mSettings.writeLPr(); 2514 2515 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2516 SystemClock.uptimeMillis()); 2517 2518 if (!mOnlyCore) { 2519 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2520 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2521 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2522 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2523 mIntentFilterVerifierComponent); 2524 } else { 2525 mRequiredVerifierPackage = null; 2526 mRequiredInstallerPackage = null; 2527 mIntentFilterVerifierComponent = null; 2528 mIntentFilterVerifier = null; 2529 } 2530 2531 mInstallerService = new PackageInstallerService(context, this); 2532 2533 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2534 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2535 // both the installer and resolver must be present to enable ephemeral 2536 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2537 if (DEBUG_EPHEMERAL) { 2538 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2539 + " installer:" + ephemeralInstallerComponent); 2540 } 2541 mEphemeralResolverComponent = ephemeralResolverComponent; 2542 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2543 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2544 mEphemeralResolverConnection = 2545 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2546 } else { 2547 if (DEBUG_EPHEMERAL) { 2548 final String missingComponent = 2549 (ephemeralResolverComponent == null) 2550 ? (ephemeralInstallerComponent == null) 2551 ? "resolver and installer" 2552 : "resolver" 2553 : "installer"; 2554 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2555 } 2556 mEphemeralResolverComponent = null; 2557 mEphemeralInstallerComponent = null; 2558 mEphemeralResolverConnection = null; 2559 } 2560 2561 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2562 } // synchronized (mPackages) 2563 } // synchronized (mInstallLock) 2564 2565 // Now after opening every single application zip, make sure they 2566 // are all flushed. Not really needed, but keeps things nice and 2567 // tidy. 2568 Runtime.getRuntime().gc(); 2569 2570 // The initial scanning above does many calls into installd while 2571 // holding the mPackages lock, but we're mostly interested in yelling 2572 // once we have a booted system. 2573 mInstaller.setWarnIfHeld(mPackages); 2574 2575 // Expose private service for system components to use. 2576 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2577 } 2578 2579 @Override 2580 public boolean isFirstBoot() { 2581 return !mRestoredSettings; 2582 } 2583 2584 @Override 2585 public boolean isOnlyCoreApps() { 2586 return mOnlyCore; 2587 } 2588 2589 @Override 2590 public boolean isUpgrade() { 2591 return mIsUpgrade; 2592 } 2593 2594 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2595 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2596 2597 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2598 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2599 UserHandle.USER_SYSTEM); 2600 if (matches.size() == 1) { 2601 return matches.get(0).getComponentInfo().packageName; 2602 } else { 2603 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2604 return null; 2605 } 2606 } 2607 2608 private @NonNull String getRequiredInstallerLPr() { 2609 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2610 intent.addCategory(Intent.CATEGORY_DEFAULT); 2611 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2612 2613 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2614 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2615 UserHandle.USER_SYSTEM); 2616 if (matches.size() == 1) { 2617 return matches.get(0).getComponentInfo().packageName; 2618 } else { 2619 throw new RuntimeException("There must be exactly one installer; found " + matches); 2620 } 2621 } 2622 2623 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2624 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2625 2626 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2627 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2628 UserHandle.USER_SYSTEM); 2629 ResolveInfo best = null; 2630 final int N = matches.size(); 2631 for (int i = 0; i < N; i++) { 2632 final ResolveInfo cur = matches.get(i); 2633 final String packageName = cur.getComponentInfo().packageName; 2634 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2635 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2636 continue; 2637 } 2638 2639 if (best == null || cur.priority > best.priority) { 2640 best = cur; 2641 } 2642 } 2643 2644 if (best != null) { 2645 return best.getComponentInfo().getComponentName(); 2646 } else { 2647 throw new RuntimeException("There must be at least one intent filter verifier"); 2648 } 2649 } 2650 2651 private @Nullable ComponentName getEphemeralResolverLPr() { 2652 final String[] packageArray = 2653 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2654 if (packageArray.length == 0) { 2655 if (DEBUG_EPHEMERAL) { 2656 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2657 } 2658 return null; 2659 } 2660 2661 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2662 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2663 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2664 UserHandle.USER_SYSTEM); 2665 2666 final int N = resolvers.size(); 2667 if (N == 0) { 2668 if (DEBUG_EPHEMERAL) { 2669 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2670 } 2671 return null; 2672 } 2673 2674 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2675 for (int i = 0; i < N; i++) { 2676 final ResolveInfo info = resolvers.get(i); 2677 2678 if (info.serviceInfo == null) { 2679 continue; 2680 } 2681 2682 final String packageName = info.serviceInfo.packageName; 2683 if (!possiblePackages.contains(packageName)) { 2684 if (DEBUG_EPHEMERAL) { 2685 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2686 + " pkg: " + packageName + ", info:" + info); 2687 } 2688 continue; 2689 } 2690 2691 if (DEBUG_EPHEMERAL) { 2692 Slog.v(TAG, "Ephemeral resolver found;" 2693 + " pkg: " + packageName + ", info:" + info); 2694 } 2695 return new ComponentName(packageName, info.serviceInfo.name); 2696 } 2697 if (DEBUG_EPHEMERAL) { 2698 Slog.v(TAG, "Ephemeral resolver NOT found"); 2699 } 2700 return null; 2701 } 2702 2703 private @Nullable ComponentName getEphemeralInstallerLPr() { 2704 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2705 intent.addCategory(Intent.CATEGORY_DEFAULT); 2706 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2707 2708 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2709 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2710 UserHandle.USER_SYSTEM); 2711 if (matches.size() == 0) { 2712 return null; 2713 } else if (matches.size() == 1) { 2714 return matches.get(0).getComponentInfo().getComponentName(); 2715 } else { 2716 throw new RuntimeException( 2717 "There must be at most one ephemeral installer; found " + matches); 2718 } 2719 } 2720 2721 private void primeDomainVerificationsLPw(int userId) { 2722 if (DEBUG_DOMAIN_VERIFICATION) { 2723 Slog.d(TAG, "Priming domain verifications in user " + userId); 2724 } 2725 2726 SystemConfig systemConfig = SystemConfig.getInstance(); 2727 ArraySet<String> packages = systemConfig.getLinkedApps(); 2728 ArraySet<String> domains = new ArraySet<String>(); 2729 2730 for (String packageName : packages) { 2731 PackageParser.Package pkg = mPackages.get(packageName); 2732 if (pkg != null) { 2733 if (!pkg.isSystemApp()) { 2734 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2735 continue; 2736 } 2737 2738 domains.clear(); 2739 for (PackageParser.Activity a : pkg.activities) { 2740 for (ActivityIntentInfo filter : a.intents) { 2741 if (hasValidDomains(filter)) { 2742 domains.addAll(filter.getHostsList()); 2743 } 2744 } 2745 } 2746 2747 if (domains.size() > 0) { 2748 if (DEBUG_DOMAIN_VERIFICATION) { 2749 Slog.v(TAG, " + " + packageName); 2750 } 2751 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2752 // state w.r.t. the formal app-linkage "no verification attempted" state; 2753 // and then 'always' in the per-user state actually used for intent resolution. 2754 final IntentFilterVerificationInfo ivi; 2755 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2756 new ArrayList<String>(domains)); 2757 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2758 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2759 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2760 } else { 2761 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2762 + "' does not handle web links"); 2763 } 2764 } else { 2765 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2766 } 2767 } 2768 2769 scheduleWritePackageRestrictionsLocked(userId); 2770 scheduleWriteSettingsLocked(); 2771 } 2772 2773 private void applyFactoryDefaultBrowserLPw(int userId) { 2774 // The default browser app's package name is stored in a string resource, 2775 // with a product-specific overlay used for vendor customization. 2776 String browserPkg = mContext.getResources().getString( 2777 com.android.internal.R.string.default_browser); 2778 if (!TextUtils.isEmpty(browserPkg)) { 2779 // non-empty string => required to be a known package 2780 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2781 if (ps == null) { 2782 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2783 browserPkg = null; 2784 } else { 2785 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2786 } 2787 } 2788 2789 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2790 // default. If there's more than one, just leave everything alone. 2791 if (browserPkg == null) { 2792 calculateDefaultBrowserLPw(userId); 2793 } 2794 } 2795 2796 private void calculateDefaultBrowserLPw(int userId) { 2797 List<String> allBrowsers = resolveAllBrowserApps(userId); 2798 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2799 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2800 } 2801 2802 private List<String> resolveAllBrowserApps(int userId) { 2803 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2804 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2805 PackageManager.MATCH_ALL, userId); 2806 2807 final int count = list.size(); 2808 List<String> result = new ArrayList<String>(count); 2809 for (int i=0; i<count; i++) { 2810 ResolveInfo info = list.get(i); 2811 if (info.activityInfo == null 2812 || !info.handleAllWebDataURI 2813 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2814 || result.contains(info.activityInfo.packageName)) { 2815 continue; 2816 } 2817 result.add(info.activityInfo.packageName); 2818 } 2819 2820 return result; 2821 } 2822 2823 private boolean packageIsBrowser(String packageName, int userId) { 2824 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2825 PackageManager.MATCH_ALL, userId); 2826 final int N = list.size(); 2827 for (int i = 0; i < N; i++) { 2828 ResolveInfo info = list.get(i); 2829 if (packageName.equals(info.activityInfo.packageName)) { 2830 return true; 2831 } 2832 } 2833 return false; 2834 } 2835 2836 private void checkDefaultBrowser() { 2837 final int myUserId = UserHandle.myUserId(); 2838 final String packageName = getDefaultBrowserPackageName(myUserId); 2839 if (packageName != null) { 2840 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2841 if (info == null) { 2842 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2843 synchronized (mPackages) { 2844 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2845 } 2846 } 2847 } 2848 } 2849 2850 @Override 2851 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2852 throws RemoteException { 2853 try { 2854 return super.onTransact(code, data, reply, flags); 2855 } catch (RuntimeException e) { 2856 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2857 Slog.wtf(TAG, "Package Manager Crash", e); 2858 } 2859 throw e; 2860 } 2861 } 2862 2863 void cleanupInstallFailedPackage(PackageSetting ps) { 2864 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2865 2866 removeDataDirsLI(ps.volumeUuid, ps.name); 2867 if (ps.codePath != null) { 2868 removeCodePathLI(ps.codePath); 2869 } 2870 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2871 if (ps.resourcePath.isDirectory()) { 2872 FileUtils.deleteContents(ps.resourcePath); 2873 } 2874 ps.resourcePath.delete(); 2875 } 2876 mSettings.removePackageLPw(ps.name); 2877 } 2878 2879 static int[] appendInts(int[] cur, int[] add) { 2880 if (add == null) return cur; 2881 if (cur == null) return add; 2882 final int N = add.length; 2883 for (int i=0; i<N; i++) { 2884 cur = appendInt(cur, add[i]); 2885 } 2886 return cur; 2887 } 2888 2889 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2890 if (!sUserManager.exists(userId)) return null; 2891 final PackageSetting ps = (PackageSetting) p.mExtras; 2892 if (ps == null) { 2893 return null; 2894 } 2895 2896 final PermissionsState permissionsState = ps.getPermissionsState(); 2897 2898 final int[] gids = permissionsState.computeGids(userId); 2899 final Set<String> permissions = permissionsState.getPermissions(userId); 2900 final PackageUserState state = ps.readUserState(userId); 2901 2902 return PackageParser.generatePackageInfo(p, gids, flags, 2903 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2904 } 2905 2906 @Override 2907 public void checkPackageStartable(String packageName, int userId) { 2908 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 2909 2910 synchronized (mPackages) { 2911 final PackageSetting ps = mSettings.mPackages.get(packageName); 2912 if (ps == null) { 2913 throw new SecurityException("Package " + packageName + " was not found!"); 2914 } 2915 2916 if (!ps.getInstalled(userId)) { 2917 throw new SecurityException( 2918 "Package " + packageName + " was not installed for user " + userId + "!"); 2919 } 2920 2921 if (mSafeMode && !ps.isSystem()) { 2922 throw new SecurityException("Package " + packageName + " not a system app!"); 2923 } 2924 2925 if (ps.frozen) { 2926 throw new SecurityException("Package " + packageName + " is currently frozen!"); 2927 } 2928 2929 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 2930 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 2931 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 2932 } 2933 } 2934 } 2935 2936 @Override 2937 public boolean isPackageAvailable(String packageName, int userId) { 2938 if (!sUserManager.exists(userId)) return false; 2939 enforceCrossUserPermission(Binder.getCallingUid(), userId, 2940 false /* requireFullPermission */, false /* checkShell */, "is package available"); 2941 synchronized (mPackages) { 2942 PackageParser.Package p = mPackages.get(packageName); 2943 if (p != null) { 2944 final PackageSetting ps = (PackageSetting) p.mExtras; 2945 if (ps != null) { 2946 final PackageUserState state = ps.readUserState(userId); 2947 if (state != null) { 2948 return PackageParser.isAvailable(state); 2949 } 2950 } 2951 } 2952 } 2953 return false; 2954 } 2955 2956 @Override 2957 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2958 if (!sUserManager.exists(userId)) return null; 2959 flags = updateFlagsForPackage(flags, userId, packageName); 2960 enforceCrossUserPermission(Binder.getCallingUid(), userId, 2961 false /* requireFullPermission */, false /* checkShell */, "get package info"); 2962 // reader 2963 synchronized (mPackages) { 2964 PackageParser.Package p = mPackages.get(packageName); 2965 if (DEBUG_PACKAGE_INFO) 2966 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2967 if (p != null) { 2968 return generatePackageInfo(p, flags, userId); 2969 } 2970 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2971 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2972 } 2973 } 2974 return null; 2975 } 2976 2977 @Override 2978 public String[] currentToCanonicalPackageNames(String[] names) { 2979 String[] out = new String[names.length]; 2980 // reader 2981 synchronized (mPackages) { 2982 for (int i=names.length-1; i>=0; i--) { 2983 PackageSetting ps = mSettings.mPackages.get(names[i]); 2984 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2985 } 2986 } 2987 return out; 2988 } 2989 2990 @Override 2991 public String[] canonicalToCurrentPackageNames(String[] names) { 2992 String[] out = new String[names.length]; 2993 // reader 2994 synchronized (mPackages) { 2995 for (int i=names.length-1; i>=0; i--) { 2996 String cur = mSettings.mRenamedPackages.get(names[i]); 2997 out[i] = cur != null ? cur : names[i]; 2998 } 2999 } 3000 return out; 3001 } 3002 3003 @Override 3004 public int getPackageUid(String packageName, int flags, int userId) { 3005 if (!sUserManager.exists(userId)) return -1; 3006 flags = updateFlagsForPackage(flags, userId, packageName); 3007 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3008 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3009 3010 // reader 3011 synchronized (mPackages) { 3012 final PackageParser.Package p = mPackages.get(packageName); 3013 if (p != null && p.isMatch(flags)) { 3014 return UserHandle.getUid(userId, p.applicationInfo.uid); 3015 } 3016 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3017 final PackageSetting ps = mSettings.mPackages.get(packageName); 3018 if (ps != null && ps.isMatch(flags)) { 3019 return UserHandle.getUid(userId, ps.appId); 3020 } 3021 } 3022 } 3023 3024 return -1; 3025 } 3026 3027 @Override 3028 public int[] getPackageGids(String packageName, int flags, int userId) { 3029 if (!sUserManager.exists(userId)) return null; 3030 flags = updateFlagsForPackage(flags, userId, packageName); 3031 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3032 false /* requireFullPermission */, false /* checkShell */, 3033 "getPackageGids"); 3034 3035 // reader 3036 synchronized (mPackages) { 3037 final PackageParser.Package p = mPackages.get(packageName); 3038 if (p != null && p.isMatch(flags)) { 3039 PackageSetting ps = (PackageSetting) p.mExtras; 3040 return ps.getPermissionsState().computeGids(userId); 3041 } 3042 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3043 final PackageSetting ps = mSettings.mPackages.get(packageName); 3044 if (ps != null && ps.isMatch(flags)) { 3045 return ps.getPermissionsState().computeGids(userId); 3046 } 3047 } 3048 } 3049 3050 return null; 3051 } 3052 3053 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3054 if (bp.perm != null) { 3055 return PackageParser.generatePermissionInfo(bp.perm, flags); 3056 } 3057 PermissionInfo pi = new PermissionInfo(); 3058 pi.name = bp.name; 3059 pi.packageName = bp.sourcePackage; 3060 pi.nonLocalizedLabel = bp.name; 3061 pi.protectionLevel = bp.protectionLevel; 3062 return pi; 3063 } 3064 3065 @Override 3066 public PermissionInfo getPermissionInfo(String name, int flags) { 3067 // reader 3068 synchronized (mPackages) { 3069 final BasePermission p = mSettings.mPermissions.get(name); 3070 if (p != null) { 3071 return generatePermissionInfo(p, flags); 3072 } 3073 return null; 3074 } 3075 } 3076 3077 @Override 3078 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3079 int flags) { 3080 // reader 3081 synchronized (mPackages) { 3082 if (group != null && !mPermissionGroups.containsKey(group)) { 3083 // This is thrown as NameNotFoundException 3084 return null; 3085 } 3086 3087 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3088 for (BasePermission p : mSettings.mPermissions.values()) { 3089 if (group == null) { 3090 if (p.perm == null || p.perm.info.group == null) { 3091 out.add(generatePermissionInfo(p, flags)); 3092 } 3093 } else { 3094 if (p.perm != null && group.equals(p.perm.info.group)) { 3095 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3096 } 3097 } 3098 } 3099 return new ParceledListSlice<>(out); 3100 } 3101 } 3102 3103 @Override 3104 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3105 // reader 3106 synchronized (mPackages) { 3107 return PackageParser.generatePermissionGroupInfo( 3108 mPermissionGroups.get(name), flags); 3109 } 3110 } 3111 3112 @Override 3113 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3114 // reader 3115 synchronized (mPackages) { 3116 final int N = mPermissionGroups.size(); 3117 ArrayList<PermissionGroupInfo> out 3118 = new ArrayList<PermissionGroupInfo>(N); 3119 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3120 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3121 } 3122 return new ParceledListSlice<>(out); 3123 } 3124 } 3125 3126 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3127 int userId) { 3128 if (!sUserManager.exists(userId)) return null; 3129 PackageSetting ps = mSettings.mPackages.get(packageName); 3130 if (ps != null) { 3131 if (ps.pkg == null) { 3132 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 3133 flags, userId); 3134 if (pInfo != null) { 3135 return pInfo.applicationInfo; 3136 } 3137 return null; 3138 } 3139 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3140 ps.readUserState(userId), userId); 3141 } 3142 return null; 3143 } 3144 3145 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 3146 int userId) { 3147 if (!sUserManager.exists(userId)) return null; 3148 PackageSetting ps = mSettings.mPackages.get(packageName); 3149 if (ps != null) { 3150 PackageParser.Package pkg = ps.pkg; 3151 if (pkg == null) { 3152 if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) { 3153 return null; 3154 } 3155 // Only data remains, so we aren't worried about code paths 3156 pkg = new PackageParser.Package(packageName); 3157 pkg.applicationInfo.packageName = packageName; 3158 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 3159 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 3160 pkg.applicationInfo.uid = ps.appId; 3161 pkg.applicationInfo.initForUser(userId); 3162 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 3163 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 3164 } 3165 return generatePackageInfo(pkg, flags, userId); 3166 } 3167 return null; 3168 } 3169 3170 @Override 3171 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3172 if (!sUserManager.exists(userId)) return null; 3173 flags = updateFlagsForApplication(flags, userId, packageName); 3174 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3175 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3176 // writer 3177 synchronized (mPackages) { 3178 PackageParser.Package p = mPackages.get(packageName); 3179 if (DEBUG_PACKAGE_INFO) Log.v( 3180 TAG, "getApplicationInfo " + packageName 3181 + ": " + p); 3182 if (p != null) { 3183 PackageSetting ps = mSettings.mPackages.get(packageName); 3184 if (ps == null) return null; 3185 // Note: isEnabledLP() does not apply here - always return info 3186 return PackageParser.generateApplicationInfo( 3187 p, flags, ps.readUserState(userId), userId); 3188 } 3189 if ("android".equals(packageName)||"system".equals(packageName)) { 3190 return mAndroidApplication; 3191 } 3192 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3193 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3194 } 3195 } 3196 return null; 3197 } 3198 3199 @Override 3200 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3201 final IPackageDataObserver observer) { 3202 mContext.enforceCallingOrSelfPermission( 3203 android.Manifest.permission.CLEAR_APP_CACHE, null); 3204 // Queue up an async operation since clearing cache may take a little while. 3205 mHandler.post(new Runnable() { 3206 public void run() { 3207 mHandler.removeCallbacks(this); 3208 boolean success = true; 3209 synchronized (mInstallLock) { 3210 try { 3211 mInstaller.freeCache(volumeUuid, freeStorageSize); 3212 } catch (InstallerException e) { 3213 Slog.w(TAG, "Couldn't clear application caches: " + e); 3214 success = false; 3215 } 3216 } 3217 if (observer != null) { 3218 try { 3219 observer.onRemoveCompleted(null, success); 3220 } catch (RemoteException e) { 3221 Slog.w(TAG, "RemoveException when invoking call back"); 3222 } 3223 } 3224 } 3225 }); 3226 } 3227 3228 @Override 3229 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3230 final IntentSender pi) { 3231 mContext.enforceCallingOrSelfPermission( 3232 android.Manifest.permission.CLEAR_APP_CACHE, null); 3233 // Queue up an async operation since clearing cache may take a little while. 3234 mHandler.post(new Runnable() { 3235 public void run() { 3236 mHandler.removeCallbacks(this); 3237 boolean success = true; 3238 synchronized (mInstallLock) { 3239 try { 3240 mInstaller.freeCache(volumeUuid, freeStorageSize); 3241 } catch (InstallerException e) { 3242 Slog.w(TAG, "Couldn't clear application caches: " + e); 3243 success = false; 3244 } 3245 } 3246 if(pi != null) { 3247 try { 3248 // Callback via pending intent 3249 int code = success ? 1 : 0; 3250 pi.sendIntent(null, code, null, 3251 null, null); 3252 } catch (SendIntentException e1) { 3253 Slog.i(TAG, "Failed to send pending intent"); 3254 } 3255 } 3256 } 3257 }); 3258 } 3259 3260 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3261 synchronized (mInstallLock) { 3262 try { 3263 mInstaller.freeCache(volumeUuid, freeStorageSize); 3264 } catch (InstallerException e) { 3265 throw new IOException("Failed to free enough space", e); 3266 } 3267 } 3268 } 3269 3270 /** 3271 * Return if the user key is currently unlocked. 3272 */ 3273 private boolean isUserKeyUnlocked(int userId) { 3274 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 3275 final IMountService mount = IMountService.Stub 3276 .asInterface(ServiceManager.getService("mount")); 3277 if (mount == null) { 3278 Slog.w(TAG, "Early during boot, assuming locked"); 3279 return false; 3280 } 3281 final long token = Binder.clearCallingIdentity(); 3282 try { 3283 return mount.isUserKeyUnlocked(userId); 3284 } catch (RemoteException e) { 3285 throw e.rethrowAsRuntimeException(); 3286 } finally { 3287 Binder.restoreCallingIdentity(token); 3288 } 3289 } else { 3290 return true; 3291 } 3292 } 3293 3294 /** 3295 * Update given flags based on encryption status of current user. 3296 */ 3297 private int updateFlags(int flags, int userId) { 3298 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3299 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3300 // Caller expressed an explicit opinion about what encryption 3301 // aware/unaware components they want to see, so fall through and 3302 // give them what they want 3303 } else { 3304 // Caller expressed no opinion, so match based on user state 3305 if (isUserKeyUnlocked(userId)) { 3306 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3307 } else { 3308 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3309 } 3310 } 3311 return flags; 3312 } 3313 3314 /** 3315 * Update given flags when being used to request {@link PackageInfo}. 3316 */ 3317 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3318 boolean triaged = true; 3319 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3320 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3321 // Caller is asking for component details, so they'd better be 3322 // asking for specific encryption matching behavior, or be triaged 3323 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3324 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3325 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3326 triaged = false; 3327 } 3328 } 3329 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3330 | PackageManager.MATCH_SYSTEM_ONLY 3331 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3332 triaged = false; 3333 } 3334 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3335 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3336 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3337 } 3338 return updateFlags(flags, userId); 3339 } 3340 3341 /** 3342 * Update given flags when being used to request {@link ApplicationInfo}. 3343 */ 3344 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3345 return updateFlagsForPackage(flags, userId, cookie); 3346 } 3347 3348 /** 3349 * Update given flags when being used to request {@link ComponentInfo}. 3350 */ 3351 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3352 if (cookie instanceof Intent) { 3353 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3354 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3355 } 3356 } 3357 3358 boolean triaged = true; 3359 // Caller is asking for component details, so they'd better be 3360 // asking for specific encryption matching behavior, or be triaged 3361 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3362 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3363 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3364 triaged = false; 3365 } 3366 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3367 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3368 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3369 } 3370 3371 return updateFlags(flags, userId); 3372 } 3373 3374 /** 3375 * Update given flags when being used to request {@link ResolveInfo}. 3376 */ 3377 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3378 // Safe mode means we shouldn't match any third-party components 3379 if (mSafeMode) { 3380 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3381 } 3382 3383 return updateFlagsForComponent(flags, userId, cookie); 3384 } 3385 3386 @Override 3387 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3388 if (!sUserManager.exists(userId)) return null; 3389 flags = updateFlagsForComponent(flags, userId, component); 3390 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3391 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3392 synchronized (mPackages) { 3393 PackageParser.Activity a = mActivities.mActivities.get(component); 3394 3395 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3396 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3397 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3398 if (ps == null) return null; 3399 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3400 userId); 3401 } 3402 if (mResolveComponentName.equals(component)) { 3403 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3404 new PackageUserState(), userId); 3405 } 3406 } 3407 return null; 3408 } 3409 3410 @Override 3411 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3412 String resolvedType) { 3413 synchronized (mPackages) { 3414 if (component.equals(mResolveComponentName)) { 3415 // The resolver supports EVERYTHING! 3416 return true; 3417 } 3418 PackageParser.Activity a = mActivities.mActivities.get(component); 3419 if (a == null) { 3420 return false; 3421 } 3422 for (int i=0; i<a.intents.size(); i++) { 3423 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3424 intent.getData(), intent.getCategories(), TAG) >= 0) { 3425 return true; 3426 } 3427 } 3428 return false; 3429 } 3430 } 3431 3432 @Override 3433 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3434 if (!sUserManager.exists(userId)) return null; 3435 flags = updateFlagsForComponent(flags, userId, component); 3436 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3437 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3438 synchronized (mPackages) { 3439 PackageParser.Activity a = mReceivers.mActivities.get(component); 3440 if (DEBUG_PACKAGE_INFO) Log.v( 3441 TAG, "getReceiverInfo " + component + ": " + a); 3442 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3443 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3444 if (ps == null) return null; 3445 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3446 userId); 3447 } 3448 } 3449 return null; 3450 } 3451 3452 @Override 3453 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3454 if (!sUserManager.exists(userId)) return null; 3455 flags = updateFlagsForComponent(flags, userId, component); 3456 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3457 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3458 synchronized (mPackages) { 3459 PackageParser.Service s = mServices.mServices.get(component); 3460 if (DEBUG_PACKAGE_INFO) Log.v( 3461 TAG, "getServiceInfo " + component + ": " + s); 3462 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3463 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3464 if (ps == null) return null; 3465 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3466 userId); 3467 } 3468 } 3469 return null; 3470 } 3471 3472 @Override 3473 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3474 if (!sUserManager.exists(userId)) return null; 3475 flags = updateFlagsForComponent(flags, userId, component); 3476 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3477 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3478 synchronized (mPackages) { 3479 PackageParser.Provider p = mProviders.mProviders.get(component); 3480 if (DEBUG_PACKAGE_INFO) Log.v( 3481 TAG, "getProviderInfo " + component + ": " + p); 3482 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3483 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3484 if (ps == null) return null; 3485 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3486 userId); 3487 } 3488 } 3489 return null; 3490 } 3491 3492 @Override 3493 public String[] getSystemSharedLibraryNames() { 3494 Set<String> libSet; 3495 synchronized (mPackages) { 3496 libSet = mSharedLibraries.keySet(); 3497 int size = libSet.size(); 3498 if (size > 0) { 3499 String[] libs = new String[size]; 3500 libSet.toArray(libs); 3501 return libs; 3502 } 3503 } 3504 return null; 3505 } 3506 3507 @Override 3508 public @Nullable String getServicesSystemSharedLibraryPackageName() { 3509 synchronized (mPackages) { 3510 SharedLibraryEntry libraryEntry = mSharedLibraries.get( 3511 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 3512 if (libraryEntry != null) { 3513 return libraryEntry.apk; 3514 } 3515 } 3516 return null; 3517 } 3518 3519 @Override 3520 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3521 synchronized (mPackages) { 3522 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3523 3524 final FeatureInfo fi = new FeatureInfo(); 3525 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3526 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3527 res.add(fi); 3528 3529 return new ParceledListSlice<>(res); 3530 } 3531 } 3532 3533 @Override 3534 public boolean hasSystemFeature(String name, int version) { 3535 synchronized (mPackages) { 3536 final FeatureInfo feat = mAvailableFeatures.get(name); 3537 if (feat == null) { 3538 return false; 3539 } else { 3540 return feat.version >= version; 3541 } 3542 } 3543 } 3544 3545 @Override 3546 public int checkPermission(String permName, String pkgName, int userId) { 3547 if (!sUserManager.exists(userId)) { 3548 return PackageManager.PERMISSION_DENIED; 3549 } 3550 3551 synchronized (mPackages) { 3552 final PackageParser.Package p = mPackages.get(pkgName); 3553 if (p != null && p.mExtras != null) { 3554 final PackageSetting ps = (PackageSetting) p.mExtras; 3555 final PermissionsState permissionsState = ps.getPermissionsState(); 3556 if (permissionsState.hasPermission(permName, userId)) { 3557 return PackageManager.PERMISSION_GRANTED; 3558 } 3559 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3560 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3561 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3562 return PackageManager.PERMISSION_GRANTED; 3563 } 3564 } 3565 } 3566 3567 return PackageManager.PERMISSION_DENIED; 3568 } 3569 3570 @Override 3571 public int checkUidPermission(String permName, int uid) { 3572 final int userId = UserHandle.getUserId(uid); 3573 3574 if (!sUserManager.exists(userId)) { 3575 return PackageManager.PERMISSION_DENIED; 3576 } 3577 3578 synchronized (mPackages) { 3579 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3580 if (obj != null) { 3581 final SettingBase ps = (SettingBase) obj; 3582 final PermissionsState permissionsState = ps.getPermissionsState(); 3583 if (permissionsState.hasPermission(permName, userId)) { 3584 return PackageManager.PERMISSION_GRANTED; 3585 } 3586 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3587 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3588 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3589 return PackageManager.PERMISSION_GRANTED; 3590 } 3591 } else { 3592 ArraySet<String> perms = mSystemPermissions.get(uid); 3593 if (perms != null) { 3594 if (perms.contains(permName)) { 3595 return PackageManager.PERMISSION_GRANTED; 3596 } 3597 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3598 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3599 return PackageManager.PERMISSION_GRANTED; 3600 } 3601 } 3602 } 3603 } 3604 3605 return PackageManager.PERMISSION_DENIED; 3606 } 3607 3608 @Override 3609 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3610 if (UserHandle.getCallingUserId() != userId) { 3611 mContext.enforceCallingPermission( 3612 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3613 "isPermissionRevokedByPolicy for user " + userId); 3614 } 3615 3616 if (checkPermission(permission, packageName, userId) 3617 == PackageManager.PERMISSION_GRANTED) { 3618 return false; 3619 } 3620 3621 final long identity = Binder.clearCallingIdentity(); 3622 try { 3623 final int flags = getPermissionFlags(permission, packageName, userId); 3624 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3625 } finally { 3626 Binder.restoreCallingIdentity(identity); 3627 } 3628 } 3629 3630 @Override 3631 public String getPermissionControllerPackageName() { 3632 synchronized (mPackages) { 3633 return mRequiredInstallerPackage; 3634 } 3635 } 3636 3637 /** 3638 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3639 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3640 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3641 * @param message the message to log on security exception 3642 */ 3643 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3644 boolean checkShell, String message) { 3645 if (userId < 0) { 3646 throw new IllegalArgumentException("Invalid userId " + userId); 3647 } 3648 if (checkShell) { 3649 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3650 } 3651 if (userId == UserHandle.getUserId(callingUid)) return; 3652 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3653 if (requireFullPermission) { 3654 mContext.enforceCallingOrSelfPermission( 3655 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3656 } else { 3657 try { 3658 mContext.enforceCallingOrSelfPermission( 3659 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3660 } catch (SecurityException se) { 3661 mContext.enforceCallingOrSelfPermission( 3662 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3663 } 3664 } 3665 } 3666 } 3667 3668 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3669 if (callingUid == Process.SHELL_UID) { 3670 if (userHandle >= 0 3671 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3672 throw new SecurityException("Shell does not have permission to access user " 3673 + userHandle); 3674 } else if (userHandle < 0) { 3675 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3676 + Debug.getCallers(3)); 3677 } 3678 } 3679 } 3680 3681 private BasePermission findPermissionTreeLP(String permName) { 3682 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3683 if (permName.startsWith(bp.name) && 3684 permName.length() > bp.name.length() && 3685 permName.charAt(bp.name.length()) == '.') { 3686 return bp; 3687 } 3688 } 3689 return null; 3690 } 3691 3692 private BasePermission checkPermissionTreeLP(String permName) { 3693 if (permName != null) { 3694 BasePermission bp = findPermissionTreeLP(permName); 3695 if (bp != null) { 3696 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3697 return bp; 3698 } 3699 throw new SecurityException("Calling uid " 3700 + Binder.getCallingUid() 3701 + " is not allowed to add to permission tree " 3702 + bp.name + " owned by uid " + bp.uid); 3703 } 3704 } 3705 throw new SecurityException("No permission tree found for " + permName); 3706 } 3707 3708 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3709 if (s1 == null) { 3710 return s2 == null; 3711 } 3712 if (s2 == null) { 3713 return false; 3714 } 3715 if (s1.getClass() != s2.getClass()) { 3716 return false; 3717 } 3718 return s1.equals(s2); 3719 } 3720 3721 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3722 if (pi1.icon != pi2.icon) return false; 3723 if (pi1.logo != pi2.logo) return false; 3724 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3725 if (!compareStrings(pi1.name, pi2.name)) return false; 3726 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3727 // We'll take care of setting this one. 3728 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3729 // These are not currently stored in settings. 3730 //if (!compareStrings(pi1.group, pi2.group)) return false; 3731 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3732 //if (pi1.labelRes != pi2.labelRes) return false; 3733 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3734 return true; 3735 } 3736 3737 int permissionInfoFootprint(PermissionInfo info) { 3738 int size = info.name.length(); 3739 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3740 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3741 return size; 3742 } 3743 3744 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3745 int size = 0; 3746 for (BasePermission perm : mSettings.mPermissions.values()) { 3747 if (perm.uid == tree.uid) { 3748 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3749 } 3750 } 3751 return size; 3752 } 3753 3754 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3755 // We calculate the max size of permissions defined by this uid and throw 3756 // if that plus the size of 'info' would exceed our stated maximum. 3757 if (tree.uid != Process.SYSTEM_UID) { 3758 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3759 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3760 throw new SecurityException("Permission tree size cap exceeded"); 3761 } 3762 } 3763 } 3764 3765 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3766 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3767 throw new SecurityException("Label must be specified in permission"); 3768 } 3769 BasePermission tree = checkPermissionTreeLP(info.name); 3770 BasePermission bp = mSettings.mPermissions.get(info.name); 3771 boolean added = bp == null; 3772 boolean changed = true; 3773 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3774 if (added) { 3775 enforcePermissionCapLocked(info, tree); 3776 bp = new BasePermission(info.name, tree.sourcePackage, 3777 BasePermission.TYPE_DYNAMIC); 3778 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3779 throw new SecurityException( 3780 "Not allowed to modify non-dynamic permission " 3781 + info.name); 3782 } else { 3783 if (bp.protectionLevel == fixedLevel 3784 && bp.perm.owner.equals(tree.perm.owner) 3785 && bp.uid == tree.uid 3786 && comparePermissionInfos(bp.perm.info, info)) { 3787 changed = false; 3788 } 3789 } 3790 bp.protectionLevel = fixedLevel; 3791 info = new PermissionInfo(info); 3792 info.protectionLevel = fixedLevel; 3793 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3794 bp.perm.info.packageName = tree.perm.info.packageName; 3795 bp.uid = tree.uid; 3796 if (added) { 3797 mSettings.mPermissions.put(info.name, bp); 3798 } 3799 if (changed) { 3800 if (!async) { 3801 mSettings.writeLPr(); 3802 } else { 3803 scheduleWriteSettingsLocked(); 3804 } 3805 } 3806 return added; 3807 } 3808 3809 @Override 3810 public boolean addPermission(PermissionInfo info) { 3811 synchronized (mPackages) { 3812 return addPermissionLocked(info, false); 3813 } 3814 } 3815 3816 @Override 3817 public boolean addPermissionAsync(PermissionInfo info) { 3818 synchronized (mPackages) { 3819 return addPermissionLocked(info, true); 3820 } 3821 } 3822 3823 @Override 3824 public void removePermission(String name) { 3825 synchronized (mPackages) { 3826 checkPermissionTreeLP(name); 3827 BasePermission bp = mSettings.mPermissions.get(name); 3828 if (bp != null) { 3829 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3830 throw new SecurityException( 3831 "Not allowed to modify non-dynamic permission " 3832 + name); 3833 } 3834 mSettings.mPermissions.remove(name); 3835 mSettings.writeLPr(); 3836 } 3837 } 3838 } 3839 3840 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3841 BasePermission bp) { 3842 int index = pkg.requestedPermissions.indexOf(bp.name); 3843 if (index == -1) { 3844 throw new SecurityException("Package " + pkg.packageName 3845 + " has not requested permission " + bp.name); 3846 } 3847 if (!bp.isRuntime() && !bp.isDevelopment()) { 3848 throw new SecurityException("Permission " + bp.name 3849 + " is not a changeable permission type"); 3850 } 3851 } 3852 3853 @Override 3854 public void grantRuntimePermission(String packageName, String name, final int userId) { 3855 if (!sUserManager.exists(userId)) { 3856 Log.e(TAG, "No such user:" + userId); 3857 return; 3858 } 3859 3860 mContext.enforceCallingOrSelfPermission( 3861 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3862 "grantRuntimePermission"); 3863 3864 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3865 true /* requireFullPermission */, true /* checkShell */, 3866 "grantRuntimePermission"); 3867 3868 final int uid; 3869 final SettingBase sb; 3870 3871 synchronized (mPackages) { 3872 final PackageParser.Package pkg = mPackages.get(packageName); 3873 if (pkg == null) { 3874 throw new IllegalArgumentException("Unknown package: " + packageName); 3875 } 3876 3877 final BasePermission bp = mSettings.mPermissions.get(name); 3878 if (bp == null) { 3879 throw new IllegalArgumentException("Unknown permission: " + name); 3880 } 3881 3882 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3883 3884 // If a permission review is required for legacy apps we represent 3885 // their permissions as always granted runtime ones since we need 3886 // to keep the review required permission flag per user while an 3887 // install permission's state is shared across all users. 3888 if (Build.PERMISSIONS_REVIEW_REQUIRED 3889 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3890 && bp.isRuntime()) { 3891 return; 3892 } 3893 3894 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3895 sb = (SettingBase) pkg.mExtras; 3896 if (sb == null) { 3897 throw new IllegalArgumentException("Unknown package: " + packageName); 3898 } 3899 3900 final PermissionsState permissionsState = sb.getPermissionsState(); 3901 3902 final int flags = permissionsState.getPermissionFlags(name, userId); 3903 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3904 throw new SecurityException("Cannot grant system fixed permission " 3905 + name + " for package " + packageName); 3906 } 3907 3908 if (bp.isDevelopment()) { 3909 // Development permissions must be handled specially, since they are not 3910 // normal runtime permissions. For now they apply to all users. 3911 if (permissionsState.grantInstallPermission(bp) != 3912 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3913 scheduleWriteSettingsLocked(); 3914 } 3915 return; 3916 } 3917 3918 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 3919 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 3920 return; 3921 } 3922 3923 final int result = permissionsState.grantRuntimePermission(bp, userId); 3924 switch (result) { 3925 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3926 return; 3927 } 3928 3929 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3930 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3931 mHandler.post(new Runnable() { 3932 @Override 3933 public void run() { 3934 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3935 } 3936 }); 3937 } 3938 break; 3939 } 3940 3941 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3942 3943 // Not critical if that is lost - app has to request again. 3944 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3945 } 3946 3947 // Only need to do this if user is initialized. Otherwise it's a new user 3948 // and there are no processes running as the user yet and there's no need 3949 // to make an expensive call to remount processes for the changed permissions. 3950 if (READ_EXTERNAL_STORAGE.equals(name) 3951 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3952 final long token = Binder.clearCallingIdentity(); 3953 try { 3954 if (sUserManager.isInitialized(userId)) { 3955 MountServiceInternal mountServiceInternal = LocalServices.getService( 3956 MountServiceInternal.class); 3957 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3958 } 3959 } finally { 3960 Binder.restoreCallingIdentity(token); 3961 } 3962 } 3963 } 3964 3965 @Override 3966 public void revokeRuntimePermission(String packageName, String name, int userId) { 3967 if (!sUserManager.exists(userId)) { 3968 Log.e(TAG, "No such user:" + userId); 3969 return; 3970 } 3971 3972 mContext.enforceCallingOrSelfPermission( 3973 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3974 "revokeRuntimePermission"); 3975 3976 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3977 true /* requireFullPermission */, true /* checkShell */, 3978 "revokeRuntimePermission"); 3979 3980 final int appId; 3981 3982 synchronized (mPackages) { 3983 final PackageParser.Package pkg = mPackages.get(packageName); 3984 if (pkg == null) { 3985 throw new IllegalArgumentException("Unknown package: " + packageName); 3986 } 3987 3988 final BasePermission bp = mSettings.mPermissions.get(name); 3989 if (bp == null) { 3990 throw new IllegalArgumentException("Unknown permission: " + name); 3991 } 3992 3993 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3994 3995 // If a permission review is required for legacy apps we represent 3996 // their permissions as always granted runtime ones since we need 3997 // to keep the review required permission flag per user while an 3998 // install permission's state is shared across all users. 3999 if (Build.PERMISSIONS_REVIEW_REQUIRED 4000 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4001 && bp.isRuntime()) { 4002 return; 4003 } 4004 4005 SettingBase sb = (SettingBase) pkg.mExtras; 4006 if (sb == null) { 4007 throw new IllegalArgumentException("Unknown package: " + packageName); 4008 } 4009 4010 final PermissionsState permissionsState = sb.getPermissionsState(); 4011 4012 final int flags = permissionsState.getPermissionFlags(name, userId); 4013 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4014 throw new SecurityException("Cannot revoke system fixed permission " 4015 + name + " for package " + packageName); 4016 } 4017 4018 if (bp.isDevelopment()) { 4019 // Development permissions must be handled specially, since they are not 4020 // normal runtime permissions. For now they apply to all users. 4021 if (permissionsState.revokeInstallPermission(bp) != 4022 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4023 scheduleWriteSettingsLocked(); 4024 } 4025 return; 4026 } 4027 4028 if (permissionsState.revokeRuntimePermission(bp, userId) == 4029 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4030 return; 4031 } 4032 4033 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4034 4035 // Critical, after this call app should never have the permission. 4036 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4037 4038 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4039 } 4040 4041 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4042 } 4043 4044 @Override 4045 public void resetRuntimePermissions() { 4046 mContext.enforceCallingOrSelfPermission( 4047 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4048 "revokeRuntimePermission"); 4049 4050 int callingUid = Binder.getCallingUid(); 4051 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4052 mContext.enforceCallingOrSelfPermission( 4053 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4054 "resetRuntimePermissions"); 4055 } 4056 4057 synchronized (mPackages) { 4058 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4059 for (int userId : UserManagerService.getInstance().getUserIds()) { 4060 final int packageCount = mPackages.size(); 4061 for (int i = 0; i < packageCount; i++) { 4062 PackageParser.Package pkg = mPackages.valueAt(i); 4063 if (!(pkg.mExtras instanceof PackageSetting)) { 4064 continue; 4065 } 4066 PackageSetting ps = (PackageSetting) pkg.mExtras; 4067 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4068 } 4069 } 4070 } 4071 } 4072 4073 @Override 4074 public int getPermissionFlags(String name, String packageName, int userId) { 4075 if (!sUserManager.exists(userId)) { 4076 return 0; 4077 } 4078 4079 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4080 4081 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4082 true /* requireFullPermission */, false /* checkShell */, 4083 "getPermissionFlags"); 4084 4085 synchronized (mPackages) { 4086 final PackageParser.Package pkg = mPackages.get(packageName); 4087 if (pkg == null) { 4088 throw new IllegalArgumentException("Unknown package: " + packageName); 4089 } 4090 4091 final BasePermission bp = mSettings.mPermissions.get(name); 4092 if (bp == null) { 4093 throw new IllegalArgumentException("Unknown permission: " + name); 4094 } 4095 4096 SettingBase sb = (SettingBase) pkg.mExtras; 4097 if (sb == null) { 4098 throw new IllegalArgumentException("Unknown package: " + packageName); 4099 } 4100 4101 PermissionsState permissionsState = sb.getPermissionsState(); 4102 return permissionsState.getPermissionFlags(name, userId); 4103 } 4104 } 4105 4106 @Override 4107 public void updatePermissionFlags(String name, String packageName, int flagMask, 4108 int flagValues, int userId) { 4109 if (!sUserManager.exists(userId)) { 4110 return; 4111 } 4112 4113 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4114 4115 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4116 true /* requireFullPermission */, true /* checkShell */, 4117 "updatePermissionFlags"); 4118 4119 // Only the system can change these flags and nothing else. 4120 if (getCallingUid() != Process.SYSTEM_UID) { 4121 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4122 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4123 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4124 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4125 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4126 } 4127 4128 synchronized (mPackages) { 4129 final PackageParser.Package pkg = mPackages.get(packageName); 4130 if (pkg == null) { 4131 throw new IllegalArgumentException("Unknown package: " + packageName); 4132 } 4133 4134 final BasePermission bp = mSettings.mPermissions.get(name); 4135 if (bp == null) { 4136 throw new IllegalArgumentException("Unknown permission: " + name); 4137 } 4138 4139 SettingBase sb = (SettingBase) pkg.mExtras; 4140 if (sb == null) { 4141 throw new IllegalArgumentException("Unknown package: " + packageName); 4142 } 4143 4144 PermissionsState permissionsState = sb.getPermissionsState(); 4145 4146 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4147 4148 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4149 // Install and runtime permissions are stored in different places, 4150 // so figure out what permission changed and persist the change. 4151 if (permissionsState.getInstallPermissionState(name) != null) { 4152 scheduleWriteSettingsLocked(); 4153 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4154 || hadState) { 4155 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4156 } 4157 } 4158 } 4159 } 4160 4161 /** 4162 * Update the permission flags for all packages and runtime permissions of a user in order 4163 * to allow device or profile owner to remove POLICY_FIXED. 4164 */ 4165 @Override 4166 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4167 if (!sUserManager.exists(userId)) { 4168 return; 4169 } 4170 4171 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4172 4173 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4174 true /* requireFullPermission */, true /* checkShell */, 4175 "updatePermissionFlagsForAllApps"); 4176 4177 // Only the system can change system fixed flags. 4178 if (getCallingUid() != Process.SYSTEM_UID) { 4179 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4180 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4181 } 4182 4183 synchronized (mPackages) { 4184 boolean changed = false; 4185 final int packageCount = mPackages.size(); 4186 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4187 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4188 SettingBase sb = (SettingBase) pkg.mExtras; 4189 if (sb == null) { 4190 continue; 4191 } 4192 PermissionsState permissionsState = sb.getPermissionsState(); 4193 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4194 userId, flagMask, flagValues); 4195 } 4196 if (changed) { 4197 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4198 } 4199 } 4200 } 4201 4202 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4203 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4204 != PackageManager.PERMISSION_GRANTED 4205 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4206 != PackageManager.PERMISSION_GRANTED) { 4207 throw new SecurityException(message + " requires " 4208 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4209 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4210 } 4211 } 4212 4213 @Override 4214 public boolean shouldShowRequestPermissionRationale(String permissionName, 4215 String packageName, int userId) { 4216 if (UserHandle.getCallingUserId() != userId) { 4217 mContext.enforceCallingPermission( 4218 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4219 "canShowRequestPermissionRationale for user " + userId); 4220 } 4221 4222 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4223 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4224 return false; 4225 } 4226 4227 if (checkPermission(permissionName, packageName, userId) 4228 == PackageManager.PERMISSION_GRANTED) { 4229 return false; 4230 } 4231 4232 final int flags; 4233 4234 final long identity = Binder.clearCallingIdentity(); 4235 try { 4236 flags = getPermissionFlags(permissionName, 4237 packageName, userId); 4238 } finally { 4239 Binder.restoreCallingIdentity(identity); 4240 } 4241 4242 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4243 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4244 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4245 4246 if ((flags & fixedFlags) != 0) { 4247 return false; 4248 } 4249 4250 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4251 } 4252 4253 @Override 4254 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4255 mContext.enforceCallingOrSelfPermission( 4256 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4257 "addOnPermissionsChangeListener"); 4258 4259 synchronized (mPackages) { 4260 mOnPermissionChangeListeners.addListenerLocked(listener); 4261 } 4262 } 4263 4264 @Override 4265 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4266 synchronized (mPackages) { 4267 mOnPermissionChangeListeners.removeListenerLocked(listener); 4268 } 4269 } 4270 4271 @Override 4272 public boolean isProtectedBroadcast(String actionName) { 4273 synchronized (mPackages) { 4274 if (mProtectedBroadcasts.contains(actionName)) { 4275 return true; 4276 } else if (actionName != null) { 4277 // TODO: remove these terrible hacks 4278 if (actionName.startsWith("android.net.netmon.lingerExpired") 4279 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4280 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4281 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4282 return true; 4283 } 4284 } 4285 } 4286 return false; 4287 } 4288 4289 @Override 4290 public int checkSignatures(String pkg1, String pkg2) { 4291 synchronized (mPackages) { 4292 final PackageParser.Package p1 = mPackages.get(pkg1); 4293 final PackageParser.Package p2 = mPackages.get(pkg2); 4294 if (p1 == null || p1.mExtras == null 4295 || p2 == null || p2.mExtras == null) { 4296 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4297 } 4298 return compareSignatures(p1.mSignatures, p2.mSignatures); 4299 } 4300 } 4301 4302 @Override 4303 public int checkUidSignatures(int uid1, int uid2) { 4304 // Map to base uids. 4305 uid1 = UserHandle.getAppId(uid1); 4306 uid2 = UserHandle.getAppId(uid2); 4307 // reader 4308 synchronized (mPackages) { 4309 Signature[] s1; 4310 Signature[] s2; 4311 Object obj = mSettings.getUserIdLPr(uid1); 4312 if (obj != null) { 4313 if (obj instanceof SharedUserSetting) { 4314 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4315 } else if (obj instanceof PackageSetting) { 4316 s1 = ((PackageSetting)obj).signatures.mSignatures; 4317 } else { 4318 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4319 } 4320 } else { 4321 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4322 } 4323 obj = mSettings.getUserIdLPr(uid2); 4324 if (obj != null) { 4325 if (obj instanceof SharedUserSetting) { 4326 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4327 } else if (obj instanceof PackageSetting) { 4328 s2 = ((PackageSetting)obj).signatures.mSignatures; 4329 } else { 4330 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4331 } 4332 } else { 4333 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4334 } 4335 return compareSignatures(s1, s2); 4336 } 4337 } 4338 4339 private void killUid(int appId, int userId, String reason) { 4340 final long identity = Binder.clearCallingIdentity(); 4341 try { 4342 IActivityManager am = ActivityManagerNative.getDefault(); 4343 if (am != null) { 4344 try { 4345 am.killUid(appId, userId, reason); 4346 } catch (RemoteException e) { 4347 /* ignore - same process */ 4348 } 4349 } 4350 } finally { 4351 Binder.restoreCallingIdentity(identity); 4352 } 4353 } 4354 4355 /** 4356 * Compares two sets of signatures. Returns: 4357 * <br /> 4358 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4359 * <br /> 4360 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4361 * <br /> 4362 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4363 * <br /> 4364 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4365 * <br /> 4366 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4367 */ 4368 static int compareSignatures(Signature[] s1, Signature[] s2) { 4369 if (s1 == null) { 4370 return s2 == null 4371 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4372 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4373 } 4374 4375 if (s2 == null) { 4376 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4377 } 4378 4379 if (s1.length != s2.length) { 4380 return PackageManager.SIGNATURE_NO_MATCH; 4381 } 4382 4383 // Since both signature sets are of size 1, we can compare without HashSets. 4384 if (s1.length == 1) { 4385 return s1[0].equals(s2[0]) ? 4386 PackageManager.SIGNATURE_MATCH : 4387 PackageManager.SIGNATURE_NO_MATCH; 4388 } 4389 4390 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4391 for (Signature sig : s1) { 4392 set1.add(sig); 4393 } 4394 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4395 for (Signature sig : s2) { 4396 set2.add(sig); 4397 } 4398 // Make sure s2 contains all signatures in s1. 4399 if (set1.equals(set2)) { 4400 return PackageManager.SIGNATURE_MATCH; 4401 } 4402 return PackageManager.SIGNATURE_NO_MATCH; 4403 } 4404 4405 /** 4406 * If the database version for this type of package (internal storage or 4407 * external storage) is less than the version where package signatures 4408 * were updated, return true. 4409 */ 4410 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4411 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4412 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4413 } 4414 4415 /** 4416 * Used for backward compatibility to make sure any packages with 4417 * certificate chains get upgraded to the new style. {@code existingSigs} 4418 * will be in the old format (since they were stored on disk from before the 4419 * system upgrade) and {@code scannedSigs} will be in the newer format. 4420 */ 4421 private int compareSignaturesCompat(PackageSignatures existingSigs, 4422 PackageParser.Package scannedPkg) { 4423 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4424 return PackageManager.SIGNATURE_NO_MATCH; 4425 } 4426 4427 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4428 for (Signature sig : existingSigs.mSignatures) { 4429 existingSet.add(sig); 4430 } 4431 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4432 for (Signature sig : scannedPkg.mSignatures) { 4433 try { 4434 Signature[] chainSignatures = sig.getChainSignatures(); 4435 for (Signature chainSig : chainSignatures) { 4436 scannedCompatSet.add(chainSig); 4437 } 4438 } catch (CertificateEncodingException e) { 4439 scannedCompatSet.add(sig); 4440 } 4441 } 4442 /* 4443 * Make sure the expanded scanned set contains all signatures in the 4444 * existing one. 4445 */ 4446 if (scannedCompatSet.equals(existingSet)) { 4447 // Migrate the old signatures to the new scheme. 4448 existingSigs.assignSignatures(scannedPkg.mSignatures); 4449 // The new KeySets will be re-added later in the scanning process. 4450 synchronized (mPackages) { 4451 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4452 } 4453 return PackageManager.SIGNATURE_MATCH; 4454 } 4455 return PackageManager.SIGNATURE_NO_MATCH; 4456 } 4457 4458 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4459 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4460 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4461 } 4462 4463 private int compareSignaturesRecover(PackageSignatures existingSigs, 4464 PackageParser.Package scannedPkg) { 4465 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4466 return PackageManager.SIGNATURE_NO_MATCH; 4467 } 4468 4469 String msg = null; 4470 try { 4471 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4472 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4473 + scannedPkg.packageName); 4474 return PackageManager.SIGNATURE_MATCH; 4475 } 4476 } catch (CertificateException e) { 4477 msg = e.getMessage(); 4478 } 4479 4480 logCriticalInfo(Log.INFO, 4481 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4482 return PackageManager.SIGNATURE_NO_MATCH; 4483 } 4484 4485 @Override 4486 public List<String> getAllPackages() { 4487 synchronized (mPackages) { 4488 return new ArrayList<String>(mPackages.keySet()); 4489 } 4490 } 4491 4492 @Override 4493 public String[] getPackagesForUid(int uid) { 4494 uid = UserHandle.getAppId(uid); 4495 // reader 4496 synchronized (mPackages) { 4497 Object obj = mSettings.getUserIdLPr(uid); 4498 if (obj instanceof SharedUserSetting) { 4499 final SharedUserSetting sus = (SharedUserSetting) obj; 4500 final int N = sus.packages.size(); 4501 final String[] res = new String[N]; 4502 final Iterator<PackageSetting> it = sus.packages.iterator(); 4503 int i = 0; 4504 while (it.hasNext()) { 4505 res[i++] = it.next().name; 4506 } 4507 return res; 4508 } else if (obj instanceof PackageSetting) { 4509 final PackageSetting ps = (PackageSetting) obj; 4510 return new String[] { ps.name }; 4511 } 4512 } 4513 return null; 4514 } 4515 4516 @Override 4517 public String getNameForUid(int uid) { 4518 // reader 4519 synchronized (mPackages) { 4520 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4521 if (obj instanceof SharedUserSetting) { 4522 final SharedUserSetting sus = (SharedUserSetting) obj; 4523 return sus.name + ":" + sus.userId; 4524 } else if (obj instanceof PackageSetting) { 4525 final PackageSetting ps = (PackageSetting) obj; 4526 return ps.name; 4527 } 4528 } 4529 return null; 4530 } 4531 4532 @Override 4533 public int getUidForSharedUser(String sharedUserName) { 4534 if(sharedUserName == null) { 4535 return -1; 4536 } 4537 // reader 4538 synchronized (mPackages) { 4539 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4540 if (suid == null) { 4541 return -1; 4542 } 4543 return suid.userId; 4544 } 4545 } 4546 4547 @Override 4548 public int getFlagsForUid(int uid) { 4549 synchronized (mPackages) { 4550 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4551 if (obj instanceof SharedUserSetting) { 4552 final SharedUserSetting sus = (SharedUserSetting) obj; 4553 return sus.pkgFlags; 4554 } else if (obj instanceof PackageSetting) { 4555 final PackageSetting ps = (PackageSetting) obj; 4556 return ps.pkgFlags; 4557 } 4558 } 4559 return 0; 4560 } 4561 4562 @Override 4563 public int getPrivateFlagsForUid(int uid) { 4564 synchronized (mPackages) { 4565 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4566 if (obj instanceof SharedUserSetting) { 4567 final SharedUserSetting sus = (SharedUserSetting) obj; 4568 return sus.pkgPrivateFlags; 4569 } else if (obj instanceof PackageSetting) { 4570 final PackageSetting ps = (PackageSetting) obj; 4571 return ps.pkgPrivateFlags; 4572 } 4573 } 4574 return 0; 4575 } 4576 4577 @Override 4578 public boolean isUidPrivileged(int uid) { 4579 uid = UserHandle.getAppId(uid); 4580 // reader 4581 synchronized (mPackages) { 4582 Object obj = mSettings.getUserIdLPr(uid); 4583 if (obj instanceof SharedUserSetting) { 4584 final SharedUserSetting sus = (SharedUserSetting) obj; 4585 final Iterator<PackageSetting> it = sus.packages.iterator(); 4586 while (it.hasNext()) { 4587 if (it.next().isPrivileged()) { 4588 return true; 4589 } 4590 } 4591 } else if (obj instanceof PackageSetting) { 4592 final PackageSetting ps = (PackageSetting) obj; 4593 return ps.isPrivileged(); 4594 } 4595 } 4596 return false; 4597 } 4598 4599 @Override 4600 public String[] getAppOpPermissionPackages(String permissionName) { 4601 synchronized (mPackages) { 4602 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4603 if (pkgs == null) { 4604 return null; 4605 } 4606 return pkgs.toArray(new String[pkgs.size()]); 4607 } 4608 } 4609 4610 @Override 4611 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4612 int flags, int userId) { 4613 if (!sUserManager.exists(userId)) return null; 4614 flags = updateFlagsForResolve(flags, userId, intent); 4615 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4616 false /* requireFullPermission */, false /* checkShell */, "resolve intent"); 4617 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4618 userId); 4619 final ResolveInfo bestChoice = 4620 chooseBestActivity(intent, resolvedType, flags, query, userId); 4621 4622 if (isEphemeralAllowed(intent, query, userId)) { 4623 final EphemeralResolveInfo ai = 4624 getEphemeralResolveInfo(intent, resolvedType, userId); 4625 if (ai != null) { 4626 if (DEBUG_EPHEMERAL) { 4627 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4628 } 4629 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4630 bestChoice.ephemeralResolveInfo = ai; 4631 } 4632 } 4633 return bestChoice; 4634 } 4635 4636 @Override 4637 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4638 IntentFilter filter, int match, ComponentName activity) { 4639 final int userId = UserHandle.getCallingUserId(); 4640 if (DEBUG_PREFERRED) { 4641 Log.v(TAG, "setLastChosenActivity intent=" + intent 4642 + " resolvedType=" + resolvedType 4643 + " flags=" + flags 4644 + " filter=" + filter 4645 + " match=" + match 4646 + " activity=" + activity); 4647 filter.dump(new PrintStreamPrinter(System.out), " "); 4648 } 4649 intent.setComponent(null); 4650 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4651 userId); 4652 // Find any earlier preferred or last chosen entries and nuke them 4653 findPreferredActivity(intent, resolvedType, 4654 flags, query, 0, false, true, false, userId); 4655 // Add the new activity as the last chosen for this filter 4656 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4657 "Setting last chosen"); 4658 } 4659 4660 @Override 4661 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4662 final int userId = UserHandle.getCallingUserId(); 4663 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4664 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4665 userId); 4666 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4667 false, false, false, userId); 4668 } 4669 4670 4671 private boolean isEphemeralAllowed( 4672 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4673 // Short circuit and return early if possible. 4674 if (DISABLE_EPHEMERAL_APPS) { 4675 return false; 4676 } 4677 final int callingUser = UserHandle.getCallingUserId(); 4678 if (callingUser != UserHandle.USER_SYSTEM) { 4679 return false; 4680 } 4681 if (mEphemeralResolverConnection == null) { 4682 return false; 4683 } 4684 if (intent.getComponent() != null) { 4685 return false; 4686 } 4687 if (intent.getPackage() != null) { 4688 return false; 4689 } 4690 final boolean isWebUri = hasWebURI(intent); 4691 if (!isWebUri) { 4692 return false; 4693 } 4694 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4695 synchronized (mPackages) { 4696 final int count = resolvedActivites.size(); 4697 for (int n = 0; n < count; n++) { 4698 ResolveInfo info = resolvedActivites.get(n); 4699 String packageName = info.activityInfo.packageName; 4700 PackageSetting ps = mSettings.mPackages.get(packageName); 4701 if (ps != null) { 4702 // Try to get the status from User settings first 4703 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4704 int status = (int) (packedStatus >> 32); 4705 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4706 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4707 if (DEBUG_EPHEMERAL) { 4708 Slog.v(TAG, "DENY ephemeral apps;" 4709 + " pkg: " + packageName + ", status: " + status); 4710 } 4711 return false; 4712 } 4713 } 4714 } 4715 } 4716 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4717 return true; 4718 } 4719 4720 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4721 int userId) { 4722 MessageDigest digest = null; 4723 try { 4724 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4725 } catch (NoSuchAlgorithmException e) { 4726 // If we can't create a digest, ignore ephemeral apps. 4727 return null; 4728 } 4729 4730 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4731 final byte[] digestBytes = digest.digest(hostBytes); 4732 int shaPrefix = 4733 digestBytes[0] << 24 4734 | digestBytes[1] << 16 4735 | digestBytes[2] << 8 4736 | digestBytes[3] << 0; 4737 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4738 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4739 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4740 // No hash prefix match; there are no ephemeral apps for this domain. 4741 return null; 4742 } 4743 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4744 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4745 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4746 continue; 4747 } 4748 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4749 // No filters; this should never happen. 4750 if (filters.isEmpty()) { 4751 continue; 4752 } 4753 // We have a domain match; resolve the filters to see if anything matches. 4754 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4755 for (int j = filters.size() - 1; j >= 0; --j) { 4756 final EphemeralResolveIntentInfo intentInfo = 4757 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4758 ephemeralResolver.addFilter(intentInfo); 4759 } 4760 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4761 intent, resolvedType, false /*defaultOnly*/, userId); 4762 if (!matchedResolveInfoList.isEmpty()) { 4763 return matchedResolveInfoList.get(0); 4764 } 4765 } 4766 // Hash or filter mis-match; no ephemeral apps for this domain. 4767 return null; 4768 } 4769 4770 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4771 int flags, List<ResolveInfo> query, int userId) { 4772 if (query != null) { 4773 final int N = query.size(); 4774 if (N == 1) { 4775 return query.get(0); 4776 } else if (N > 1) { 4777 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4778 // If there is more than one activity with the same priority, 4779 // then let the user decide between them. 4780 ResolveInfo r0 = query.get(0); 4781 ResolveInfo r1 = query.get(1); 4782 if (DEBUG_INTENT_MATCHING || debug) { 4783 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4784 + r1.activityInfo.name + "=" + r1.priority); 4785 } 4786 // If the first activity has a higher priority, or a different 4787 // default, then it is always desirable to pick it. 4788 if (r0.priority != r1.priority 4789 || r0.preferredOrder != r1.preferredOrder 4790 || r0.isDefault != r1.isDefault) { 4791 return query.get(0); 4792 } 4793 // If we have saved a preference for a preferred activity for 4794 // this Intent, use that. 4795 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4796 flags, query, r0.priority, true, false, debug, userId); 4797 if (ri != null) { 4798 return ri; 4799 } 4800 ri = new ResolveInfo(mResolveInfo); 4801 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4802 ri.activityInfo.applicationInfo = new ApplicationInfo( 4803 ri.activityInfo.applicationInfo); 4804 if (userId != 0) { 4805 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4806 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4807 } 4808 // Make sure that the resolver is displayable in car mode 4809 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4810 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4811 return ri; 4812 } 4813 } 4814 return null; 4815 } 4816 4817 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4818 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4819 final int N = query.size(); 4820 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4821 .get(userId); 4822 // Get the list of persistent preferred activities that handle the intent 4823 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4824 List<PersistentPreferredActivity> pprefs = ppir != null 4825 ? ppir.queryIntent(intent, resolvedType, 4826 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4827 : null; 4828 if (pprefs != null && pprefs.size() > 0) { 4829 final int M = pprefs.size(); 4830 for (int i=0; i<M; i++) { 4831 final PersistentPreferredActivity ppa = pprefs.get(i); 4832 if (DEBUG_PREFERRED || debug) { 4833 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4834 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4835 + "\n component=" + ppa.mComponent); 4836 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4837 } 4838 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4839 flags | MATCH_DISABLED_COMPONENTS, userId); 4840 if (DEBUG_PREFERRED || debug) { 4841 Slog.v(TAG, "Found persistent preferred activity:"); 4842 if (ai != null) { 4843 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4844 } else { 4845 Slog.v(TAG, " null"); 4846 } 4847 } 4848 if (ai == null) { 4849 // This previously registered persistent preferred activity 4850 // component is no longer known. Ignore it and do NOT remove it. 4851 continue; 4852 } 4853 for (int j=0; j<N; j++) { 4854 final ResolveInfo ri = query.get(j); 4855 if (!ri.activityInfo.applicationInfo.packageName 4856 .equals(ai.applicationInfo.packageName)) { 4857 continue; 4858 } 4859 if (!ri.activityInfo.name.equals(ai.name)) { 4860 continue; 4861 } 4862 // Found a persistent preference that can handle the intent. 4863 if (DEBUG_PREFERRED || debug) { 4864 Slog.v(TAG, "Returning persistent preferred activity: " + 4865 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4866 } 4867 return ri; 4868 } 4869 } 4870 } 4871 return null; 4872 } 4873 4874 // TODO: handle preferred activities missing while user has amnesia 4875 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4876 List<ResolveInfo> query, int priority, boolean always, 4877 boolean removeMatches, boolean debug, int userId) { 4878 if (!sUserManager.exists(userId)) return null; 4879 flags = updateFlagsForResolve(flags, userId, intent); 4880 // writer 4881 synchronized (mPackages) { 4882 if (intent.getSelector() != null) { 4883 intent = intent.getSelector(); 4884 } 4885 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4886 4887 // Try to find a matching persistent preferred activity. 4888 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4889 debug, userId); 4890 4891 // If a persistent preferred activity matched, use it. 4892 if (pri != null) { 4893 return pri; 4894 } 4895 4896 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4897 // Get the list of preferred activities that handle the intent 4898 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4899 List<PreferredActivity> prefs = pir != null 4900 ? pir.queryIntent(intent, resolvedType, 4901 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4902 : null; 4903 if (prefs != null && prefs.size() > 0) { 4904 boolean changed = false; 4905 try { 4906 // First figure out how good the original match set is. 4907 // We will only allow preferred activities that came 4908 // from the same match quality. 4909 int match = 0; 4910 4911 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4912 4913 final int N = query.size(); 4914 for (int j=0; j<N; j++) { 4915 final ResolveInfo ri = query.get(j); 4916 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4917 + ": 0x" + Integer.toHexString(match)); 4918 if (ri.match > match) { 4919 match = ri.match; 4920 } 4921 } 4922 4923 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4924 + Integer.toHexString(match)); 4925 4926 match &= IntentFilter.MATCH_CATEGORY_MASK; 4927 final int M = prefs.size(); 4928 for (int i=0; i<M; i++) { 4929 final PreferredActivity pa = prefs.get(i); 4930 if (DEBUG_PREFERRED || debug) { 4931 Slog.v(TAG, "Checking PreferredActivity ds=" 4932 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4933 + "\n component=" + pa.mPref.mComponent); 4934 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4935 } 4936 if (pa.mPref.mMatch != match) { 4937 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4938 + Integer.toHexString(pa.mPref.mMatch)); 4939 continue; 4940 } 4941 // If it's not an "always" type preferred activity and that's what we're 4942 // looking for, skip it. 4943 if (always && !pa.mPref.mAlways) { 4944 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4945 continue; 4946 } 4947 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4948 flags | MATCH_DISABLED_COMPONENTS, userId); 4949 if (DEBUG_PREFERRED || debug) { 4950 Slog.v(TAG, "Found preferred activity:"); 4951 if (ai != null) { 4952 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4953 } else { 4954 Slog.v(TAG, " null"); 4955 } 4956 } 4957 if (ai == null) { 4958 // This previously registered preferred activity 4959 // component is no longer known. Most likely an update 4960 // to the app was installed and in the new version this 4961 // component no longer exists. Clean it up by removing 4962 // it from the preferred activities list, and skip it. 4963 Slog.w(TAG, "Removing dangling preferred activity: " 4964 + pa.mPref.mComponent); 4965 pir.removeFilter(pa); 4966 changed = true; 4967 continue; 4968 } 4969 for (int j=0; j<N; j++) { 4970 final ResolveInfo ri = query.get(j); 4971 if (!ri.activityInfo.applicationInfo.packageName 4972 .equals(ai.applicationInfo.packageName)) { 4973 continue; 4974 } 4975 if (!ri.activityInfo.name.equals(ai.name)) { 4976 continue; 4977 } 4978 4979 if (removeMatches) { 4980 pir.removeFilter(pa); 4981 changed = true; 4982 if (DEBUG_PREFERRED) { 4983 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4984 } 4985 break; 4986 } 4987 4988 // Okay we found a previously set preferred or last chosen app. 4989 // If the result set is different from when this 4990 // was created, we need to clear it and re-ask the 4991 // user their preference, if we're looking for an "always" type entry. 4992 if (always && !pa.mPref.sameSet(query)) { 4993 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4994 + intent + " type " + resolvedType); 4995 if (DEBUG_PREFERRED) { 4996 Slog.v(TAG, "Removing preferred activity since set changed " 4997 + pa.mPref.mComponent); 4998 } 4999 pir.removeFilter(pa); 5000 // Re-add the filter as a "last chosen" entry (!always) 5001 PreferredActivity lastChosen = new PreferredActivity( 5002 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5003 pir.addFilter(lastChosen); 5004 changed = true; 5005 return null; 5006 } 5007 5008 // Yay! Either the set matched or we're looking for the last chosen 5009 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5010 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5011 return ri; 5012 } 5013 } 5014 } finally { 5015 if (changed) { 5016 if (DEBUG_PREFERRED) { 5017 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5018 } 5019 scheduleWritePackageRestrictionsLocked(userId); 5020 } 5021 } 5022 } 5023 } 5024 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5025 return null; 5026 } 5027 5028 /* 5029 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5030 */ 5031 @Override 5032 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5033 int targetUserId) { 5034 mContext.enforceCallingOrSelfPermission( 5035 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5036 List<CrossProfileIntentFilter> matches = 5037 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5038 if (matches != null) { 5039 int size = matches.size(); 5040 for (int i = 0; i < size; i++) { 5041 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5042 } 5043 } 5044 if (hasWebURI(intent)) { 5045 // cross-profile app linking works only towards the parent. 5046 final UserInfo parent = getProfileParent(sourceUserId); 5047 synchronized(mPackages) { 5048 int flags = updateFlagsForResolve(0, parent.id, intent); 5049 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5050 intent, resolvedType, flags, sourceUserId, parent.id); 5051 return xpDomainInfo != null; 5052 } 5053 } 5054 return false; 5055 } 5056 5057 private UserInfo getProfileParent(int userId) { 5058 final long identity = Binder.clearCallingIdentity(); 5059 try { 5060 return sUserManager.getProfileParent(userId); 5061 } finally { 5062 Binder.restoreCallingIdentity(identity); 5063 } 5064 } 5065 5066 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5067 String resolvedType, int userId) { 5068 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5069 if (resolver != null) { 5070 return resolver.queryIntent(intent, resolvedType, false, userId); 5071 } 5072 return null; 5073 } 5074 5075 @Override 5076 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5077 String resolvedType, int flags, int userId) { 5078 return new ParceledListSlice<>( 5079 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5080 } 5081 5082 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5083 String resolvedType, int flags, int userId) { 5084 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5085 flags = updateFlagsForResolve(flags, userId, intent); 5086 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5087 false /* requireFullPermission */, false /* checkShell */, 5088 "query intent activities"); 5089 ComponentName comp = intent.getComponent(); 5090 if (comp == null) { 5091 if (intent.getSelector() != null) { 5092 intent = intent.getSelector(); 5093 comp = intent.getComponent(); 5094 } 5095 } 5096 5097 if (comp != null) { 5098 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5099 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5100 if (ai != null) { 5101 final ResolveInfo ri = new ResolveInfo(); 5102 ri.activityInfo = ai; 5103 list.add(ri); 5104 } 5105 return list; 5106 } 5107 5108 // reader 5109 synchronized (mPackages) { 5110 final String pkgName = intent.getPackage(); 5111 if (pkgName == null) { 5112 List<CrossProfileIntentFilter> matchingFilters = 5113 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5114 // Check for results that need to skip the current profile. 5115 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5116 resolvedType, flags, userId); 5117 if (xpResolveInfo != null) { 5118 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5119 result.add(xpResolveInfo); 5120 return filterIfNotSystemUser(result, userId); 5121 } 5122 5123 // Check for results in the current profile. 5124 List<ResolveInfo> result = mActivities.queryIntent( 5125 intent, resolvedType, flags, userId); 5126 result = filterIfNotSystemUser(result, userId); 5127 5128 // Check for cross profile results. 5129 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5130 xpResolveInfo = queryCrossProfileIntents( 5131 matchingFilters, intent, resolvedType, flags, userId, 5132 hasNonNegativePriorityResult); 5133 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5134 boolean isVisibleToUser = filterIfNotSystemUser( 5135 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5136 if (isVisibleToUser) { 5137 result.add(xpResolveInfo); 5138 Collections.sort(result, mResolvePrioritySorter); 5139 } 5140 } 5141 if (hasWebURI(intent)) { 5142 CrossProfileDomainInfo xpDomainInfo = null; 5143 final UserInfo parent = getProfileParent(userId); 5144 if (parent != null) { 5145 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5146 flags, userId, parent.id); 5147 } 5148 if (xpDomainInfo != null) { 5149 if (xpResolveInfo != null) { 5150 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5151 // in the result. 5152 result.remove(xpResolveInfo); 5153 } 5154 if (result.size() == 0) { 5155 result.add(xpDomainInfo.resolveInfo); 5156 return result; 5157 } 5158 } else if (result.size() <= 1) { 5159 return result; 5160 } 5161 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5162 xpDomainInfo, userId); 5163 Collections.sort(result, mResolvePrioritySorter); 5164 } 5165 return result; 5166 } 5167 final PackageParser.Package pkg = mPackages.get(pkgName); 5168 if (pkg != null) { 5169 return filterIfNotSystemUser( 5170 mActivities.queryIntentForPackage( 5171 intent, resolvedType, flags, pkg.activities, userId), 5172 userId); 5173 } 5174 return new ArrayList<ResolveInfo>(); 5175 } 5176 } 5177 5178 private static class CrossProfileDomainInfo { 5179 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5180 ResolveInfo resolveInfo; 5181 /* Best domain verification status of the activities found in the other profile */ 5182 int bestDomainVerificationStatus; 5183 } 5184 5185 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5186 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5187 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5188 sourceUserId)) { 5189 return null; 5190 } 5191 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5192 resolvedType, flags, parentUserId); 5193 5194 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5195 return null; 5196 } 5197 CrossProfileDomainInfo result = null; 5198 int size = resultTargetUser.size(); 5199 for (int i = 0; i < size; i++) { 5200 ResolveInfo riTargetUser = resultTargetUser.get(i); 5201 // Intent filter verification is only for filters that specify a host. So don't return 5202 // those that handle all web uris. 5203 if (riTargetUser.handleAllWebDataURI) { 5204 continue; 5205 } 5206 String packageName = riTargetUser.activityInfo.packageName; 5207 PackageSetting ps = mSettings.mPackages.get(packageName); 5208 if (ps == null) { 5209 continue; 5210 } 5211 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5212 int status = (int)(verificationState >> 32); 5213 if (result == null) { 5214 result = new CrossProfileDomainInfo(); 5215 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5216 sourceUserId, parentUserId); 5217 result.bestDomainVerificationStatus = status; 5218 } else { 5219 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5220 result.bestDomainVerificationStatus); 5221 } 5222 } 5223 // Don't consider matches with status NEVER across profiles. 5224 if (result != null && result.bestDomainVerificationStatus 5225 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5226 return null; 5227 } 5228 return result; 5229 } 5230 5231 /** 5232 * Verification statuses are ordered from the worse to the best, except for 5233 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5234 */ 5235 private int bestDomainVerificationStatus(int status1, int status2) { 5236 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5237 return status2; 5238 } 5239 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5240 return status1; 5241 } 5242 return (int) MathUtils.max(status1, status2); 5243 } 5244 5245 private boolean isUserEnabled(int userId) { 5246 long callingId = Binder.clearCallingIdentity(); 5247 try { 5248 UserInfo userInfo = sUserManager.getUserInfo(userId); 5249 return userInfo != null && userInfo.isEnabled(); 5250 } finally { 5251 Binder.restoreCallingIdentity(callingId); 5252 } 5253 } 5254 5255 /** 5256 * Filter out activities with systemUserOnly flag set, when current user is not System. 5257 * 5258 * @return filtered list 5259 */ 5260 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5261 if (userId == UserHandle.USER_SYSTEM) { 5262 return resolveInfos; 5263 } 5264 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5265 ResolveInfo info = resolveInfos.get(i); 5266 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5267 resolveInfos.remove(i); 5268 } 5269 } 5270 return resolveInfos; 5271 } 5272 5273 /** 5274 * @param resolveInfos list of resolve infos in descending priority order 5275 * @return if the list contains a resolve info with non-negative priority 5276 */ 5277 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5278 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5279 } 5280 5281 private static boolean hasWebURI(Intent intent) { 5282 if (intent.getData() == null) { 5283 return false; 5284 } 5285 final String scheme = intent.getScheme(); 5286 if (TextUtils.isEmpty(scheme)) { 5287 return false; 5288 } 5289 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5290 } 5291 5292 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5293 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5294 int userId) { 5295 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5296 5297 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5298 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5299 candidates.size()); 5300 } 5301 5302 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5303 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5304 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5305 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5306 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5307 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5308 5309 synchronized (mPackages) { 5310 final int count = candidates.size(); 5311 // First, try to use linked apps. Partition the candidates into four lists: 5312 // one for the final results, one for the "do not use ever", one for "undefined status" 5313 // and finally one for "browser app type". 5314 for (int n=0; n<count; n++) { 5315 ResolveInfo info = candidates.get(n); 5316 String packageName = info.activityInfo.packageName; 5317 PackageSetting ps = mSettings.mPackages.get(packageName); 5318 if (ps != null) { 5319 // Add to the special match all list (Browser use case) 5320 if (info.handleAllWebDataURI) { 5321 matchAllList.add(info); 5322 continue; 5323 } 5324 // Try to get the status from User settings first 5325 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5326 int status = (int)(packedStatus >> 32); 5327 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5328 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5329 if (DEBUG_DOMAIN_VERIFICATION) { 5330 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5331 + " : linkgen=" + linkGeneration); 5332 } 5333 // Use link-enabled generation as preferredOrder, i.e. 5334 // prefer newly-enabled over earlier-enabled. 5335 info.preferredOrder = linkGeneration; 5336 alwaysList.add(info); 5337 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5338 if (DEBUG_DOMAIN_VERIFICATION) { 5339 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5340 } 5341 neverList.add(info); 5342 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5343 if (DEBUG_DOMAIN_VERIFICATION) { 5344 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5345 } 5346 alwaysAskList.add(info); 5347 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5348 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5349 if (DEBUG_DOMAIN_VERIFICATION) { 5350 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5351 } 5352 undefinedList.add(info); 5353 } 5354 } 5355 } 5356 5357 // We'll want to include browser possibilities in a few cases 5358 boolean includeBrowser = false; 5359 5360 // First try to add the "always" resolution(s) for the current user, if any 5361 if (alwaysList.size() > 0) { 5362 result.addAll(alwaysList); 5363 } else { 5364 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5365 result.addAll(undefinedList); 5366 // Maybe add one for the other profile. 5367 if (xpDomainInfo != null && ( 5368 xpDomainInfo.bestDomainVerificationStatus 5369 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5370 result.add(xpDomainInfo.resolveInfo); 5371 } 5372 includeBrowser = true; 5373 } 5374 5375 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5376 // If there were 'always' entries their preferred order has been set, so we also 5377 // back that off to make the alternatives equivalent 5378 if (alwaysAskList.size() > 0) { 5379 for (ResolveInfo i : result) { 5380 i.preferredOrder = 0; 5381 } 5382 result.addAll(alwaysAskList); 5383 includeBrowser = true; 5384 } 5385 5386 if (includeBrowser) { 5387 // Also add browsers (all of them or only the default one) 5388 if (DEBUG_DOMAIN_VERIFICATION) { 5389 Slog.v(TAG, " ...including browsers in candidate set"); 5390 } 5391 if ((matchFlags & MATCH_ALL) != 0) { 5392 result.addAll(matchAllList); 5393 } else { 5394 // Browser/generic handling case. If there's a default browser, go straight 5395 // to that (but only if there is no other higher-priority match). 5396 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5397 int maxMatchPrio = 0; 5398 ResolveInfo defaultBrowserMatch = null; 5399 final int numCandidates = matchAllList.size(); 5400 for (int n = 0; n < numCandidates; n++) { 5401 ResolveInfo info = matchAllList.get(n); 5402 // track the highest overall match priority... 5403 if (info.priority > maxMatchPrio) { 5404 maxMatchPrio = info.priority; 5405 } 5406 // ...and the highest-priority default browser match 5407 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5408 if (defaultBrowserMatch == null 5409 || (defaultBrowserMatch.priority < info.priority)) { 5410 if (debug) { 5411 Slog.v(TAG, "Considering default browser match " + info); 5412 } 5413 defaultBrowserMatch = info; 5414 } 5415 } 5416 } 5417 if (defaultBrowserMatch != null 5418 && defaultBrowserMatch.priority >= maxMatchPrio 5419 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5420 { 5421 if (debug) { 5422 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5423 } 5424 result.add(defaultBrowserMatch); 5425 } else { 5426 result.addAll(matchAllList); 5427 } 5428 } 5429 5430 // If there is nothing selected, add all candidates and remove the ones that the user 5431 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5432 if (result.size() == 0) { 5433 result.addAll(candidates); 5434 result.removeAll(neverList); 5435 } 5436 } 5437 } 5438 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5439 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5440 result.size()); 5441 for (ResolveInfo info : result) { 5442 Slog.v(TAG, " + " + info.activityInfo); 5443 } 5444 } 5445 return result; 5446 } 5447 5448 // Returns a packed value as a long: 5449 // 5450 // high 'int'-sized word: link status: undefined/ask/never/always. 5451 // low 'int'-sized word: relative priority among 'always' results. 5452 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5453 long result = ps.getDomainVerificationStatusForUser(userId); 5454 // if none available, get the master status 5455 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5456 if (ps.getIntentFilterVerificationInfo() != null) { 5457 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5458 } 5459 } 5460 return result; 5461 } 5462 5463 private ResolveInfo querySkipCurrentProfileIntents( 5464 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5465 int flags, int sourceUserId) { 5466 if (matchingFilters != null) { 5467 int size = matchingFilters.size(); 5468 for (int i = 0; i < size; i ++) { 5469 CrossProfileIntentFilter filter = matchingFilters.get(i); 5470 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5471 // Checking if there are activities in the target user that can handle the 5472 // intent. 5473 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5474 resolvedType, flags, sourceUserId); 5475 if (resolveInfo != null) { 5476 return resolveInfo; 5477 } 5478 } 5479 } 5480 } 5481 return null; 5482 } 5483 5484 // Return matching ResolveInfo in target user if any. 5485 private ResolveInfo queryCrossProfileIntents( 5486 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5487 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5488 if (matchingFilters != null) { 5489 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5490 // match the same intent. For performance reasons, it is better not to 5491 // run queryIntent twice for the same userId 5492 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5493 int size = matchingFilters.size(); 5494 for (int i = 0; i < size; i++) { 5495 CrossProfileIntentFilter filter = matchingFilters.get(i); 5496 int targetUserId = filter.getTargetUserId(); 5497 boolean skipCurrentProfile = 5498 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5499 boolean skipCurrentProfileIfNoMatchFound = 5500 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5501 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5502 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5503 // Checking if there are activities in the target user that can handle the 5504 // intent. 5505 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5506 resolvedType, flags, sourceUserId); 5507 if (resolveInfo != null) return resolveInfo; 5508 alreadyTriedUserIds.put(targetUserId, true); 5509 } 5510 } 5511 } 5512 return null; 5513 } 5514 5515 /** 5516 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5517 * will forward the intent to the filter's target user. 5518 * Otherwise, returns null. 5519 */ 5520 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5521 String resolvedType, int flags, int sourceUserId) { 5522 int targetUserId = filter.getTargetUserId(); 5523 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5524 resolvedType, flags, targetUserId); 5525 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5526 // If all the matches in the target profile are suspended, return null. 5527 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5528 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5529 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5530 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5531 targetUserId); 5532 } 5533 } 5534 } 5535 return null; 5536 } 5537 5538 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5539 int sourceUserId, int targetUserId) { 5540 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5541 long ident = Binder.clearCallingIdentity(); 5542 boolean targetIsProfile; 5543 try { 5544 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5545 } finally { 5546 Binder.restoreCallingIdentity(ident); 5547 } 5548 String className; 5549 if (targetIsProfile) { 5550 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5551 } else { 5552 className = FORWARD_INTENT_TO_PARENT; 5553 } 5554 ComponentName forwardingActivityComponentName = new ComponentName( 5555 mAndroidApplication.packageName, className); 5556 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5557 sourceUserId); 5558 if (!targetIsProfile) { 5559 forwardingActivityInfo.showUserIcon = targetUserId; 5560 forwardingResolveInfo.noResourceId = true; 5561 } 5562 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5563 forwardingResolveInfo.priority = 0; 5564 forwardingResolveInfo.preferredOrder = 0; 5565 forwardingResolveInfo.match = 0; 5566 forwardingResolveInfo.isDefault = true; 5567 forwardingResolveInfo.filter = filter; 5568 forwardingResolveInfo.targetUserId = targetUserId; 5569 return forwardingResolveInfo; 5570 } 5571 5572 @Override 5573 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5574 Intent[] specifics, String[] specificTypes, Intent intent, 5575 String resolvedType, int flags, int userId) { 5576 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5577 specificTypes, intent, resolvedType, flags, userId)); 5578 } 5579 5580 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5581 Intent[] specifics, String[] specificTypes, Intent intent, 5582 String resolvedType, int flags, int userId) { 5583 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5584 flags = updateFlagsForResolve(flags, userId, intent); 5585 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5586 false /* requireFullPermission */, false /* checkShell */, 5587 "query intent activity options"); 5588 final String resultsAction = intent.getAction(); 5589 5590 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5591 | PackageManager.GET_RESOLVED_FILTER, userId); 5592 5593 if (DEBUG_INTENT_MATCHING) { 5594 Log.v(TAG, "Query " + intent + ": " + results); 5595 } 5596 5597 int specificsPos = 0; 5598 int N; 5599 5600 // todo: note that the algorithm used here is O(N^2). This 5601 // isn't a problem in our current environment, but if we start running 5602 // into situations where we have more than 5 or 10 matches then this 5603 // should probably be changed to something smarter... 5604 5605 // First we go through and resolve each of the specific items 5606 // that were supplied, taking care of removing any corresponding 5607 // duplicate items in the generic resolve list. 5608 if (specifics != null) { 5609 for (int i=0; i<specifics.length; i++) { 5610 final Intent sintent = specifics[i]; 5611 if (sintent == null) { 5612 continue; 5613 } 5614 5615 if (DEBUG_INTENT_MATCHING) { 5616 Log.v(TAG, "Specific #" + i + ": " + sintent); 5617 } 5618 5619 String action = sintent.getAction(); 5620 if (resultsAction != null && resultsAction.equals(action)) { 5621 // If this action was explicitly requested, then don't 5622 // remove things that have it. 5623 action = null; 5624 } 5625 5626 ResolveInfo ri = null; 5627 ActivityInfo ai = null; 5628 5629 ComponentName comp = sintent.getComponent(); 5630 if (comp == null) { 5631 ri = resolveIntent( 5632 sintent, 5633 specificTypes != null ? specificTypes[i] : null, 5634 flags, userId); 5635 if (ri == null) { 5636 continue; 5637 } 5638 if (ri == mResolveInfo) { 5639 // ACK! Must do something better with this. 5640 } 5641 ai = ri.activityInfo; 5642 comp = new ComponentName(ai.applicationInfo.packageName, 5643 ai.name); 5644 } else { 5645 ai = getActivityInfo(comp, flags, userId); 5646 if (ai == null) { 5647 continue; 5648 } 5649 } 5650 5651 // Look for any generic query activities that are duplicates 5652 // of this specific one, and remove them from the results. 5653 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5654 N = results.size(); 5655 int j; 5656 for (j=specificsPos; j<N; j++) { 5657 ResolveInfo sri = results.get(j); 5658 if ((sri.activityInfo.name.equals(comp.getClassName()) 5659 && sri.activityInfo.applicationInfo.packageName.equals( 5660 comp.getPackageName())) 5661 || (action != null && sri.filter.matchAction(action))) { 5662 results.remove(j); 5663 if (DEBUG_INTENT_MATCHING) Log.v( 5664 TAG, "Removing duplicate item from " + j 5665 + " due to specific " + specificsPos); 5666 if (ri == null) { 5667 ri = sri; 5668 } 5669 j--; 5670 N--; 5671 } 5672 } 5673 5674 // Add this specific item to its proper place. 5675 if (ri == null) { 5676 ri = new ResolveInfo(); 5677 ri.activityInfo = ai; 5678 } 5679 results.add(specificsPos, ri); 5680 ri.specificIndex = i; 5681 specificsPos++; 5682 } 5683 } 5684 5685 // Now we go through the remaining generic results and remove any 5686 // duplicate actions that are found here. 5687 N = results.size(); 5688 for (int i=specificsPos; i<N-1; i++) { 5689 final ResolveInfo rii = results.get(i); 5690 if (rii.filter == null) { 5691 continue; 5692 } 5693 5694 // Iterate over all of the actions of this result's intent 5695 // filter... typically this should be just one. 5696 final Iterator<String> it = rii.filter.actionsIterator(); 5697 if (it == null) { 5698 continue; 5699 } 5700 while (it.hasNext()) { 5701 final String action = it.next(); 5702 if (resultsAction != null && resultsAction.equals(action)) { 5703 // If this action was explicitly requested, then don't 5704 // remove things that have it. 5705 continue; 5706 } 5707 for (int j=i+1; j<N; j++) { 5708 final ResolveInfo rij = results.get(j); 5709 if (rij.filter != null && rij.filter.hasAction(action)) { 5710 results.remove(j); 5711 if (DEBUG_INTENT_MATCHING) Log.v( 5712 TAG, "Removing duplicate item from " + j 5713 + " due to action " + action + " at " + i); 5714 j--; 5715 N--; 5716 } 5717 } 5718 } 5719 5720 // If the caller didn't request filter information, drop it now 5721 // so we don't have to marshall/unmarshall it. 5722 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5723 rii.filter = null; 5724 } 5725 } 5726 5727 // Filter out the caller activity if so requested. 5728 if (caller != null) { 5729 N = results.size(); 5730 for (int i=0; i<N; i++) { 5731 ActivityInfo ainfo = results.get(i).activityInfo; 5732 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5733 && caller.getClassName().equals(ainfo.name)) { 5734 results.remove(i); 5735 break; 5736 } 5737 } 5738 } 5739 5740 // If the caller didn't request filter information, 5741 // drop them now so we don't have to 5742 // marshall/unmarshall it. 5743 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5744 N = results.size(); 5745 for (int i=0; i<N; i++) { 5746 results.get(i).filter = null; 5747 } 5748 } 5749 5750 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5751 return results; 5752 } 5753 5754 @Override 5755 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 5756 String resolvedType, int flags, int userId) { 5757 return new ParceledListSlice<>( 5758 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 5759 } 5760 5761 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 5762 String resolvedType, int flags, int userId) { 5763 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5764 flags = updateFlagsForResolve(flags, userId, intent); 5765 ComponentName comp = intent.getComponent(); 5766 if (comp == null) { 5767 if (intent.getSelector() != null) { 5768 intent = intent.getSelector(); 5769 comp = intent.getComponent(); 5770 } 5771 } 5772 if (comp != null) { 5773 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5774 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5775 if (ai != null) { 5776 ResolveInfo ri = new ResolveInfo(); 5777 ri.activityInfo = ai; 5778 list.add(ri); 5779 } 5780 return list; 5781 } 5782 5783 // reader 5784 synchronized (mPackages) { 5785 String pkgName = intent.getPackage(); 5786 if (pkgName == null) { 5787 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5788 } 5789 final PackageParser.Package pkg = mPackages.get(pkgName); 5790 if (pkg != null) { 5791 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5792 userId); 5793 } 5794 return Collections.emptyList(); 5795 } 5796 } 5797 5798 @Override 5799 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5800 if (!sUserManager.exists(userId)) return null; 5801 flags = updateFlagsForResolve(flags, userId, intent); 5802 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 5803 if (query != null) { 5804 if (query.size() >= 1) { 5805 // If there is more than one service with the same priority, 5806 // just arbitrarily pick the first one. 5807 return query.get(0); 5808 } 5809 } 5810 return null; 5811 } 5812 5813 @Override 5814 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 5815 String resolvedType, int flags, int userId) { 5816 return new ParceledListSlice<>( 5817 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 5818 } 5819 5820 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 5821 String resolvedType, int flags, int userId) { 5822 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5823 flags = updateFlagsForResolve(flags, userId, intent); 5824 ComponentName comp = intent.getComponent(); 5825 if (comp == null) { 5826 if (intent.getSelector() != null) { 5827 intent = intent.getSelector(); 5828 comp = intent.getComponent(); 5829 } 5830 } 5831 if (comp != null) { 5832 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5833 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5834 if (si != null) { 5835 final ResolveInfo ri = new ResolveInfo(); 5836 ri.serviceInfo = si; 5837 list.add(ri); 5838 } 5839 return list; 5840 } 5841 5842 // reader 5843 synchronized (mPackages) { 5844 String pkgName = intent.getPackage(); 5845 if (pkgName == null) { 5846 return mServices.queryIntent(intent, resolvedType, flags, userId); 5847 } 5848 final PackageParser.Package pkg = mPackages.get(pkgName); 5849 if (pkg != null) { 5850 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5851 userId); 5852 } 5853 return Collections.emptyList(); 5854 } 5855 } 5856 5857 @Override 5858 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 5859 String resolvedType, int flags, int userId) { 5860 return new ParceledListSlice<>( 5861 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 5862 } 5863 5864 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 5865 Intent intent, String resolvedType, int flags, int userId) { 5866 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5867 flags = updateFlagsForResolve(flags, userId, intent); 5868 ComponentName comp = intent.getComponent(); 5869 if (comp == null) { 5870 if (intent.getSelector() != null) { 5871 intent = intent.getSelector(); 5872 comp = intent.getComponent(); 5873 } 5874 } 5875 if (comp != null) { 5876 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5877 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5878 if (pi != null) { 5879 final ResolveInfo ri = new ResolveInfo(); 5880 ri.providerInfo = pi; 5881 list.add(ri); 5882 } 5883 return list; 5884 } 5885 5886 // reader 5887 synchronized (mPackages) { 5888 String pkgName = intent.getPackage(); 5889 if (pkgName == null) { 5890 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5891 } 5892 final PackageParser.Package pkg = mPackages.get(pkgName); 5893 if (pkg != null) { 5894 return mProviders.queryIntentForPackage( 5895 intent, resolvedType, flags, pkg.providers, userId); 5896 } 5897 return Collections.emptyList(); 5898 } 5899 } 5900 5901 @Override 5902 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5903 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5904 flags = updateFlagsForPackage(flags, userId, null); 5905 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5906 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5907 true /* requireFullPermission */, false /* checkShell */, 5908 "get installed packages"); 5909 5910 // writer 5911 synchronized (mPackages) { 5912 ArrayList<PackageInfo> list; 5913 if (listUninstalled) { 5914 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5915 for (PackageSetting ps : mSettings.mPackages.values()) { 5916 PackageInfo pi; 5917 if (ps.pkg != null) { 5918 pi = generatePackageInfo(ps.pkg, flags, userId); 5919 } else { 5920 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5921 } 5922 if (pi != null) { 5923 list.add(pi); 5924 } 5925 } 5926 } else { 5927 list = new ArrayList<PackageInfo>(mPackages.size()); 5928 for (PackageParser.Package p : mPackages.values()) { 5929 PackageInfo pi = generatePackageInfo(p, flags, userId); 5930 if (pi != null) { 5931 list.add(pi); 5932 } 5933 } 5934 } 5935 5936 return new ParceledListSlice<PackageInfo>(list); 5937 } 5938 } 5939 5940 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5941 String[] permissions, boolean[] tmp, int flags, int userId) { 5942 int numMatch = 0; 5943 final PermissionsState permissionsState = ps.getPermissionsState(); 5944 for (int i=0; i<permissions.length; i++) { 5945 final String permission = permissions[i]; 5946 if (permissionsState.hasPermission(permission, userId)) { 5947 tmp[i] = true; 5948 numMatch++; 5949 } else { 5950 tmp[i] = false; 5951 } 5952 } 5953 if (numMatch == 0) { 5954 return; 5955 } 5956 PackageInfo pi; 5957 if (ps.pkg != null) { 5958 pi = generatePackageInfo(ps.pkg, flags, userId); 5959 } else { 5960 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5961 } 5962 // The above might return null in cases of uninstalled apps or install-state 5963 // skew across users/profiles. 5964 if (pi != null) { 5965 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5966 if (numMatch == permissions.length) { 5967 pi.requestedPermissions = permissions; 5968 } else { 5969 pi.requestedPermissions = new String[numMatch]; 5970 numMatch = 0; 5971 for (int i=0; i<permissions.length; i++) { 5972 if (tmp[i]) { 5973 pi.requestedPermissions[numMatch] = permissions[i]; 5974 numMatch++; 5975 } 5976 } 5977 } 5978 } 5979 list.add(pi); 5980 } 5981 } 5982 5983 @Override 5984 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5985 String[] permissions, int flags, int userId) { 5986 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5987 flags = updateFlagsForPackage(flags, userId, permissions); 5988 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5989 5990 // writer 5991 synchronized (mPackages) { 5992 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5993 boolean[] tmpBools = new boolean[permissions.length]; 5994 if (listUninstalled) { 5995 for (PackageSetting ps : mSettings.mPackages.values()) { 5996 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5997 } 5998 } else { 5999 for (PackageParser.Package pkg : mPackages.values()) { 6000 PackageSetting ps = (PackageSetting)pkg.mExtras; 6001 if (ps != null) { 6002 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6003 userId); 6004 } 6005 } 6006 } 6007 6008 return new ParceledListSlice<PackageInfo>(list); 6009 } 6010 } 6011 6012 @Override 6013 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6014 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6015 flags = updateFlagsForApplication(flags, userId, null); 6016 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6017 6018 // writer 6019 synchronized (mPackages) { 6020 ArrayList<ApplicationInfo> list; 6021 if (listUninstalled) { 6022 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6023 for (PackageSetting ps : mSettings.mPackages.values()) { 6024 ApplicationInfo ai; 6025 if (ps.pkg != null) { 6026 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6027 ps.readUserState(userId), userId); 6028 } else { 6029 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6030 } 6031 if (ai != null) { 6032 list.add(ai); 6033 } 6034 } 6035 } else { 6036 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6037 for (PackageParser.Package p : mPackages.values()) { 6038 if (p.mExtras != null) { 6039 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6040 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6041 if (ai != null) { 6042 list.add(ai); 6043 } 6044 } 6045 } 6046 } 6047 6048 return new ParceledListSlice<ApplicationInfo>(list); 6049 } 6050 } 6051 6052 @Override 6053 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6054 if (DISABLE_EPHEMERAL_APPS) { 6055 return null; 6056 } 6057 6058 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6059 "getEphemeralApplications"); 6060 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6061 true /* requireFullPermission */, false /* checkShell */, 6062 "getEphemeralApplications"); 6063 synchronized (mPackages) { 6064 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6065 .getEphemeralApplicationsLPw(userId); 6066 if (ephemeralApps != null) { 6067 return new ParceledListSlice<>(ephemeralApps); 6068 } 6069 } 6070 return null; 6071 } 6072 6073 @Override 6074 public boolean isEphemeralApplication(String packageName, int userId) { 6075 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6076 true /* requireFullPermission */, false /* checkShell */, 6077 "isEphemeral"); 6078 if (DISABLE_EPHEMERAL_APPS) { 6079 return false; 6080 } 6081 6082 if (!isCallerSameApp(packageName)) { 6083 return false; 6084 } 6085 synchronized (mPackages) { 6086 PackageParser.Package pkg = mPackages.get(packageName); 6087 if (pkg != null) { 6088 return pkg.applicationInfo.isEphemeralApp(); 6089 } 6090 } 6091 return false; 6092 } 6093 6094 @Override 6095 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6096 if (DISABLE_EPHEMERAL_APPS) { 6097 return null; 6098 } 6099 6100 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6101 true /* requireFullPermission */, false /* checkShell */, 6102 "getCookie"); 6103 if (!isCallerSameApp(packageName)) { 6104 return null; 6105 } 6106 synchronized (mPackages) { 6107 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6108 packageName, userId); 6109 } 6110 } 6111 6112 @Override 6113 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6114 if (DISABLE_EPHEMERAL_APPS) { 6115 return true; 6116 } 6117 6118 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6119 true /* requireFullPermission */, true /* checkShell */, 6120 "setCookie"); 6121 if (!isCallerSameApp(packageName)) { 6122 return false; 6123 } 6124 synchronized (mPackages) { 6125 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6126 packageName, cookie, userId); 6127 } 6128 } 6129 6130 @Override 6131 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6132 if (DISABLE_EPHEMERAL_APPS) { 6133 return null; 6134 } 6135 6136 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6137 "getEphemeralApplicationIcon"); 6138 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6139 true /* requireFullPermission */, false /* checkShell */, 6140 "getEphemeralApplicationIcon"); 6141 synchronized (mPackages) { 6142 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6143 packageName, userId); 6144 } 6145 } 6146 6147 private boolean isCallerSameApp(String packageName) { 6148 PackageParser.Package pkg = mPackages.get(packageName); 6149 return pkg != null 6150 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6151 } 6152 6153 @Override 6154 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6155 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6156 } 6157 6158 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6159 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6160 6161 // reader 6162 synchronized (mPackages) { 6163 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6164 final int userId = UserHandle.getCallingUserId(); 6165 while (i.hasNext()) { 6166 final PackageParser.Package p = i.next(); 6167 if (p.applicationInfo == null) continue; 6168 6169 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6170 && !p.applicationInfo.isDirectBootAware(); 6171 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6172 && p.applicationInfo.isDirectBootAware(); 6173 6174 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6175 && (!mSafeMode || isSystemApp(p)) 6176 && (matchesUnaware || matchesAware)) { 6177 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6178 if (ps != null) { 6179 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6180 ps.readUserState(userId), userId); 6181 if (ai != null) { 6182 finalList.add(ai); 6183 } 6184 } 6185 } 6186 } 6187 } 6188 6189 return finalList; 6190 } 6191 6192 @Override 6193 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6194 if (!sUserManager.exists(userId)) return null; 6195 flags = updateFlagsForComponent(flags, userId, name); 6196 // reader 6197 synchronized (mPackages) { 6198 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6199 PackageSetting ps = provider != null 6200 ? mSettings.mPackages.get(provider.owner.packageName) 6201 : null; 6202 return ps != null 6203 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6204 ? PackageParser.generateProviderInfo(provider, flags, 6205 ps.readUserState(userId), userId) 6206 : null; 6207 } 6208 } 6209 6210 /** 6211 * @deprecated 6212 */ 6213 @Deprecated 6214 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6215 // reader 6216 synchronized (mPackages) { 6217 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6218 .entrySet().iterator(); 6219 final int userId = UserHandle.getCallingUserId(); 6220 while (i.hasNext()) { 6221 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6222 PackageParser.Provider p = entry.getValue(); 6223 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6224 6225 if (ps != null && p.syncable 6226 && (!mSafeMode || (p.info.applicationInfo.flags 6227 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6228 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6229 ps.readUserState(userId), userId); 6230 if (info != null) { 6231 outNames.add(entry.getKey()); 6232 outInfo.add(info); 6233 } 6234 } 6235 } 6236 } 6237 } 6238 6239 @Override 6240 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6241 int uid, int flags) { 6242 final int userId = processName != null ? UserHandle.getUserId(uid) 6243 : UserHandle.getCallingUserId(); 6244 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6245 flags = updateFlagsForComponent(flags, userId, processName); 6246 6247 ArrayList<ProviderInfo> finalList = null; 6248 // reader 6249 synchronized (mPackages) { 6250 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6251 while (i.hasNext()) { 6252 final PackageParser.Provider p = i.next(); 6253 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6254 if (ps != null && p.info.authority != null 6255 && (processName == null 6256 || (p.info.processName.equals(processName) 6257 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6258 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6259 if (finalList == null) { 6260 finalList = new ArrayList<ProviderInfo>(3); 6261 } 6262 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6263 ps.readUserState(userId), userId); 6264 if (info != null) { 6265 finalList.add(info); 6266 } 6267 } 6268 } 6269 } 6270 6271 if (finalList != null) { 6272 Collections.sort(finalList, mProviderInitOrderSorter); 6273 return new ParceledListSlice<ProviderInfo>(finalList); 6274 } 6275 6276 return ParceledListSlice.emptyList(); 6277 } 6278 6279 @Override 6280 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6281 // reader 6282 synchronized (mPackages) { 6283 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6284 return PackageParser.generateInstrumentationInfo(i, flags); 6285 } 6286 } 6287 6288 @Override 6289 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6290 String targetPackage, int flags) { 6291 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6292 } 6293 6294 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6295 int flags) { 6296 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6297 6298 // reader 6299 synchronized (mPackages) { 6300 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6301 while (i.hasNext()) { 6302 final PackageParser.Instrumentation p = i.next(); 6303 if (targetPackage == null 6304 || targetPackage.equals(p.info.targetPackage)) { 6305 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6306 flags); 6307 if (ii != null) { 6308 finalList.add(ii); 6309 } 6310 } 6311 } 6312 } 6313 6314 return finalList; 6315 } 6316 6317 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6318 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6319 if (overlays == null) { 6320 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6321 return; 6322 } 6323 for (PackageParser.Package opkg : overlays.values()) { 6324 // Not much to do if idmap fails: we already logged the error 6325 // and we certainly don't want to abort installation of pkg simply 6326 // because an overlay didn't fit properly. For these reasons, 6327 // ignore the return value of createIdmapForPackagePairLI. 6328 createIdmapForPackagePairLI(pkg, opkg); 6329 } 6330 } 6331 6332 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6333 PackageParser.Package opkg) { 6334 if (!opkg.mTrustedOverlay) { 6335 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6336 opkg.baseCodePath + ": overlay not trusted"); 6337 return false; 6338 } 6339 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6340 if (overlaySet == null) { 6341 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6342 opkg.baseCodePath + " but target package has no known overlays"); 6343 return false; 6344 } 6345 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6346 // TODO: generate idmap for split APKs 6347 try { 6348 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6349 } catch (InstallerException e) { 6350 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6351 + opkg.baseCodePath); 6352 return false; 6353 } 6354 PackageParser.Package[] overlayArray = 6355 overlaySet.values().toArray(new PackageParser.Package[0]); 6356 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6357 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6358 return p1.mOverlayPriority - p2.mOverlayPriority; 6359 } 6360 }; 6361 Arrays.sort(overlayArray, cmp); 6362 6363 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6364 int i = 0; 6365 for (PackageParser.Package p : overlayArray) { 6366 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6367 } 6368 return true; 6369 } 6370 6371 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6372 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6373 try { 6374 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6375 } finally { 6376 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6377 } 6378 } 6379 6380 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6381 final File[] files = dir.listFiles(); 6382 if (ArrayUtils.isEmpty(files)) { 6383 Log.d(TAG, "No files in app dir " + dir); 6384 return; 6385 } 6386 6387 if (DEBUG_PACKAGE_SCANNING) { 6388 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6389 + " flags=0x" + Integer.toHexString(parseFlags)); 6390 } 6391 6392 for (File file : files) { 6393 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6394 && !PackageInstallerService.isStageName(file.getName()); 6395 if (!isPackage) { 6396 // Ignore entries which are not packages 6397 continue; 6398 } 6399 try { 6400 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6401 scanFlags, currentTime, null); 6402 } catch (PackageManagerException e) { 6403 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6404 6405 // Delete invalid userdata apps 6406 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6407 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6408 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6409 removeCodePathLI(file); 6410 } 6411 } 6412 } 6413 } 6414 6415 private static File getSettingsProblemFile() { 6416 File dataDir = Environment.getDataDirectory(); 6417 File systemDir = new File(dataDir, "system"); 6418 File fname = new File(systemDir, "uiderrors.txt"); 6419 return fname; 6420 } 6421 6422 static void reportSettingsProblem(int priority, String msg) { 6423 logCriticalInfo(priority, msg); 6424 } 6425 6426 static void logCriticalInfo(int priority, String msg) { 6427 Slog.println(priority, TAG, msg); 6428 EventLogTags.writePmCriticalInfo(msg); 6429 try { 6430 File fname = getSettingsProblemFile(); 6431 FileOutputStream out = new FileOutputStream(fname, true); 6432 PrintWriter pw = new FastPrintWriter(out); 6433 SimpleDateFormat formatter = new SimpleDateFormat(); 6434 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6435 pw.println(dateString + ": " + msg); 6436 pw.close(); 6437 FileUtils.setPermissions( 6438 fname.toString(), 6439 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6440 -1, -1); 6441 } catch (java.io.IOException e) { 6442 } 6443 } 6444 6445 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6446 int parseFlags) throws PackageManagerException { 6447 if (ps != null 6448 && ps.codePath.equals(srcFile) 6449 && ps.timeStamp == srcFile.lastModified() 6450 && !isCompatSignatureUpdateNeeded(pkg) 6451 && !isRecoverSignatureUpdateNeeded(pkg)) { 6452 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6453 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6454 ArraySet<PublicKey> signingKs; 6455 synchronized (mPackages) { 6456 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6457 } 6458 if (ps.signatures.mSignatures != null 6459 && ps.signatures.mSignatures.length != 0 6460 && signingKs != null) { 6461 // Optimization: reuse the existing cached certificates 6462 // if the package appears to be unchanged. 6463 pkg.mSignatures = ps.signatures.mSignatures; 6464 pkg.mSigningKeys = signingKs; 6465 return; 6466 } 6467 6468 Slog.w(TAG, "PackageSetting for " + ps.name 6469 + " is missing signatures. Collecting certs again to recover them."); 6470 } else { 6471 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6472 } 6473 6474 try { 6475 PackageParser.collectCertificates(pkg, parseFlags); 6476 } catch (PackageParserException e) { 6477 throw PackageManagerException.from(e); 6478 } 6479 } 6480 6481 /** 6482 * Traces a package scan. 6483 * @see #scanPackageLI(File, int, int, long, UserHandle) 6484 */ 6485 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6486 long currentTime, UserHandle user) throws PackageManagerException { 6487 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6488 try { 6489 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6490 } finally { 6491 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6492 } 6493 } 6494 6495 /** 6496 * Scans a package and returns the newly parsed package. 6497 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6498 */ 6499 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6500 long currentTime, UserHandle user) throws PackageManagerException { 6501 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6502 parseFlags |= mDefParseFlags; 6503 PackageParser pp = new PackageParser(); 6504 pp.setSeparateProcesses(mSeparateProcesses); 6505 pp.setOnlyCoreApps(mOnlyCore); 6506 pp.setDisplayMetrics(mMetrics); 6507 6508 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6509 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6510 } 6511 6512 final PackageParser.Package pkg; 6513 try { 6514 pkg = pp.parsePackage(scanFile, parseFlags); 6515 } catch (PackageParserException e) { 6516 throw PackageManagerException.from(e); 6517 } 6518 6519 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6520 } 6521 6522 /** 6523 * Scans a package and returns the newly parsed package. 6524 * @throws PackageManagerException on a parse error. 6525 */ 6526 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6527 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6528 throws PackageManagerException { 6529 // If the package has children and this is the first dive in the function 6530 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6531 // packages (parent and children) would be successfully scanned before the 6532 // actual scan since scanning mutates internal state and we want to atomically 6533 // install the package and its children. 6534 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6535 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6536 scanFlags |= SCAN_CHECK_ONLY; 6537 } 6538 } else { 6539 scanFlags &= ~SCAN_CHECK_ONLY; 6540 } 6541 6542 // Scan the parent 6543 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags, 6544 scanFlags, currentTime, user); 6545 6546 // Scan the children 6547 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6548 for (int i = 0; i < childCount; i++) { 6549 PackageParser.Package childPackage = pkg.childPackages.get(i); 6550 scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags, 6551 currentTime, user); 6552 } 6553 6554 6555 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6556 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6557 } 6558 6559 return scannedPkg; 6560 } 6561 6562 /** 6563 * Scans a package and returns the newly parsed package. 6564 * @throws PackageManagerException on a parse error. 6565 */ 6566 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6567 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6568 throws PackageManagerException { 6569 PackageSetting ps = null; 6570 PackageSetting updatedPkg; 6571 // reader 6572 synchronized (mPackages) { 6573 // Look to see if we already know about this package. 6574 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6575 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6576 // This package has been renamed to its original name. Let's 6577 // use that. 6578 ps = mSettings.peekPackageLPr(oldName); 6579 } 6580 // If there was no original package, see one for the real package name. 6581 if (ps == null) { 6582 ps = mSettings.peekPackageLPr(pkg.packageName); 6583 } 6584 // Check to see if this package could be hiding/updating a system 6585 // package. Must look for it either under the original or real 6586 // package name depending on our state. 6587 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6588 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6589 6590 // If this is a package we don't know about on the system partition, we 6591 // may need to remove disabled child packages on the system partition 6592 // or may need to not add child packages if the parent apk is updated 6593 // on the data partition and no longer defines this child package. 6594 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6595 // If this is a parent package for an updated system app and this system 6596 // app got an OTA update which no longer defines some of the child packages 6597 // we have to prune them from the disabled system packages. 6598 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6599 if (disabledPs != null) { 6600 final int scannedChildCount = (pkg.childPackages != null) 6601 ? pkg.childPackages.size() : 0; 6602 final int disabledChildCount = disabledPs.childPackageNames != null 6603 ? disabledPs.childPackageNames.size() : 0; 6604 for (int i = 0; i < disabledChildCount; i++) { 6605 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6606 boolean disabledPackageAvailable = false; 6607 for (int j = 0; j < scannedChildCount; j++) { 6608 PackageParser.Package childPkg = pkg.childPackages.get(j); 6609 if (childPkg.packageName.equals(disabledChildPackageName)) { 6610 disabledPackageAvailable = true; 6611 break; 6612 } 6613 } 6614 if (!disabledPackageAvailable) { 6615 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6616 } 6617 } 6618 } 6619 } 6620 } 6621 6622 boolean updatedPkgBetter = false; 6623 // First check if this is a system package that may involve an update 6624 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6625 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6626 // it needs to drop FLAG_PRIVILEGED. 6627 if (locationIsPrivileged(scanFile)) { 6628 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6629 } else { 6630 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6631 } 6632 6633 if (ps != null && !ps.codePath.equals(scanFile)) { 6634 // The path has changed from what was last scanned... check the 6635 // version of the new path against what we have stored to determine 6636 // what to do. 6637 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6638 if (pkg.mVersionCode <= ps.versionCode) { 6639 // The system package has been updated and the code path does not match 6640 // Ignore entry. Skip it. 6641 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6642 + " ignored: updated version " + ps.versionCode 6643 + " better than this " + pkg.mVersionCode); 6644 if (!updatedPkg.codePath.equals(scanFile)) { 6645 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6646 + ps.name + " changing from " + updatedPkg.codePathString 6647 + " to " + scanFile); 6648 updatedPkg.codePath = scanFile; 6649 updatedPkg.codePathString = scanFile.toString(); 6650 updatedPkg.resourcePath = scanFile; 6651 updatedPkg.resourcePathString = scanFile.toString(); 6652 } 6653 updatedPkg.pkg = pkg; 6654 updatedPkg.versionCode = pkg.mVersionCode; 6655 6656 // Update the disabled system child packages to point to the package too. 6657 final int childCount = updatedPkg.childPackageNames != null 6658 ? updatedPkg.childPackageNames.size() : 0; 6659 for (int i = 0; i < childCount; i++) { 6660 String childPackageName = updatedPkg.childPackageNames.get(i); 6661 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6662 childPackageName); 6663 if (updatedChildPkg != null) { 6664 updatedChildPkg.pkg = pkg; 6665 updatedChildPkg.versionCode = pkg.mVersionCode; 6666 } 6667 } 6668 6669 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6670 + scanFile + " ignored: updated version " + ps.versionCode 6671 + " better than this " + pkg.mVersionCode); 6672 } else { 6673 // The current app on the system partition is better than 6674 // what we have updated to on the data partition; switch 6675 // back to the system partition version. 6676 // At this point, its safely assumed that package installation for 6677 // apps in system partition will go through. If not there won't be a working 6678 // version of the app 6679 // writer 6680 synchronized (mPackages) { 6681 // Just remove the loaded entries from package lists. 6682 mPackages.remove(ps.name); 6683 } 6684 6685 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6686 + " reverting from " + ps.codePathString 6687 + ": new version " + pkg.mVersionCode 6688 + " better than installed " + ps.versionCode); 6689 6690 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6691 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6692 synchronized (mInstallLock) { 6693 args.cleanUpResourcesLI(); 6694 } 6695 synchronized (mPackages) { 6696 mSettings.enableSystemPackageLPw(ps.name); 6697 } 6698 updatedPkgBetter = true; 6699 } 6700 } 6701 } 6702 6703 if (updatedPkg != null) { 6704 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6705 // initially 6706 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6707 6708 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6709 // flag set initially 6710 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6711 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6712 } 6713 } 6714 6715 // Verify certificates against what was last scanned 6716 collectCertificatesLI(ps, pkg, scanFile, parseFlags); 6717 6718 /* 6719 * A new system app appeared, but we already had a non-system one of the 6720 * same name installed earlier. 6721 */ 6722 boolean shouldHideSystemApp = false; 6723 if (updatedPkg == null && ps != null 6724 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6725 /* 6726 * Check to make sure the signatures match first. If they don't, 6727 * wipe the installed application and its data. 6728 */ 6729 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6730 != PackageManager.SIGNATURE_MATCH) { 6731 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6732 + " signatures don't match existing userdata copy; removing"); 6733 deletePackageLI(pkg.packageName, null, true, null, 0, null, false, null); 6734 ps = null; 6735 } else { 6736 /* 6737 * If the newly-added system app is an older version than the 6738 * already installed version, hide it. It will be scanned later 6739 * and re-added like an update. 6740 */ 6741 if (pkg.mVersionCode <= ps.versionCode) { 6742 shouldHideSystemApp = true; 6743 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6744 + " but new version " + pkg.mVersionCode + " better than installed " 6745 + ps.versionCode + "; hiding system"); 6746 } else { 6747 /* 6748 * The newly found system app is a newer version that the 6749 * one previously installed. Simply remove the 6750 * already-installed application and replace it with our own 6751 * while keeping the application data. 6752 */ 6753 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6754 + " reverting from " + ps.codePathString + ": new version " 6755 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6756 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6757 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6758 synchronized (mInstallLock) { 6759 args.cleanUpResourcesLI(); 6760 } 6761 } 6762 } 6763 } 6764 6765 // The apk is forward locked (not public) if its code and resources 6766 // are kept in different files. (except for app in either system or 6767 // vendor path). 6768 // TODO grab this value from PackageSettings 6769 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6770 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6771 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6772 } 6773 } 6774 6775 // TODO: extend to support forward-locked splits 6776 String resourcePath = null; 6777 String baseResourcePath = null; 6778 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6779 if (ps != null && ps.resourcePathString != null) { 6780 resourcePath = ps.resourcePathString; 6781 baseResourcePath = ps.resourcePathString; 6782 } else { 6783 // Should not happen at all. Just log an error. 6784 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6785 } 6786 } else { 6787 resourcePath = pkg.codePath; 6788 baseResourcePath = pkg.baseCodePath; 6789 } 6790 6791 // Set application objects path explicitly. 6792 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 6793 pkg.setApplicationInfoCodePath(pkg.codePath); 6794 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 6795 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 6796 pkg.setApplicationInfoResourcePath(resourcePath); 6797 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 6798 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 6799 6800 // Note that we invoke the following method only if we are about to unpack an application 6801 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6802 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6803 6804 /* 6805 * If the system app should be overridden by a previously installed 6806 * data, hide the system app now and let the /data/app scan pick it up 6807 * again. 6808 */ 6809 if (shouldHideSystemApp) { 6810 synchronized (mPackages) { 6811 mSettings.disableSystemPackageLPw(pkg.packageName, true); 6812 } 6813 } 6814 6815 return scannedPkg; 6816 } 6817 6818 private static String fixProcessName(String defProcessName, 6819 String processName, int uid) { 6820 if (processName == null) { 6821 return defProcessName; 6822 } 6823 return processName; 6824 } 6825 6826 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6827 throws PackageManagerException { 6828 if (pkgSetting.signatures.mSignatures != null) { 6829 // Already existing package. Make sure signatures match 6830 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6831 == PackageManager.SIGNATURE_MATCH; 6832 if (!match) { 6833 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6834 == PackageManager.SIGNATURE_MATCH; 6835 } 6836 if (!match) { 6837 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6838 == PackageManager.SIGNATURE_MATCH; 6839 } 6840 if (!match) { 6841 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6842 + pkg.packageName + " signatures do not match the " 6843 + "previously installed version; ignoring!"); 6844 } 6845 } 6846 6847 // Check for shared user signatures 6848 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6849 // Already existing package. Make sure signatures match 6850 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6851 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6852 if (!match) { 6853 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6854 == PackageManager.SIGNATURE_MATCH; 6855 } 6856 if (!match) { 6857 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6858 == PackageManager.SIGNATURE_MATCH; 6859 } 6860 if (!match) { 6861 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6862 "Package " + pkg.packageName 6863 + " has no signatures that match those in shared user " 6864 + pkgSetting.sharedUser.name + "; ignoring!"); 6865 } 6866 } 6867 } 6868 6869 /** 6870 * Enforces that only the system UID or root's UID can call a method exposed 6871 * via Binder. 6872 * 6873 * @param message used as message if SecurityException is thrown 6874 * @throws SecurityException if the caller is not system or root 6875 */ 6876 private static final void enforceSystemOrRoot(String message) { 6877 final int uid = Binder.getCallingUid(); 6878 if (uid != Process.SYSTEM_UID && uid != 0) { 6879 throw new SecurityException(message); 6880 } 6881 } 6882 6883 @Override 6884 public void performFstrimIfNeeded() { 6885 enforceSystemOrRoot("Only the system can request fstrim"); 6886 6887 // Before everything else, see whether we need to fstrim. 6888 try { 6889 IMountService ms = PackageHelper.getMountService(); 6890 if (ms != null) { 6891 final boolean isUpgrade = isUpgrade(); 6892 boolean doTrim = isUpgrade; 6893 if (doTrim) { 6894 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6895 } else { 6896 final long interval = android.provider.Settings.Global.getLong( 6897 mContext.getContentResolver(), 6898 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6899 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6900 if (interval > 0) { 6901 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6902 if (timeSinceLast > interval) { 6903 doTrim = true; 6904 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6905 + "; running immediately"); 6906 } 6907 } 6908 } 6909 if (doTrim) { 6910 if (!isFirstBoot()) { 6911 try { 6912 ActivityManagerNative.getDefault().showBootMessage( 6913 mContext.getResources().getString( 6914 R.string.android_upgrading_fstrim), true); 6915 } catch (RemoteException e) { 6916 } 6917 } 6918 ms.runMaintenance(); 6919 } 6920 } else { 6921 Slog.e(TAG, "Mount service unavailable!"); 6922 } 6923 } catch (RemoteException e) { 6924 // Can't happen; MountService is local 6925 } 6926 } 6927 6928 @Override 6929 public void updatePackagesIfNeeded() { 6930 enforceSystemOrRoot("Only the system can request package update"); 6931 6932 // We need to re-extract after an OTA. 6933 boolean causeUpgrade = isUpgrade(); 6934 6935 // First boot or factory reset. 6936 // Note: we also handle devices that are upgrading to N right now as if it is their 6937 // first boot, as they do not have profile data. 6938 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 6939 6940 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 6941 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 6942 6943 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 6944 return; 6945 } 6946 6947 List<PackageParser.Package> pkgs; 6948 synchronized (mPackages) { 6949 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 6950 } 6951 6952 int curr = 0; 6953 int total = pkgs.size(); 6954 for (PackageParser.Package pkg : pkgs) { 6955 curr++; 6956 6957 if (DEBUG_DEXOPT) { 6958 Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName); 6959 } 6960 6961 if (PackageDexOptimizer.canOptimizePackage(pkg)) { 6962 // If the cache was pruned, any compiled odex files will likely be out of date 6963 // and would have to be patched (would be SELF_PATCHOAT, which is deprecated). 6964 // Instead, force the extraction in this case. 6965 performDexOpt(pkg.packageName, 6966 null /* instructionSet */, 6967 false /* checkProfiles */, 6968 causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT, 6969 false /* force */); 6970 } 6971 } 6972 } 6973 6974 @Override 6975 public void notifyPackageUse(String packageName) { 6976 synchronized (mPackages) { 6977 PackageParser.Package p = mPackages.get(packageName); 6978 if (p == null) { 6979 return; 6980 } 6981 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6982 } 6983 } 6984 6985 // TODO: this is not used nor needed. Delete it. 6986 @Override 6987 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6988 return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */, 6989 getFullCompilerFilter(), false /* force */); 6990 } 6991 6992 @Override 6993 public boolean performDexOpt(String packageName, String instructionSet, 6994 boolean checkProfiles, int compileReason, boolean force) { 6995 return performDexOptTraced(packageName, instructionSet, checkProfiles, 6996 getCompilerFilterForReason(compileReason), force); 6997 } 6998 6999 @Override 7000 public boolean performDexOptMode(String packageName, String instructionSet, 7001 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7002 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7003 targetCompilerFilter, force); 7004 } 7005 7006 private boolean performDexOptTraced(String packageName, String instructionSet, 7007 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7008 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7009 try { 7010 return performDexOptInternal(packageName, instructionSet, checkProfiles, 7011 targetCompilerFilter, force); 7012 } finally { 7013 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7014 } 7015 } 7016 7017 private boolean performDexOptInternal(String packageName, String instructionSet, 7018 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7019 PackageParser.Package p; 7020 final String targetInstructionSet; 7021 synchronized (mPackages) { 7022 p = mPackages.get(packageName); 7023 if (p == null) { 7024 return false; 7025 } 7026 mPackageUsage.write(false); 7027 7028 targetInstructionSet = instructionSet != null ? instructionSet : 7029 getPrimaryInstructionSet(p.applicationInfo); 7030 } 7031 long callingId = Binder.clearCallingIdentity(); 7032 try { 7033 synchronized (mInstallLock) { 7034 final String[] instructionSets = new String[] { targetInstructionSet }; 7035 int result = performDexOptInternalWithDependenciesLI(p, instructionSets, 7036 checkProfiles, targetCompilerFilter, force); 7037 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 7038 } 7039 } finally { 7040 Binder.restoreCallingIdentity(callingId); 7041 } 7042 } 7043 7044 public ArraySet<String> getOptimizablePackages() { 7045 ArraySet<String> pkgs = new ArraySet<String>(); 7046 synchronized (mPackages) { 7047 for (PackageParser.Package p : mPackages.values()) { 7048 if (PackageDexOptimizer.canOptimizePackage(p)) { 7049 pkgs.add(p.packageName); 7050 } 7051 } 7052 } 7053 return pkgs; 7054 } 7055 7056 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7057 String instructionSets[], boolean checkProfiles, String targetCompilerFilter, 7058 boolean force) { 7059 // Select the dex optimizer based on the force parameter. 7060 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7061 // allocate an object here. 7062 PackageDexOptimizer pdo = force 7063 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7064 : mPackageDexOptimizer; 7065 7066 // Optimize all dependencies first. Note: we ignore the return value and march on 7067 // on errors. 7068 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7069 if (!deps.isEmpty()) { 7070 for (PackageParser.Package depPackage : deps) { 7071 // TODO: Analyze and investigate if we (should) profile libraries. 7072 // Currently this will do a full compilation of the library by default. 7073 pdo.performDexOpt(depPackage, instructionSets, false /* checkProfiles */, 7074 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7075 } 7076 } 7077 7078 return pdo.performDexOpt(p, instructionSets, checkProfiles, targetCompilerFilter); 7079 } 7080 7081 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7082 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7083 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7084 Set<String> collectedNames = new HashSet<>(); 7085 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7086 7087 retValue.remove(p); 7088 7089 return retValue; 7090 } else { 7091 return Collections.emptyList(); 7092 } 7093 } 7094 7095 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7096 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7097 if (!collectedNames.contains(p.packageName)) { 7098 collectedNames.add(p.packageName); 7099 collected.add(p); 7100 7101 if (p.usesLibraries != null) { 7102 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7103 } 7104 if (p.usesOptionalLibraries != null) { 7105 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7106 collectedNames); 7107 } 7108 } 7109 } 7110 7111 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7112 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7113 for (String libName : libs) { 7114 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7115 if (libPkg != null) { 7116 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7117 } 7118 } 7119 } 7120 7121 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7122 synchronized (mPackages) { 7123 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7124 if (lib != null && lib.apk != null) { 7125 return mPackages.get(lib.apk); 7126 } 7127 } 7128 return null; 7129 } 7130 7131 public void shutdown() { 7132 mPackageUsage.write(true); 7133 } 7134 7135 @Override 7136 public void forceDexOpt(String packageName) { 7137 enforceSystemOrRoot("forceDexOpt"); 7138 7139 PackageParser.Package pkg; 7140 synchronized (mPackages) { 7141 pkg = mPackages.get(packageName); 7142 if (pkg == null) { 7143 throw new IllegalArgumentException("Unknown package: " + packageName); 7144 } 7145 } 7146 7147 synchronized (mInstallLock) { 7148 final String[] instructionSets = new String[] { 7149 getPrimaryInstructionSet(pkg.applicationInfo) }; 7150 7151 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7152 7153 // Whoever is calling forceDexOpt wants a fully compiled package. 7154 // Don't use profiles since that may cause compilation to be skipped. 7155 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7156 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7157 true /* force */); 7158 7159 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7160 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7161 throw new IllegalStateException("Failed to dexopt: " + res); 7162 } 7163 } 7164 } 7165 7166 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7167 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7168 Slog.w(TAG, "Unable to update from " + oldPkg.name 7169 + " to " + newPkg.packageName 7170 + ": old package not in system partition"); 7171 return false; 7172 } else if (mPackages.get(oldPkg.name) != null) { 7173 Slog.w(TAG, "Unable to update from " + oldPkg.name 7174 + " to " + newPkg.packageName 7175 + ": old package still exists"); 7176 return false; 7177 } 7178 return true; 7179 } 7180 7181 private boolean removeDataDirsLI(String volumeUuid, String packageName) { 7182 // TODO: triage flags as part of 26466827 7183 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7184 7185 boolean res = true; 7186 final int[] users = sUserManager.getUserIds(); 7187 for (int user : users) { 7188 try { 7189 mInstaller.destroyAppData(volumeUuid, packageName, user, flags); 7190 } catch (InstallerException e) { 7191 Slog.w(TAG, "Failed to delete data directory", e); 7192 res = false; 7193 } 7194 } 7195 return res; 7196 } 7197 7198 void removeCodePathLI(File codePath) { 7199 if (codePath.isDirectory()) { 7200 try { 7201 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7202 } catch (InstallerException e) { 7203 Slog.w(TAG, "Failed to remove code path", e); 7204 } 7205 } else { 7206 codePath.delete(); 7207 } 7208 } 7209 7210 void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) { 7211 try { 7212 mInstaller.destroyAppData(volumeUuid, packageName, userId, flags); 7213 } catch (InstallerException e) { 7214 Slog.w(TAG, "Failed to destroy app data", e); 7215 } 7216 } 7217 7218 void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags, 7219 int appId, String seinfo) { 7220 try { 7221 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo); 7222 } catch (InstallerException e) { 7223 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 7224 } 7225 } 7226 7227 private void deleteProfilesLI(String packageName, boolean destroy) { 7228 final PackageParser.Package pkg; 7229 synchronized (mPackages) { 7230 pkg = mPackages.get(packageName); 7231 } 7232 if (pkg == null) { 7233 Slog.w(TAG, "Failed to delete profiles. No package: " + packageName); 7234 return; 7235 } 7236 deleteProfilesLI(pkg, destroy); 7237 } 7238 7239 private void deleteProfilesLI(PackageParser.Package pkg, boolean destroy) { 7240 try { 7241 if (destroy) { 7242 mInstaller.destroyAppProfiles(pkg.packageName); 7243 } else { 7244 mInstaller.clearAppProfiles(pkg.packageName); 7245 } 7246 } catch (InstallerException ex) { 7247 Log.e(TAG, "Could not delete profiles for package " + pkg.packageName); 7248 } 7249 } 7250 7251 private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 7252 final PackageParser.Package pkg; 7253 synchronized (mPackages) { 7254 pkg = mPackages.get(packageName); 7255 } 7256 if (pkg == null) { 7257 Slog.w(TAG, "Failed to delete code cache directory. No package: " + packageName); 7258 return; 7259 } 7260 deleteCodeCacheDirsLI(pkg); 7261 } 7262 7263 private void deleteCodeCacheDirsLI(PackageParser.Package pkg) { 7264 // TODO: triage flags as part of 26466827 7265 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7266 7267 int[] users = sUserManager.getUserIds(); 7268 int res = 0; 7269 for (int user : users) { 7270 // Remove the parent code cache 7271 try { 7272 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, user, 7273 flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7274 } catch (InstallerException e) { 7275 Slog.w(TAG, "Failed to delete code cache directory", e); 7276 } 7277 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7278 for (int i = 0; i < childCount; i++) { 7279 PackageParser.Package childPkg = pkg.childPackages.get(i); 7280 // Remove the child code cache 7281 try { 7282 mInstaller.clearAppData(childPkg.volumeUuid, childPkg.packageName, 7283 user, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7284 } catch (InstallerException e) { 7285 Slog.w(TAG, "Failed to delete code cache directory", e); 7286 } 7287 } 7288 } 7289 } 7290 7291 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7292 long lastUpdateTime) { 7293 // Set parent install/update time 7294 PackageSetting ps = (PackageSetting) pkg.mExtras; 7295 if (ps != null) { 7296 ps.firstInstallTime = firstInstallTime; 7297 ps.lastUpdateTime = lastUpdateTime; 7298 } 7299 // Set children install/update time 7300 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7301 for (int i = 0; i < childCount; i++) { 7302 PackageParser.Package childPkg = pkg.childPackages.get(i); 7303 ps = (PackageSetting) childPkg.mExtras; 7304 if (ps != null) { 7305 ps.firstInstallTime = firstInstallTime; 7306 ps.lastUpdateTime = lastUpdateTime; 7307 } 7308 } 7309 } 7310 7311 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7312 PackageParser.Package changingLib) { 7313 if (file.path != null) { 7314 usesLibraryFiles.add(file.path); 7315 return; 7316 } 7317 PackageParser.Package p = mPackages.get(file.apk); 7318 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7319 // If we are doing this while in the middle of updating a library apk, 7320 // then we need to make sure to use that new apk for determining the 7321 // dependencies here. (We haven't yet finished committing the new apk 7322 // to the package manager state.) 7323 if (p == null || p.packageName.equals(changingLib.packageName)) { 7324 p = changingLib; 7325 } 7326 } 7327 if (p != null) { 7328 usesLibraryFiles.addAll(p.getAllCodePaths()); 7329 } 7330 } 7331 7332 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7333 PackageParser.Package changingLib) throws PackageManagerException { 7334 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7335 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7336 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7337 for (int i=0; i<N; i++) { 7338 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7339 if (file == null) { 7340 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7341 "Package " + pkg.packageName + " requires unavailable shared library " 7342 + pkg.usesLibraries.get(i) + "; failing!"); 7343 } 7344 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7345 } 7346 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7347 for (int i=0; i<N; i++) { 7348 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7349 if (file == null) { 7350 Slog.w(TAG, "Package " + pkg.packageName 7351 + " desires unavailable shared library " 7352 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7353 } else { 7354 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7355 } 7356 } 7357 N = usesLibraryFiles.size(); 7358 if (N > 0) { 7359 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7360 } else { 7361 pkg.usesLibraryFiles = null; 7362 } 7363 } 7364 } 7365 7366 private static boolean hasString(List<String> list, List<String> which) { 7367 if (list == null) { 7368 return false; 7369 } 7370 for (int i=list.size()-1; i>=0; i--) { 7371 for (int j=which.size()-1; j>=0; j--) { 7372 if (which.get(j).equals(list.get(i))) { 7373 return true; 7374 } 7375 } 7376 } 7377 return false; 7378 } 7379 7380 private void updateAllSharedLibrariesLPw() { 7381 for (PackageParser.Package pkg : mPackages.values()) { 7382 try { 7383 updateSharedLibrariesLPw(pkg, null); 7384 } catch (PackageManagerException e) { 7385 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7386 } 7387 } 7388 } 7389 7390 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7391 PackageParser.Package changingPkg) { 7392 ArrayList<PackageParser.Package> res = null; 7393 for (PackageParser.Package pkg : mPackages.values()) { 7394 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7395 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7396 if (res == null) { 7397 res = new ArrayList<PackageParser.Package>(); 7398 } 7399 res.add(pkg); 7400 try { 7401 updateSharedLibrariesLPw(pkg, changingPkg); 7402 } catch (PackageManagerException e) { 7403 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7404 } 7405 } 7406 } 7407 return res; 7408 } 7409 7410 /** 7411 * Derive the value of the {@code cpuAbiOverride} based on the provided 7412 * value and an optional stored value from the package settings. 7413 */ 7414 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7415 String cpuAbiOverride = null; 7416 7417 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7418 cpuAbiOverride = null; 7419 } else if (abiOverride != null) { 7420 cpuAbiOverride = abiOverride; 7421 } else if (settings != null) { 7422 cpuAbiOverride = settings.cpuAbiOverrideString; 7423 } 7424 7425 return cpuAbiOverride; 7426 } 7427 7428 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 7429 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7430 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7431 // If the package has children and this is the first dive in the function 7432 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7433 // whether all packages (parent and children) would be successfully scanned 7434 // before the actual scan since scanning mutates internal state and we want 7435 // to atomically install the package and its children. 7436 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7437 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7438 scanFlags |= SCAN_CHECK_ONLY; 7439 } 7440 } else { 7441 scanFlags &= ~SCAN_CHECK_ONLY; 7442 } 7443 7444 final PackageParser.Package scannedPkg; 7445 try { 7446 // Scan the parent 7447 scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 7448 // Scan the children 7449 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7450 for (int i = 0; i < childCount; i++) { 7451 PackageParser.Package childPkg = pkg.childPackages.get(i); 7452 scanPackageLI(childPkg, parseFlags, 7453 scanFlags, currentTime, user); 7454 } 7455 } finally { 7456 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7457 } 7458 7459 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7460 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 7461 } 7462 7463 return scannedPkg; 7464 } 7465 7466 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 7467 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7468 boolean success = false; 7469 try { 7470 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 7471 currentTime, user); 7472 success = true; 7473 return res; 7474 } finally { 7475 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7476 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 7477 } 7478 } 7479 } 7480 7481 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 7482 int scanFlags, long currentTime, UserHandle user) 7483 throws PackageManagerException { 7484 final File scanFile = new File(pkg.codePath); 7485 if (pkg.applicationInfo.getCodePath() == null || 7486 pkg.applicationInfo.getResourcePath() == null) { 7487 // Bail out. The resource and code paths haven't been set. 7488 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7489 "Code and resource paths haven't been set correctly"); 7490 } 7491 7492 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7493 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7494 } else { 7495 // Only allow system apps to be flagged as core apps. 7496 pkg.coreApp = false; 7497 } 7498 7499 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7500 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7501 } 7502 7503 if (mCustomResolverComponentName != null && 7504 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7505 setUpCustomResolverActivity(pkg); 7506 } 7507 7508 if (pkg.packageName.equals("android")) { 7509 synchronized (mPackages) { 7510 if (mAndroidApplication != null) { 7511 Slog.w(TAG, "*************************************************"); 7512 Slog.w(TAG, "Core android package being redefined. Skipping."); 7513 Slog.w(TAG, " file=" + scanFile); 7514 Slog.w(TAG, "*************************************************"); 7515 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7516 "Core android package being redefined. Skipping."); 7517 } 7518 7519 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7520 // Set up information for our fall-back user intent resolution activity. 7521 mPlatformPackage = pkg; 7522 pkg.mVersionCode = mSdkVersion; 7523 mAndroidApplication = pkg.applicationInfo; 7524 7525 if (!mResolverReplaced) { 7526 mResolveActivity.applicationInfo = mAndroidApplication; 7527 mResolveActivity.name = ResolverActivity.class.getName(); 7528 mResolveActivity.packageName = mAndroidApplication.packageName; 7529 mResolveActivity.processName = "system:ui"; 7530 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7531 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7532 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7533 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7534 mResolveActivity.exported = true; 7535 mResolveActivity.enabled = true; 7536 mResolveInfo.activityInfo = mResolveActivity; 7537 mResolveInfo.priority = 0; 7538 mResolveInfo.preferredOrder = 0; 7539 mResolveInfo.match = 0; 7540 mResolveComponentName = new ComponentName( 7541 mAndroidApplication.packageName, mResolveActivity.name); 7542 } 7543 } 7544 } 7545 } 7546 7547 if (DEBUG_PACKAGE_SCANNING) { 7548 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7549 Log.d(TAG, "Scanning package " + pkg.packageName); 7550 } 7551 7552 synchronized (mPackages) { 7553 if (mPackages.containsKey(pkg.packageName) 7554 || mSharedLibraries.containsKey(pkg.packageName)) { 7555 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7556 "Application package " + pkg.packageName 7557 + " already installed. Skipping duplicate."); 7558 } 7559 7560 // If we're only installing presumed-existing packages, require that the 7561 // scanned APK is both already known and at the path previously established 7562 // for it. Previously unknown packages we pick up normally, but if we have an 7563 // a priori expectation about this package's install presence, enforce it. 7564 // With a singular exception for new system packages. When an OTA contains 7565 // a new system package, we allow the codepath to change from a system location 7566 // to the user-installed location. If we don't allow this change, any newer, 7567 // user-installed version of the application will be ignored. 7568 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7569 if (mExpectingBetter.containsKey(pkg.packageName)) { 7570 logCriticalInfo(Log.WARN, 7571 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7572 } else { 7573 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7574 if (known != null) { 7575 if (DEBUG_PACKAGE_SCANNING) { 7576 Log.d(TAG, "Examining " + pkg.codePath 7577 + " and requiring known paths " + known.codePathString 7578 + " & " + known.resourcePathString); 7579 } 7580 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7581 || !pkg.applicationInfo.getResourcePath().equals( 7582 known.resourcePathString)) { 7583 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7584 "Application package " + pkg.packageName 7585 + " found at " + pkg.applicationInfo.getCodePath() 7586 + " but expected at " + known.codePathString 7587 + "; ignoring."); 7588 } 7589 } 7590 } 7591 } 7592 } 7593 7594 // Initialize package source and resource directories 7595 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7596 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7597 7598 SharedUserSetting suid = null; 7599 PackageSetting pkgSetting = null; 7600 7601 if (!isSystemApp(pkg)) { 7602 // Only system apps can use these features. 7603 pkg.mOriginalPackages = null; 7604 pkg.mRealPackage = null; 7605 pkg.mAdoptPermissions = null; 7606 } 7607 7608 // Getting the package setting may have a side-effect, so if we 7609 // are only checking if scan would succeed, stash a copy of the 7610 // old setting to restore at the end. 7611 PackageSetting nonMutatedPs = null; 7612 7613 // writer 7614 synchronized (mPackages) { 7615 if (pkg.mSharedUserId != null) { 7616 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7617 if (suid == null) { 7618 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7619 "Creating application package " + pkg.packageName 7620 + " for shared user failed"); 7621 } 7622 if (DEBUG_PACKAGE_SCANNING) { 7623 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7624 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7625 + "): packages=" + suid.packages); 7626 } 7627 } 7628 7629 // Check if we are renaming from an original package name. 7630 PackageSetting origPackage = null; 7631 String realName = null; 7632 if (pkg.mOriginalPackages != null) { 7633 // This package may need to be renamed to a previously 7634 // installed name. Let's check on that... 7635 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7636 if (pkg.mOriginalPackages.contains(renamed)) { 7637 // This package had originally been installed as the 7638 // original name, and we have already taken care of 7639 // transitioning to the new one. Just update the new 7640 // one to continue using the old name. 7641 realName = pkg.mRealPackage; 7642 if (!pkg.packageName.equals(renamed)) { 7643 // Callers into this function may have already taken 7644 // care of renaming the package; only do it here if 7645 // it is not already done. 7646 pkg.setPackageName(renamed); 7647 } 7648 7649 } else { 7650 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7651 if ((origPackage = mSettings.peekPackageLPr( 7652 pkg.mOriginalPackages.get(i))) != null) { 7653 // We do have the package already installed under its 7654 // original name... should we use it? 7655 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7656 // New package is not compatible with original. 7657 origPackage = null; 7658 continue; 7659 } else if (origPackage.sharedUser != null) { 7660 // Make sure uid is compatible between packages. 7661 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7662 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7663 + " to " + pkg.packageName + ": old uid " 7664 + origPackage.sharedUser.name 7665 + " differs from " + pkg.mSharedUserId); 7666 origPackage = null; 7667 continue; 7668 } 7669 } else { 7670 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7671 + pkg.packageName + " to old name " + origPackage.name); 7672 } 7673 break; 7674 } 7675 } 7676 } 7677 } 7678 7679 if (mTransferedPackages.contains(pkg.packageName)) { 7680 Slog.w(TAG, "Package " + pkg.packageName 7681 + " was transferred to another, but its .apk remains"); 7682 } 7683 7684 // See comments in nonMutatedPs declaration 7685 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7686 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 7687 if (foundPs != null) { 7688 nonMutatedPs = new PackageSetting(foundPs); 7689 } 7690 } 7691 7692 // Just create the setting, don't add it yet. For already existing packages 7693 // the PkgSetting exists already and doesn't have to be created. 7694 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7695 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7696 pkg.applicationInfo.primaryCpuAbi, 7697 pkg.applicationInfo.secondaryCpuAbi, 7698 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7699 user, false); 7700 if (pkgSetting == null) { 7701 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7702 "Creating application package " + pkg.packageName + " failed"); 7703 } 7704 7705 if (pkgSetting.origPackage != null) { 7706 // If we are first transitioning from an original package, 7707 // fix up the new package's name now. We need to do this after 7708 // looking up the package under its new name, so getPackageLP 7709 // can take care of fiddling things correctly. 7710 pkg.setPackageName(origPackage.name); 7711 7712 // File a report about this. 7713 String msg = "New package " + pkgSetting.realName 7714 + " renamed to replace old package " + pkgSetting.name; 7715 reportSettingsProblem(Log.WARN, msg); 7716 7717 // Make a note of it. 7718 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7719 mTransferedPackages.add(origPackage.name); 7720 } 7721 7722 // No longer need to retain this. 7723 pkgSetting.origPackage = null; 7724 } 7725 7726 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 7727 // Make a note of it. 7728 mTransferedPackages.add(pkg.packageName); 7729 } 7730 7731 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7732 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7733 } 7734 7735 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7736 // Check all shared libraries and map to their actual file path. 7737 // We only do this here for apps not on a system dir, because those 7738 // are the only ones that can fail an install due to this. We 7739 // will take care of the system apps by updating all of their 7740 // library paths after the scan is done. 7741 updateSharedLibrariesLPw(pkg, null); 7742 } 7743 7744 if (mFoundPolicyFile) { 7745 SELinuxMMAC.assignSeinfoValue(pkg); 7746 } 7747 7748 pkg.applicationInfo.uid = pkgSetting.appId; 7749 pkg.mExtras = pkgSetting; 7750 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7751 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7752 // We just determined the app is signed correctly, so bring 7753 // over the latest parsed certs. 7754 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7755 } else { 7756 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7757 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7758 "Package " + pkg.packageName + " upgrade keys do not match the " 7759 + "previously installed version"); 7760 } else { 7761 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7762 String msg = "System package " + pkg.packageName 7763 + " signature changed; retaining data."; 7764 reportSettingsProblem(Log.WARN, msg); 7765 } 7766 } 7767 } else { 7768 try { 7769 verifySignaturesLP(pkgSetting, pkg); 7770 // We just determined the app is signed correctly, so bring 7771 // over the latest parsed certs. 7772 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7773 } catch (PackageManagerException e) { 7774 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7775 throw e; 7776 } 7777 // The signature has changed, but this package is in the system 7778 // image... let's recover! 7779 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7780 // However... if this package is part of a shared user, but it 7781 // doesn't match the signature of the shared user, let's fail. 7782 // What this means is that you can't change the signatures 7783 // associated with an overall shared user, which doesn't seem all 7784 // that unreasonable. 7785 if (pkgSetting.sharedUser != null) { 7786 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7787 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7788 throw new PackageManagerException( 7789 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7790 "Signature mismatch for shared user: " 7791 + pkgSetting.sharedUser); 7792 } 7793 } 7794 // File a report about this. 7795 String msg = "System package " + pkg.packageName 7796 + " signature changed; retaining data."; 7797 reportSettingsProblem(Log.WARN, msg); 7798 } 7799 } 7800 // Verify that this new package doesn't have any content providers 7801 // that conflict with existing packages. Only do this if the 7802 // package isn't already installed, since we don't want to break 7803 // things that are installed. 7804 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7805 final int N = pkg.providers.size(); 7806 int i; 7807 for (i=0; i<N; i++) { 7808 PackageParser.Provider p = pkg.providers.get(i); 7809 if (p.info.authority != null) { 7810 String names[] = p.info.authority.split(";"); 7811 for (int j = 0; j < names.length; j++) { 7812 if (mProvidersByAuthority.containsKey(names[j])) { 7813 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7814 final String otherPackageName = 7815 ((other != null && other.getComponentName() != null) ? 7816 other.getComponentName().getPackageName() : "?"); 7817 throw new PackageManagerException( 7818 INSTALL_FAILED_CONFLICTING_PROVIDER, 7819 "Can't install because provider name " + names[j] 7820 + " (in package " + pkg.applicationInfo.packageName 7821 + ") is already used by " + otherPackageName); 7822 } 7823 } 7824 } 7825 } 7826 } 7827 7828 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 7829 // This package wants to adopt ownership of permissions from 7830 // another package. 7831 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7832 final String origName = pkg.mAdoptPermissions.get(i); 7833 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7834 if (orig != null) { 7835 if (verifyPackageUpdateLPr(orig, pkg)) { 7836 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7837 + pkg.packageName); 7838 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7839 } 7840 } 7841 } 7842 } 7843 } 7844 7845 final String pkgName = pkg.packageName; 7846 7847 final long scanFileTime = scanFile.lastModified(); 7848 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7849 pkg.applicationInfo.processName = fixProcessName( 7850 pkg.applicationInfo.packageName, 7851 pkg.applicationInfo.processName, 7852 pkg.applicationInfo.uid); 7853 7854 if (pkg != mPlatformPackage) { 7855 // Get all of our default paths setup 7856 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7857 } 7858 7859 final String path = scanFile.getPath(); 7860 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7861 7862 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7863 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7864 7865 // Some system apps still use directory structure for native libraries 7866 // in which case we might end up not detecting abi solely based on apk 7867 // structure. Try to detect abi based on directory structure. 7868 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7869 pkg.applicationInfo.primaryCpuAbi == null) { 7870 setBundledAppAbisAndRoots(pkg, pkgSetting); 7871 setNativeLibraryPaths(pkg); 7872 } 7873 7874 } else { 7875 if ((scanFlags & SCAN_MOVE) != 0) { 7876 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7877 // but we already have this packages package info in the PackageSetting. We just 7878 // use that and derive the native library path based on the new codepath. 7879 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7880 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7881 } 7882 7883 // Set native library paths again. For moves, the path will be updated based on the 7884 // ABIs we've determined above. For non-moves, the path will be updated based on the 7885 // ABIs we determined during compilation, but the path will depend on the final 7886 // package path (after the rename away from the stage path). 7887 setNativeLibraryPaths(pkg); 7888 } 7889 7890 // This is a special case for the "system" package, where the ABI is 7891 // dictated by the zygote configuration (and init.rc). We should keep track 7892 // of this ABI so that we can deal with "normal" applications that run under 7893 // the same UID correctly. 7894 if (mPlatformPackage == pkg) { 7895 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7896 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7897 } 7898 7899 // If there's a mismatch between the abi-override in the package setting 7900 // and the abiOverride specified for the install. Warn about this because we 7901 // would've already compiled the app without taking the package setting into 7902 // account. 7903 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7904 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7905 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7906 " for package " + pkg.packageName); 7907 } 7908 } 7909 7910 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7911 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7912 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7913 7914 // Copy the derived override back to the parsed package, so that we can 7915 // update the package settings accordingly. 7916 pkg.cpuAbiOverride = cpuAbiOverride; 7917 7918 if (DEBUG_ABI_SELECTION) { 7919 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7920 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7921 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7922 } 7923 7924 // Push the derived path down into PackageSettings so we know what to 7925 // clean up at uninstall time. 7926 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7927 7928 if (DEBUG_ABI_SELECTION) { 7929 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7930 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7931 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7932 } 7933 7934 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7935 // We don't do this here during boot because we can do it all 7936 // at once after scanning all existing packages. 7937 // 7938 // We also do this *before* we perform dexopt on this package, so that 7939 // we can avoid redundant dexopts, and also to make sure we've got the 7940 // code and package path correct. 7941 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7942 pkg, true /* boot complete */); 7943 } 7944 7945 if (mFactoryTest && pkg.requestedPermissions.contains( 7946 android.Manifest.permission.FACTORY_TEST)) { 7947 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7948 } 7949 7950 ArrayList<PackageParser.Package> clientLibPkgs = null; 7951 7952 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7953 if (nonMutatedPs != null) { 7954 synchronized (mPackages) { 7955 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 7956 } 7957 } 7958 return pkg; 7959 } 7960 7961 // Only privileged apps and updated privileged apps can add child packages. 7962 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 7963 if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) { 7964 throw new PackageManagerException("Only privileged apps and updated " 7965 + "privileged apps can add child packages. Ignoring package " 7966 + pkg.packageName); 7967 } 7968 final int childCount = pkg.childPackages.size(); 7969 for (int i = 0; i < childCount; i++) { 7970 PackageParser.Package childPkg = pkg.childPackages.get(i); 7971 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 7972 childPkg.packageName)) { 7973 throw new PackageManagerException("Cannot override a child package of " 7974 + "another disabled system app. Ignoring package " + pkg.packageName); 7975 } 7976 } 7977 } 7978 7979 // writer 7980 synchronized (mPackages) { 7981 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7982 // Only system apps can add new shared libraries. 7983 if (pkg.libraryNames != null) { 7984 for (int i=0; i<pkg.libraryNames.size(); i++) { 7985 String name = pkg.libraryNames.get(i); 7986 boolean allowed = false; 7987 if (pkg.isUpdatedSystemApp()) { 7988 // New library entries can only be added through the 7989 // system image. This is important to get rid of a lot 7990 // of nasty edge cases: for example if we allowed a non- 7991 // system update of the app to add a library, then uninstalling 7992 // the update would make the library go away, and assumptions 7993 // we made such as through app install filtering would now 7994 // have allowed apps on the device which aren't compatible 7995 // with it. Better to just have the restriction here, be 7996 // conservative, and create many fewer cases that can negatively 7997 // impact the user experience. 7998 final PackageSetting sysPs = mSettings 7999 .getDisabledSystemPkgLPr(pkg.packageName); 8000 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8001 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8002 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8003 allowed = true; 8004 break; 8005 } 8006 } 8007 } 8008 } else { 8009 allowed = true; 8010 } 8011 if (allowed) { 8012 if (!mSharedLibraries.containsKey(name)) { 8013 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8014 } else if (!name.equals(pkg.packageName)) { 8015 Slog.w(TAG, "Package " + pkg.packageName + " library " 8016 + name + " already exists; skipping"); 8017 } 8018 } else { 8019 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8020 + name + " that is not declared on system image; skipping"); 8021 } 8022 } 8023 if ((scanFlags & SCAN_BOOTING) == 0) { 8024 // If we are not booting, we need to update any applications 8025 // that are clients of our shared library. If we are booting, 8026 // this will all be done once the scan is complete. 8027 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8028 } 8029 } 8030 } 8031 } 8032 8033 // Request the ActivityManager to kill the process(only for existing packages) 8034 // so that we do not end up in a confused state while the user is still using the older 8035 // version of the application while the new one gets installed. 8036 final boolean isReplacing = (scanFlags & SCAN_REPLACING) != 0; 8037 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 8038 if (killApp) { 8039 if (isReplacing) { 8040 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 8041 8042 killApplication(pkg.applicationInfo.packageName, 8043 pkg.applicationInfo.uid, "replace pkg"); 8044 8045 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8046 } 8047 } 8048 8049 // Also need to kill any apps that are dependent on the library. 8050 if (clientLibPkgs != null) { 8051 for (int i=0; i<clientLibPkgs.size(); i++) { 8052 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8053 killApplication(clientPkg.applicationInfo.packageName, 8054 clientPkg.applicationInfo.uid, "update lib"); 8055 } 8056 } 8057 8058 // Make sure we're not adding any bogus keyset info 8059 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8060 ksms.assertScannedPackageValid(pkg); 8061 8062 // writer 8063 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8064 8065 boolean createIdmapFailed = false; 8066 synchronized (mPackages) { 8067 // We don't expect installation to fail beyond this point 8068 8069 // Add the new setting to mSettings 8070 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8071 // Add the new setting to mPackages 8072 mPackages.put(pkg.applicationInfo.packageName, pkg); 8073 // Make sure we don't accidentally delete its data. 8074 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8075 while (iter.hasNext()) { 8076 PackageCleanItem item = iter.next(); 8077 if (pkgName.equals(item.packageName)) { 8078 iter.remove(); 8079 } 8080 } 8081 8082 // Take care of first install / last update times. 8083 if (currentTime != 0) { 8084 if (pkgSetting.firstInstallTime == 0) { 8085 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8086 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8087 pkgSetting.lastUpdateTime = currentTime; 8088 } 8089 } else if (pkgSetting.firstInstallTime == 0) { 8090 // We need *something*. Take time time stamp of the file. 8091 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8092 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8093 if (scanFileTime != pkgSetting.timeStamp) { 8094 // A package on the system image has changed; consider this 8095 // to be an update. 8096 pkgSetting.lastUpdateTime = scanFileTime; 8097 } 8098 } 8099 8100 // Add the package's KeySets to the global KeySetManagerService 8101 ksms.addScannedPackageLPw(pkg); 8102 8103 int N = pkg.providers.size(); 8104 StringBuilder r = null; 8105 int i; 8106 for (i=0; i<N; i++) { 8107 PackageParser.Provider p = pkg.providers.get(i); 8108 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8109 p.info.processName, pkg.applicationInfo.uid); 8110 mProviders.addProvider(p); 8111 p.syncable = p.info.isSyncable; 8112 if (p.info.authority != null) { 8113 String names[] = p.info.authority.split(";"); 8114 p.info.authority = null; 8115 for (int j = 0; j < names.length; j++) { 8116 if (j == 1 && p.syncable) { 8117 // We only want the first authority for a provider to possibly be 8118 // syncable, so if we already added this provider using a different 8119 // authority clear the syncable flag. We copy the provider before 8120 // changing it because the mProviders object contains a reference 8121 // to a provider that we don't want to change. 8122 // Only do this for the second authority since the resulting provider 8123 // object can be the same for all future authorities for this provider. 8124 p = new PackageParser.Provider(p); 8125 p.syncable = false; 8126 } 8127 if (!mProvidersByAuthority.containsKey(names[j])) { 8128 mProvidersByAuthority.put(names[j], p); 8129 if (p.info.authority == null) { 8130 p.info.authority = names[j]; 8131 } else { 8132 p.info.authority = p.info.authority + ";" + names[j]; 8133 } 8134 if (DEBUG_PACKAGE_SCANNING) { 8135 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 8136 Log.d(TAG, "Registered content provider: " + names[j] 8137 + ", className = " + p.info.name + ", isSyncable = " 8138 + p.info.isSyncable); 8139 } 8140 } else { 8141 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8142 Slog.w(TAG, "Skipping provider name " + names[j] + 8143 " (in package " + pkg.applicationInfo.packageName + 8144 "): name already used by " 8145 + ((other != null && other.getComponentName() != null) 8146 ? other.getComponentName().getPackageName() : "?")); 8147 } 8148 } 8149 } 8150 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8151 if (r == null) { 8152 r = new StringBuilder(256); 8153 } else { 8154 r.append(' '); 8155 } 8156 r.append(p.info.name); 8157 } 8158 } 8159 if (r != null) { 8160 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8161 } 8162 8163 N = pkg.services.size(); 8164 r = null; 8165 for (i=0; i<N; i++) { 8166 PackageParser.Service s = pkg.services.get(i); 8167 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8168 s.info.processName, pkg.applicationInfo.uid); 8169 mServices.addService(s); 8170 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8171 if (r == null) { 8172 r = new StringBuilder(256); 8173 } else { 8174 r.append(' '); 8175 } 8176 r.append(s.info.name); 8177 } 8178 } 8179 if (r != null) { 8180 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8181 } 8182 8183 N = pkg.receivers.size(); 8184 r = null; 8185 for (i=0; i<N; i++) { 8186 PackageParser.Activity a = pkg.receivers.get(i); 8187 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8188 a.info.processName, pkg.applicationInfo.uid); 8189 mReceivers.addActivity(a, "receiver"); 8190 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8191 if (r == null) { 8192 r = new StringBuilder(256); 8193 } else { 8194 r.append(' '); 8195 } 8196 r.append(a.info.name); 8197 } 8198 } 8199 if (r != null) { 8200 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8201 } 8202 8203 N = pkg.activities.size(); 8204 r = null; 8205 for (i=0; i<N; i++) { 8206 PackageParser.Activity a = pkg.activities.get(i); 8207 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8208 a.info.processName, pkg.applicationInfo.uid); 8209 mActivities.addActivity(a, "activity"); 8210 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8211 if (r == null) { 8212 r = new StringBuilder(256); 8213 } else { 8214 r.append(' '); 8215 } 8216 r.append(a.info.name); 8217 } 8218 } 8219 if (r != null) { 8220 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8221 } 8222 8223 N = pkg.permissionGroups.size(); 8224 r = null; 8225 for (i=0; i<N; i++) { 8226 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8227 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8228 if (cur == null) { 8229 mPermissionGroups.put(pg.info.name, pg); 8230 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8231 if (r == null) { 8232 r = new StringBuilder(256); 8233 } else { 8234 r.append(' '); 8235 } 8236 r.append(pg.info.name); 8237 } 8238 } else { 8239 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8240 + pg.info.packageName + " ignored: original from " 8241 + cur.info.packageName); 8242 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8243 if (r == null) { 8244 r = new StringBuilder(256); 8245 } else { 8246 r.append(' '); 8247 } 8248 r.append("DUP:"); 8249 r.append(pg.info.name); 8250 } 8251 } 8252 } 8253 if (r != null) { 8254 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8255 } 8256 8257 N = pkg.permissions.size(); 8258 r = null; 8259 for (i=0; i<N; i++) { 8260 PackageParser.Permission p = pkg.permissions.get(i); 8261 8262 // Assume by default that we did not install this permission into the system. 8263 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8264 8265 // Now that permission groups have a special meaning, we ignore permission 8266 // groups for legacy apps to prevent unexpected behavior. In particular, 8267 // permissions for one app being granted to someone just becase they happen 8268 // to be in a group defined by another app (before this had no implications). 8269 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8270 p.group = mPermissionGroups.get(p.info.group); 8271 // Warn for a permission in an unknown group. 8272 if (p.info.group != null && p.group == null) { 8273 Slog.w(TAG, "Permission " + p.info.name + " from package " 8274 + p.info.packageName + " in an unknown group " + p.info.group); 8275 } 8276 } 8277 8278 ArrayMap<String, BasePermission> permissionMap = 8279 p.tree ? mSettings.mPermissionTrees 8280 : mSettings.mPermissions; 8281 BasePermission bp = permissionMap.get(p.info.name); 8282 8283 // Allow system apps to redefine non-system permissions 8284 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8285 final boolean currentOwnerIsSystem = (bp.perm != null 8286 && isSystemApp(bp.perm.owner)); 8287 if (isSystemApp(p.owner)) { 8288 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8289 // It's a built-in permission and no owner, take ownership now 8290 bp.packageSetting = pkgSetting; 8291 bp.perm = p; 8292 bp.uid = pkg.applicationInfo.uid; 8293 bp.sourcePackage = p.info.packageName; 8294 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8295 } else if (!currentOwnerIsSystem) { 8296 String msg = "New decl " + p.owner + " of permission " 8297 + p.info.name + " is system; overriding " + bp.sourcePackage; 8298 reportSettingsProblem(Log.WARN, msg); 8299 bp = null; 8300 } 8301 } 8302 } 8303 8304 if (bp == null) { 8305 bp = new BasePermission(p.info.name, p.info.packageName, 8306 BasePermission.TYPE_NORMAL); 8307 permissionMap.put(p.info.name, bp); 8308 } 8309 8310 if (bp.perm == null) { 8311 if (bp.sourcePackage == null 8312 || bp.sourcePackage.equals(p.info.packageName)) { 8313 BasePermission tree = findPermissionTreeLP(p.info.name); 8314 if (tree == null 8315 || tree.sourcePackage.equals(p.info.packageName)) { 8316 bp.packageSetting = pkgSetting; 8317 bp.perm = p; 8318 bp.uid = pkg.applicationInfo.uid; 8319 bp.sourcePackage = p.info.packageName; 8320 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8321 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8322 if (r == null) { 8323 r = new StringBuilder(256); 8324 } else { 8325 r.append(' '); 8326 } 8327 r.append(p.info.name); 8328 } 8329 } else { 8330 Slog.w(TAG, "Permission " + p.info.name + " from package " 8331 + p.info.packageName + " ignored: base tree " 8332 + tree.name + " is from package " 8333 + tree.sourcePackage); 8334 } 8335 } else { 8336 Slog.w(TAG, "Permission " + p.info.name + " from package " 8337 + p.info.packageName + " ignored: original from " 8338 + bp.sourcePackage); 8339 } 8340 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8341 if (r == null) { 8342 r = new StringBuilder(256); 8343 } else { 8344 r.append(' '); 8345 } 8346 r.append("DUP:"); 8347 r.append(p.info.name); 8348 } 8349 if (bp.perm == p) { 8350 bp.protectionLevel = p.info.protectionLevel; 8351 } 8352 } 8353 8354 if (r != null) { 8355 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8356 } 8357 8358 N = pkg.instrumentation.size(); 8359 r = null; 8360 for (i=0; i<N; i++) { 8361 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8362 a.info.packageName = pkg.applicationInfo.packageName; 8363 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8364 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8365 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8366 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8367 a.info.dataDir = pkg.applicationInfo.dataDir; 8368 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8369 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8370 8371 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8372 // need other information about the application, like the ABI and what not ? 8373 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8374 mInstrumentation.put(a.getComponentName(), a); 8375 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8376 if (r == null) { 8377 r = new StringBuilder(256); 8378 } else { 8379 r.append(' '); 8380 } 8381 r.append(a.info.name); 8382 } 8383 } 8384 if (r != null) { 8385 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8386 } 8387 8388 if (pkg.protectedBroadcasts != null) { 8389 N = pkg.protectedBroadcasts.size(); 8390 for (i=0; i<N; i++) { 8391 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8392 } 8393 } 8394 8395 pkgSetting.setTimeStamp(scanFileTime); 8396 8397 // Create idmap files for pairs of (packages, overlay packages). 8398 // Note: "android", ie framework-res.apk, is handled by native layers. 8399 if (pkg.mOverlayTarget != null) { 8400 // This is an overlay package. 8401 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8402 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8403 mOverlays.put(pkg.mOverlayTarget, 8404 new ArrayMap<String, PackageParser.Package>()); 8405 } 8406 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8407 map.put(pkg.packageName, pkg); 8408 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8409 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8410 createIdmapFailed = true; 8411 } 8412 } 8413 } else if (mOverlays.containsKey(pkg.packageName) && 8414 !pkg.packageName.equals("android")) { 8415 // This is a regular package, with one or more known overlay packages. 8416 createIdmapsForPackageLI(pkg); 8417 } 8418 } 8419 8420 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8421 8422 if (createIdmapFailed) { 8423 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8424 "scanPackageLI failed to createIdmap"); 8425 } 8426 return pkg; 8427 } 8428 8429 /** 8430 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8431 * is derived purely on the basis of the contents of {@code scanFile} and 8432 * {@code cpuAbiOverride}. 8433 * 8434 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8435 */ 8436 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8437 String cpuAbiOverride, boolean extractLibs) 8438 throws PackageManagerException { 8439 // TODO: We can probably be smarter about this stuff. For installed apps, 8440 // we can calculate this information at install time once and for all. For 8441 // system apps, we can probably assume that this information doesn't change 8442 // after the first boot scan. As things stand, we do lots of unnecessary work. 8443 8444 // Give ourselves some initial paths; we'll come back for another 8445 // pass once we've determined ABI below. 8446 setNativeLibraryPaths(pkg); 8447 8448 // We would never need to extract libs for forward-locked and external packages, 8449 // since the container service will do it for us. We shouldn't attempt to 8450 // extract libs from system app when it was not updated. 8451 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8452 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8453 extractLibs = false; 8454 } 8455 8456 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8457 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8458 8459 NativeLibraryHelper.Handle handle = null; 8460 try { 8461 handle = NativeLibraryHelper.Handle.create(pkg); 8462 // TODO(multiArch): This can be null for apps that didn't go through the 8463 // usual installation process. We can calculate it again, like we 8464 // do during install time. 8465 // 8466 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8467 // unnecessary. 8468 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8469 8470 // Null out the abis so that they can be recalculated. 8471 pkg.applicationInfo.primaryCpuAbi = null; 8472 pkg.applicationInfo.secondaryCpuAbi = null; 8473 if (isMultiArch(pkg.applicationInfo)) { 8474 // Warn if we've set an abiOverride for multi-lib packages.. 8475 // By definition, we need to copy both 32 and 64 bit libraries for 8476 // such packages. 8477 if (pkg.cpuAbiOverride != null 8478 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8479 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8480 } 8481 8482 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8483 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8484 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8485 if (extractLibs) { 8486 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8487 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8488 useIsaSpecificSubdirs); 8489 } else { 8490 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8491 } 8492 } 8493 8494 maybeThrowExceptionForMultiArchCopy( 8495 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8496 8497 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8498 if (extractLibs) { 8499 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8500 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8501 useIsaSpecificSubdirs); 8502 } else { 8503 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8504 } 8505 } 8506 8507 maybeThrowExceptionForMultiArchCopy( 8508 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8509 8510 if (abi64 >= 0) { 8511 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8512 } 8513 8514 if (abi32 >= 0) { 8515 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8516 if (abi64 >= 0) { 8517 if (cpuAbiOverride == null && pkg.use32bitAbi) { 8518 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8519 pkg.applicationInfo.primaryCpuAbi = abi; 8520 } else { 8521 pkg.applicationInfo.secondaryCpuAbi = abi; 8522 } 8523 } else { 8524 pkg.applicationInfo.primaryCpuAbi = abi; 8525 } 8526 } 8527 8528 } else { 8529 String[] abiList = (cpuAbiOverride != null) ? 8530 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8531 8532 // Enable gross and lame hacks for apps that are built with old 8533 // SDK tools. We must scan their APKs for renderscript bitcode and 8534 // not launch them if it's present. Don't bother checking on devices 8535 // that don't have 64 bit support. 8536 boolean needsRenderScriptOverride = false; 8537 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8538 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8539 abiList = Build.SUPPORTED_32_BIT_ABIS; 8540 needsRenderScriptOverride = true; 8541 } 8542 8543 final int copyRet; 8544 if (extractLibs) { 8545 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8546 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8547 } else { 8548 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8549 } 8550 8551 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8552 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8553 "Error unpackaging native libs for app, errorCode=" + copyRet); 8554 } 8555 8556 if (copyRet >= 0) { 8557 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8558 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8559 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8560 } else if (needsRenderScriptOverride) { 8561 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8562 } 8563 } 8564 } catch (IOException ioe) { 8565 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8566 } finally { 8567 IoUtils.closeQuietly(handle); 8568 } 8569 8570 // Now that we've calculated the ABIs and determined if it's an internal app, 8571 // we will go ahead and populate the nativeLibraryPath. 8572 setNativeLibraryPaths(pkg); 8573 } 8574 8575 /** 8576 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8577 * i.e, so that all packages can be run inside a single process if required. 8578 * 8579 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8580 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8581 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8582 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8583 * updating a package that belongs to a shared user. 8584 * 8585 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8586 * adds unnecessary complexity. 8587 */ 8588 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8589 PackageParser.Package scannedPackage, boolean bootComplete) { 8590 String requiredInstructionSet = null; 8591 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8592 requiredInstructionSet = VMRuntime.getInstructionSet( 8593 scannedPackage.applicationInfo.primaryCpuAbi); 8594 } 8595 8596 PackageSetting requirer = null; 8597 for (PackageSetting ps : packagesForUser) { 8598 // If packagesForUser contains scannedPackage, we skip it. This will happen 8599 // when scannedPackage is an update of an existing package. Without this check, 8600 // we will never be able to change the ABI of any package belonging to a shared 8601 // user, even if it's compatible with other packages. 8602 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8603 if (ps.primaryCpuAbiString == null) { 8604 continue; 8605 } 8606 8607 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8608 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8609 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8610 // this but there's not much we can do. 8611 String errorMessage = "Instruction set mismatch, " 8612 + ((requirer == null) ? "[caller]" : requirer) 8613 + " requires " + requiredInstructionSet + " whereas " + ps 8614 + " requires " + instructionSet; 8615 Slog.w(TAG, errorMessage); 8616 } 8617 8618 if (requiredInstructionSet == null) { 8619 requiredInstructionSet = instructionSet; 8620 requirer = ps; 8621 } 8622 } 8623 } 8624 8625 if (requiredInstructionSet != null) { 8626 String adjustedAbi; 8627 if (requirer != null) { 8628 // requirer != null implies that either scannedPackage was null or that scannedPackage 8629 // did not require an ABI, in which case we have to adjust scannedPackage to match 8630 // the ABI of the set (which is the same as requirer's ABI) 8631 adjustedAbi = requirer.primaryCpuAbiString; 8632 if (scannedPackage != null) { 8633 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8634 } 8635 } else { 8636 // requirer == null implies that we're updating all ABIs in the set to 8637 // match scannedPackage. 8638 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8639 } 8640 8641 for (PackageSetting ps : packagesForUser) { 8642 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8643 if (ps.primaryCpuAbiString != null) { 8644 continue; 8645 } 8646 8647 ps.primaryCpuAbiString = adjustedAbi; 8648 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8649 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8650 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8651 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8652 + " (requirer=" 8653 + (requirer == null ? "null" : requirer.pkg.packageName) 8654 + ", scannedPackage=" 8655 + (scannedPackage != null ? scannedPackage.packageName : "null") 8656 + ")"); 8657 try { 8658 mInstaller.rmdex(ps.codePathString, 8659 getDexCodeInstructionSet(getPreferredInstructionSet())); 8660 } catch (InstallerException ignored) { 8661 } 8662 } 8663 } 8664 } 8665 } 8666 } 8667 8668 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8669 synchronized (mPackages) { 8670 mResolverReplaced = true; 8671 // Set up information for custom user intent resolution activity. 8672 mResolveActivity.applicationInfo = pkg.applicationInfo; 8673 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8674 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8675 mResolveActivity.processName = pkg.applicationInfo.packageName; 8676 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8677 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8678 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8679 mResolveActivity.theme = 0; 8680 mResolveActivity.exported = true; 8681 mResolveActivity.enabled = true; 8682 mResolveInfo.activityInfo = mResolveActivity; 8683 mResolveInfo.priority = 0; 8684 mResolveInfo.preferredOrder = 0; 8685 mResolveInfo.match = 0; 8686 mResolveComponentName = mCustomResolverComponentName; 8687 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8688 mResolveComponentName); 8689 } 8690 } 8691 8692 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8693 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8694 8695 // Set up information for ephemeral installer activity 8696 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8697 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8698 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8699 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8700 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8701 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8702 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8703 mEphemeralInstallerActivity.theme = 0; 8704 mEphemeralInstallerActivity.exported = true; 8705 mEphemeralInstallerActivity.enabled = true; 8706 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8707 mEphemeralInstallerInfo.priority = 0; 8708 mEphemeralInstallerInfo.preferredOrder = 0; 8709 mEphemeralInstallerInfo.match = 0; 8710 8711 if (DEBUG_EPHEMERAL) { 8712 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8713 } 8714 } 8715 8716 private static String calculateBundledApkRoot(final String codePathString) { 8717 final File codePath = new File(codePathString); 8718 final File codeRoot; 8719 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8720 codeRoot = Environment.getRootDirectory(); 8721 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8722 codeRoot = Environment.getOemDirectory(); 8723 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8724 codeRoot = Environment.getVendorDirectory(); 8725 } else { 8726 // Unrecognized code path; take its top real segment as the apk root: 8727 // e.g. /something/app/blah.apk => /something 8728 try { 8729 File f = codePath.getCanonicalFile(); 8730 File parent = f.getParentFile(); // non-null because codePath is a file 8731 File tmp; 8732 while ((tmp = parent.getParentFile()) != null) { 8733 f = parent; 8734 parent = tmp; 8735 } 8736 codeRoot = f; 8737 Slog.w(TAG, "Unrecognized code path " 8738 + codePath + " - using " + codeRoot); 8739 } catch (IOException e) { 8740 // Can't canonicalize the code path -- shenanigans? 8741 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8742 return Environment.getRootDirectory().getPath(); 8743 } 8744 } 8745 return codeRoot.getPath(); 8746 } 8747 8748 /** 8749 * Derive and set the location of native libraries for the given package, 8750 * which varies depending on where and how the package was installed. 8751 */ 8752 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8753 final ApplicationInfo info = pkg.applicationInfo; 8754 final String codePath = pkg.codePath; 8755 final File codeFile = new File(codePath); 8756 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8757 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8758 8759 info.nativeLibraryRootDir = null; 8760 info.nativeLibraryRootRequiresIsa = false; 8761 info.nativeLibraryDir = null; 8762 info.secondaryNativeLibraryDir = null; 8763 8764 if (isApkFile(codeFile)) { 8765 // Monolithic install 8766 if (bundledApp) { 8767 // If "/system/lib64/apkname" exists, assume that is the per-package 8768 // native library directory to use; otherwise use "/system/lib/apkname". 8769 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8770 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8771 getPrimaryInstructionSet(info)); 8772 8773 // This is a bundled system app so choose the path based on the ABI. 8774 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8775 // is just the default path. 8776 final String apkName = deriveCodePathName(codePath); 8777 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8778 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8779 apkName).getAbsolutePath(); 8780 8781 if (info.secondaryCpuAbi != null) { 8782 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8783 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8784 secondaryLibDir, apkName).getAbsolutePath(); 8785 } 8786 } else if (asecApp) { 8787 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8788 .getAbsolutePath(); 8789 } else { 8790 final String apkName = deriveCodePathName(codePath); 8791 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8792 .getAbsolutePath(); 8793 } 8794 8795 info.nativeLibraryRootRequiresIsa = false; 8796 info.nativeLibraryDir = info.nativeLibraryRootDir; 8797 } else { 8798 // Cluster install 8799 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8800 info.nativeLibraryRootRequiresIsa = true; 8801 8802 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8803 getPrimaryInstructionSet(info)).getAbsolutePath(); 8804 8805 if (info.secondaryCpuAbi != null) { 8806 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8807 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8808 } 8809 } 8810 } 8811 8812 /** 8813 * Calculate the abis and roots for a bundled app. These can uniquely 8814 * be determined from the contents of the system partition, i.e whether 8815 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8816 * of this information, and instead assume that the system was built 8817 * sensibly. 8818 */ 8819 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8820 PackageSetting pkgSetting) { 8821 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8822 8823 // If "/system/lib64/apkname" exists, assume that is the per-package 8824 // native library directory to use; otherwise use "/system/lib/apkname". 8825 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8826 setBundledAppAbi(pkg, apkRoot, apkName); 8827 // pkgSetting might be null during rescan following uninstall of updates 8828 // to a bundled app, so accommodate that possibility. The settings in 8829 // that case will be established later from the parsed package. 8830 // 8831 // If the settings aren't null, sync them up with what we've just derived. 8832 // note that apkRoot isn't stored in the package settings. 8833 if (pkgSetting != null) { 8834 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8835 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8836 } 8837 } 8838 8839 /** 8840 * Deduces the ABI of a bundled app and sets the relevant fields on the 8841 * parsed pkg object. 8842 * 8843 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8844 * under which system libraries are installed. 8845 * @param apkName the name of the installed package. 8846 */ 8847 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8848 final File codeFile = new File(pkg.codePath); 8849 8850 final boolean has64BitLibs; 8851 final boolean has32BitLibs; 8852 if (isApkFile(codeFile)) { 8853 // Monolithic install 8854 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8855 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8856 } else { 8857 // Cluster install 8858 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8859 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8860 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8861 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8862 has64BitLibs = (new File(rootDir, isa)).exists(); 8863 } else { 8864 has64BitLibs = false; 8865 } 8866 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8867 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8868 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8869 has32BitLibs = (new File(rootDir, isa)).exists(); 8870 } else { 8871 has32BitLibs = false; 8872 } 8873 } 8874 8875 if (has64BitLibs && !has32BitLibs) { 8876 // The package has 64 bit libs, but not 32 bit libs. Its primary 8877 // ABI should be 64 bit. We can safely assume here that the bundled 8878 // native libraries correspond to the most preferred ABI in the list. 8879 8880 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8881 pkg.applicationInfo.secondaryCpuAbi = null; 8882 } else if (has32BitLibs && !has64BitLibs) { 8883 // The package has 32 bit libs but not 64 bit libs. Its primary 8884 // ABI should be 32 bit. 8885 8886 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8887 pkg.applicationInfo.secondaryCpuAbi = null; 8888 } else if (has32BitLibs && has64BitLibs) { 8889 // The application has both 64 and 32 bit bundled libraries. We check 8890 // here that the app declares multiArch support, and warn if it doesn't. 8891 // 8892 // We will be lenient here and record both ABIs. The primary will be the 8893 // ABI that's higher on the list, i.e, a device that's configured to prefer 8894 // 64 bit apps will see a 64 bit primary ABI, 8895 8896 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8897 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 8898 } 8899 8900 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8901 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8902 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8903 } else { 8904 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8905 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8906 } 8907 } else { 8908 pkg.applicationInfo.primaryCpuAbi = null; 8909 pkg.applicationInfo.secondaryCpuAbi = null; 8910 } 8911 } 8912 8913 private void killPackage(PackageParser.Package pkg, String reason) { 8914 // Kill the parent package 8915 killApplication(pkg.packageName, pkg.applicationInfo.uid, reason); 8916 // Kill the child packages 8917 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8918 for (int i = 0; i < childCount; i++) { 8919 PackageParser.Package childPkg = pkg.childPackages.get(i); 8920 killApplication(childPkg.packageName, childPkg.applicationInfo.uid, reason); 8921 } 8922 } 8923 8924 private void killApplication(String pkgName, int appId, String reason) { 8925 // Request the ActivityManager to kill the process(only for existing packages) 8926 // so that we do not end up in a confused state while the user is still using the older 8927 // version of the application while the new one gets installed. 8928 IActivityManager am = ActivityManagerNative.getDefault(); 8929 if (am != null) { 8930 try { 8931 am.killApplicationWithAppId(pkgName, appId, reason); 8932 } catch (RemoteException e) { 8933 } 8934 } 8935 } 8936 8937 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 8938 // Remove the parent package setting 8939 PackageSetting ps = (PackageSetting) pkg.mExtras; 8940 if (ps != null) { 8941 removePackageLI(ps, chatty); 8942 } 8943 // Remove the child package setting 8944 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8945 for (int i = 0; i < childCount; i++) { 8946 PackageParser.Package childPkg = pkg.childPackages.get(i); 8947 ps = (PackageSetting) childPkg.mExtras; 8948 if (ps != null) { 8949 removePackageLI(ps, chatty); 8950 } 8951 } 8952 } 8953 8954 void removePackageLI(PackageSetting ps, boolean chatty) { 8955 if (DEBUG_INSTALL) { 8956 if (chatty) 8957 Log.d(TAG, "Removing package " + ps.name); 8958 } 8959 8960 // writer 8961 synchronized (mPackages) { 8962 mPackages.remove(ps.name); 8963 final PackageParser.Package pkg = ps.pkg; 8964 if (pkg != null) { 8965 cleanPackageDataStructuresLILPw(pkg, chatty); 8966 } 8967 } 8968 } 8969 8970 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8971 if (DEBUG_INSTALL) { 8972 if (chatty) 8973 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8974 } 8975 8976 // writer 8977 synchronized (mPackages) { 8978 // Remove the parent package 8979 mPackages.remove(pkg.applicationInfo.packageName); 8980 cleanPackageDataStructuresLILPw(pkg, chatty); 8981 8982 // Remove the child packages 8983 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8984 for (int i = 0; i < childCount; i++) { 8985 PackageParser.Package childPkg = pkg.childPackages.get(i); 8986 mPackages.remove(childPkg.applicationInfo.packageName); 8987 cleanPackageDataStructuresLILPw(childPkg, chatty); 8988 } 8989 } 8990 } 8991 8992 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8993 int N = pkg.providers.size(); 8994 StringBuilder r = null; 8995 int i; 8996 for (i=0; i<N; i++) { 8997 PackageParser.Provider p = pkg.providers.get(i); 8998 mProviders.removeProvider(p); 8999 if (p.info.authority == null) { 9000 9001 /* There was another ContentProvider with this authority when 9002 * this app was installed so this authority is null, 9003 * Ignore it as we don't have to unregister the provider. 9004 */ 9005 continue; 9006 } 9007 String names[] = p.info.authority.split(";"); 9008 for (int j = 0; j < names.length; j++) { 9009 if (mProvidersByAuthority.get(names[j]) == p) { 9010 mProvidersByAuthority.remove(names[j]); 9011 if (DEBUG_REMOVE) { 9012 if (chatty) 9013 Log.d(TAG, "Unregistered content provider: " + names[j] 9014 + ", className = " + p.info.name + ", isSyncable = " 9015 + p.info.isSyncable); 9016 } 9017 } 9018 } 9019 if (DEBUG_REMOVE && chatty) { 9020 if (r == null) { 9021 r = new StringBuilder(256); 9022 } else { 9023 r.append(' '); 9024 } 9025 r.append(p.info.name); 9026 } 9027 } 9028 if (r != null) { 9029 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9030 } 9031 9032 N = pkg.services.size(); 9033 r = null; 9034 for (i=0; i<N; i++) { 9035 PackageParser.Service s = pkg.services.get(i); 9036 mServices.removeService(s); 9037 if (chatty) { 9038 if (r == null) { 9039 r = new StringBuilder(256); 9040 } else { 9041 r.append(' '); 9042 } 9043 r.append(s.info.name); 9044 } 9045 } 9046 if (r != null) { 9047 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9048 } 9049 9050 N = pkg.receivers.size(); 9051 r = null; 9052 for (i=0; i<N; i++) { 9053 PackageParser.Activity a = pkg.receivers.get(i); 9054 mReceivers.removeActivity(a, "receiver"); 9055 if (DEBUG_REMOVE && chatty) { 9056 if (r == null) { 9057 r = new StringBuilder(256); 9058 } else { 9059 r.append(' '); 9060 } 9061 r.append(a.info.name); 9062 } 9063 } 9064 if (r != null) { 9065 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9066 } 9067 9068 N = pkg.activities.size(); 9069 r = null; 9070 for (i=0; i<N; i++) { 9071 PackageParser.Activity a = pkg.activities.get(i); 9072 mActivities.removeActivity(a, "activity"); 9073 if (DEBUG_REMOVE && chatty) { 9074 if (r == null) { 9075 r = new StringBuilder(256); 9076 } else { 9077 r.append(' '); 9078 } 9079 r.append(a.info.name); 9080 } 9081 } 9082 if (r != null) { 9083 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9084 } 9085 9086 N = pkg.permissions.size(); 9087 r = null; 9088 for (i=0; i<N; i++) { 9089 PackageParser.Permission p = pkg.permissions.get(i); 9090 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9091 if (bp == null) { 9092 bp = mSettings.mPermissionTrees.get(p.info.name); 9093 } 9094 if (bp != null && bp.perm == p) { 9095 bp.perm = null; 9096 if (DEBUG_REMOVE && chatty) { 9097 if (r == null) { 9098 r = new StringBuilder(256); 9099 } else { 9100 r.append(' '); 9101 } 9102 r.append(p.info.name); 9103 } 9104 } 9105 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9106 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9107 if (appOpPkgs != null) { 9108 appOpPkgs.remove(pkg.packageName); 9109 } 9110 } 9111 } 9112 if (r != null) { 9113 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9114 } 9115 9116 N = pkg.requestedPermissions.size(); 9117 r = null; 9118 for (i=0; i<N; i++) { 9119 String perm = pkg.requestedPermissions.get(i); 9120 BasePermission bp = mSettings.mPermissions.get(perm); 9121 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9122 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9123 if (appOpPkgs != null) { 9124 appOpPkgs.remove(pkg.packageName); 9125 if (appOpPkgs.isEmpty()) { 9126 mAppOpPermissionPackages.remove(perm); 9127 } 9128 } 9129 } 9130 } 9131 if (r != null) { 9132 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9133 } 9134 9135 N = pkg.instrumentation.size(); 9136 r = null; 9137 for (i=0; i<N; i++) { 9138 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9139 mInstrumentation.remove(a.getComponentName()); 9140 if (DEBUG_REMOVE && chatty) { 9141 if (r == null) { 9142 r = new StringBuilder(256); 9143 } else { 9144 r.append(' '); 9145 } 9146 r.append(a.info.name); 9147 } 9148 } 9149 if (r != null) { 9150 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9151 } 9152 9153 r = null; 9154 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9155 // Only system apps can hold shared libraries. 9156 if (pkg.libraryNames != null) { 9157 for (i=0; i<pkg.libraryNames.size(); i++) { 9158 String name = pkg.libraryNames.get(i); 9159 SharedLibraryEntry cur = mSharedLibraries.get(name); 9160 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9161 mSharedLibraries.remove(name); 9162 if (DEBUG_REMOVE && chatty) { 9163 if (r == null) { 9164 r = new StringBuilder(256); 9165 } else { 9166 r.append(' '); 9167 } 9168 r.append(name); 9169 } 9170 } 9171 } 9172 } 9173 } 9174 if (r != null) { 9175 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9176 } 9177 } 9178 9179 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9180 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9181 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9182 return true; 9183 } 9184 } 9185 return false; 9186 } 9187 9188 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9189 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9190 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9191 9192 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9193 // Update the parent permissions 9194 updatePermissionsLPw(pkg.packageName, pkg, flags); 9195 // Update the child permissions 9196 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9197 for (int i = 0; i < childCount; i++) { 9198 PackageParser.Package childPkg = pkg.childPackages.get(i); 9199 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9200 } 9201 } 9202 9203 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9204 int flags) { 9205 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9206 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9207 } 9208 9209 private void updatePermissionsLPw(String changingPkg, 9210 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9211 // Make sure there are no dangling permission trees. 9212 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9213 while (it.hasNext()) { 9214 final BasePermission bp = it.next(); 9215 if (bp.packageSetting == null) { 9216 // We may not yet have parsed the package, so just see if 9217 // we still know about its settings. 9218 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9219 } 9220 if (bp.packageSetting == null) { 9221 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9222 + " from package " + bp.sourcePackage); 9223 it.remove(); 9224 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9225 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9226 Slog.i(TAG, "Removing old permission tree: " + bp.name 9227 + " from package " + bp.sourcePackage); 9228 flags |= UPDATE_PERMISSIONS_ALL; 9229 it.remove(); 9230 } 9231 } 9232 } 9233 9234 // Make sure all dynamic permissions have been assigned to a package, 9235 // and make sure there are no dangling permissions. 9236 it = mSettings.mPermissions.values().iterator(); 9237 while (it.hasNext()) { 9238 final BasePermission bp = it.next(); 9239 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9240 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9241 + bp.name + " pkg=" + bp.sourcePackage 9242 + " info=" + bp.pendingInfo); 9243 if (bp.packageSetting == null && bp.pendingInfo != null) { 9244 final BasePermission tree = findPermissionTreeLP(bp.name); 9245 if (tree != null && tree.perm != null) { 9246 bp.packageSetting = tree.packageSetting; 9247 bp.perm = new PackageParser.Permission(tree.perm.owner, 9248 new PermissionInfo(bp.pendingInfo)); 9249 bp.perm.info.packageName = tree.perm.info.packageName; 9250 bp.perm.info.name = bp.name; 9251 bp.uid = tree.uid; 9252 } 9253 } 9254 } 9255 if (bp.packageSetting == null) { 9256 // We may not yet have parsed the package, so just see if 9257 // we still know about its settings. 9258 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9259 } 9260 if (bp.packageSetting == null) { 9261 Slog.w(TAG, "Removing dangling permission: " + bp.name 9262 + " from package " + bp.sourcePackage); 9263 it.remove(); 9264 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9265 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9266 Slog.i(TAG, "Removing old permission: " + bp.name 9267 + " from package " + bp.sourcePackage); 9268 flags |= UPDATE_PERMISSIONS_ALL; 9269 it.remove(); 9270 } 9271 } 9272 } 9273 9274 // Now update the permissions for all packages, in particular 9275 // replace the granted permissions of the system packages. 9276 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9277 for (PackageParser.Package pkg : mPackages.values()) { 9278 if (pkg != pkgInfo) { 9279 // Only replace for packages on requested volume 9280 final String volumeUuid = getVolumeUuidForPackage(pkg); 9281 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9282 && Objects.equals(replaceVolumeUuid, volumeUuid); 9283 grantPermissionsLPw(pkg, replace, changingPkg); 9284 } 9285 } 9286 } 9287 9288 if (pkgInfo != null) { 9289 // Only replace for packages on requested volume 9290 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9291 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9292 && Objects.equals(replaceVolumeUuid, volumeUuid); 9293 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9294 } 9295 } 9296 9297 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9298 String packageOfInterest) { 9299 // IMPORTANT: There are two types of permissions: install and runtime. 9300 // Install time permissions are granted when the app is installed to 9301 // all device users and users added in the future. Runtime permissions 9302 // are granted at runtime explicitly to specific users. Normal and signature 9303 // protected permissions are install time permissions. Dangerous permissions 9304 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9305 // otherwise they are runtime permissions. This function does not manage 9306 // runtime permissions except for the case an app targeting Lollipop MR1 9307 // being upgraded to target a newer SDK, in which case dangerous permissions 9308 // are transformed from install time to runtime ones. 9309 9310 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9311 if (ps == null) { 9312 return; 9313 } 9314 9315 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9316 9317 PermissionsState permissionsState = ps.getPermissionsState(); 9318 PermissionsState origPermissions = permissionsState; 9319 9320 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9321 9322 boolean runtimePermissionsRevoked = false; 9323 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9324 9325 boolean changedInstallPermission = false; 9326 9327 if (replace) { 9328 ps.installPermissionsFixed = false; 9329 if (!ps.isSharedUser()) { 9330 origPermissions = new PermissionsState(permissionsState); 9331 permissionsState.reset(); 9332 } else { 9333 // We need to know only about runtime permission changes since the 9334 // calling code always writes the install permissions state but 9335 // the runtime ones are written only if changed. The only cases of 9336 // changed runtime permissions here are promotion of an install to 9337 // runtime and revocation of a runtime from a shared user. 9338 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9339 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9340 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9341 runtimePermissionsRevoked = true; 9342 } 9343 } 9344 } 9345 9346 permissionsState.setGlobalGids(mGlobalGids); 9347 9348 final int N = pkg.requestedPermissions.size(); 9349 for (int i=0; i<N; i++) { 9350 final String name = pkg.requestedPermissions.get(i); 9351 final BasePermission bp = mSettings.mPermissions.get(name); 9352 9353 if (DEBUG_INSTALL) { 9354 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9355 } 9356 9357 if (bp == null || bp.packageSetting == null) { 9358 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9359 Slog.w(TAG, "Unknown permission " + name 9360 + " in package " + pkg.packageName); 9361 } 9362 continue; 9363 } 9364 9365 final String perm = bp.name; 9366 boolean allowedSig = false; 9367 int grant = GRANT_DENIED; 9368 9369 // Keep track of app op permissions. 9370 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9371 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9372 if (pkgs == null) { 9373 pkgs = new ArraySet<>(); 9374 mAppOpPermissionPackages.put(bp.name, pkgs); 9375 } 9376 pkgs.add(pkg.packageName); 9377 } 9378 9379 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9380 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9381 >= Build.VERSION_CODES.M; 9382 switch (level) { 9383 case PermissionInfo.PROTECTION_NORMAL: { 9384 // For all apps normal permissions are install time ones. 9385 grant = GRANT_INSTALL; 9386 } break; 9387 9388 case PermissionInfo.PROTECTION_DANGEROUS: { 9389 // If a permission review is required for legacy apps we represent 9390 // their permissions as always granted runtime ones since we need 9391 // to keep the review required permission flag per user while an 9392 // install permission's state is shared across all users. 9393 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9394 // For legacy apps dangerous permissions are install time ones. 9395 grant = GRANT_INSTALL; 9396 } else if (origPermissions.hasInstallPermission(bp.name)) { 9397 // For legacy apps that became modern, install becomes runtime. 9398 grant = GRANT_UPGRADE; 9399 } else if (mPromoteSystemApps 9400 && isSystemApp(ps) 9401 && mExistingSystemPackages.contains(ps.name)) { 9402 // For legacy system apps, install becomes runtime. 9403 // We cannot check hasInstallPermission() for system apps since those 9404 // permissions were granted implicitly and not persisted pre-M. 9405 grant = GRANT_UPGRADE; 9406 } else { 9407 // For modern apps keep runtime permissions unchanged. 9408 grant = GRANT_RUNTIME; 9409 } 9410 } break; 9411 9412 case PermissionInfo.PROTECTION_SIGNATURE: { 9413 // For all apps signature permissions are install time ones. 9414 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9415 if (allowedSig) { 9416 grant = GRANT_INSTALL; 9417 } 9418 } break; 9419 } 9420 9421 if (DEBUG_INSTALL) { 9422 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9423 } 9424 9425 if (grant != GRANT_DENIED) { 9426 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9427 // If this is an existing, non-system package, then 9428 // we can't add any new permissions to it. 9429 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9430 // Except... if this is a permission that was added 9431 // to the platform (note: need to only do this when 9432 // updating the platform). 9433 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9434 grant = GRANT_DENIED; 9435 } 9436 } 9437 } 9438 9439 switch (grant) { 9440 case GRANT_INSTALL: { 9441 // Revoke this as runtime permission to handle the case of 9442 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 9443 for (int userId : UserManagerService.getInstance().getUserIds()) { 9444 if (origPermissions.getRuntimePermissionState( 9445 bp.name, userId) != null) { 9446 // Revoke the runtime permission and clear the flags. 9447 origPermissions.revokeRuntimePermission(bp, userId); 9448 origPermissions.updatePermissionFlags(bp, userId, 9449 PackageManager.MASK_PERMISSION_FLAGS, 0); 9450 // If we revoked a permission permission, we have to write. 9451 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9452 changedRuntimePermissionUserIds, userId); 9453 } 9454 } 9455 // Grant an install permission. 9456 if (permissionsState.grantInstallPermission(bp) != 9457 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9458 changedInstallPermission = true; 9459 } 9460 } break; 9461 9462 case GRANT_RUNTIME: { 9463 // Grant previously granted runtime permissions. 9464 for (int userId : UserManagerService.getInstance().getUserIds()) { 9465 PermissionState permissionState = origPermissions 9466 .getRuntimePermissionState(bp.name, userId); 9467 int flags = permissionState != null 9468 ? permissionState.getFlags() : 0; 9469 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9470 if (permissionsState.grantRuntimePermission(bp, userId) == 9471 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9472 // If we cannot put the permission as it was, we have to write. 9473 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9474 changedRuntimePermissionUserIds, userId); 9475 } 9476 // If the app supports runtime permissions no need for a review. 9477 if (Build.PERMISSIONS_REVIEW_REQUIRED 9478 && appSupportsRuntimePermissions 9479 && (flags & PackageManager 9480 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9481 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9482 // Since we changed the flags, we have to write. 9483 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9484 changedRuntimePermissionUserIds, userId); 9485 } 9486 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9487 && !appSupportsRuntimePermissions) { 9488 // For legacy apps that need a permission review, every new 9489 // runtime permission is granted but it is pending a review. 9490 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9491 permissionsState.grantRuntimePermission(bp, userId); 9492 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9493 // We changed the permission and flags, hence have to write. 9494 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9495 changedRuntimePermissionUserIds, userId); 9496 } 9497 } 9498 // Propagate the permission flags. 9499 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9500 } 9501 } break; 9502 9503 case GRANT_UPGRADE: { 9504 // Grant runtime permissions for a previously held install permission. 9505 PermissionState permissionState = origPermissions 9506 .getInstallPermissionState(bp.name); 9507 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9508 9509 if (origPermissions.revokeInstallPermission(bp) 9510 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9511 // We will be transferring the permission flags, so clear them. 9512 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9513 PackageManager.MASK_PERMISSION_FLAGS, 0); 9514 changedInstallPermission = true; 9515 } 9516 9517 // If the permission is not to be promoted to runtime we ignore it and 9518 // also its other flags as they are not applicable to install permissions. 9519 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9520 for (int userId : currentUserIds) { 9521 if (permissionsState.grantRuntimePermission(bp, userId) != 9522 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9523 // Transfer the permission flags. 9524 permissionsState.updatePermissionFlags(bp, userId, 9525 flags, flags); 9526 // If we granted the permission, we have to write. 9527 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9528 changedRuntimePermissionUserIds, userId); 9529 } 9530 } 9531 } 9532 } break; 9533 9534 default: { 9535 if (packageOfInterest == null 9536 || packageOfInterest.equals(pkg.packageName)) { 9537 Slog.w(TAG, "Not granting permission " + perm 9538 + " to package " + pkg.packageName 9539 + " because it was previously installed without"); 9540 } 9541 } break; 9542 } 9543 } else { 9544 if (permissionsState.revokeInstallPermission(bp) != 9545 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9546 // Also drop the permission flags. 9547 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9548 PackageManager.MASK_PERMISSION_FLAGS, 0); 9549 changedInstallPermission = true; 9550 Slog.i(TAG, "Un-granting permission " + perm 9551 + " from package " + pkg.packageName 9552 + " (protectionLevel=" + bp.protectionLevel 9553 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9554 + ")"); 9555 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9556 // Don't print warning for app op permissions, since it is fine for them 9557 // not to be granted, there is a UI for the user to decide. 9558 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9559 Slog.w(TAG, "Not granting permission " + perm 9560 + " to package " + pkg.packageName 9561 + " (protectionLevel=" + bp.protectionLevel 9562 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9563 + ")"); 9564 } 9565 } 9566 } 9567 } 9568 9569 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9570 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9571 // This is the first that we have heard about this package, so the 9572 // permissions we have now selected are fixed until explicitly 9573 // changed. 9574 ps.installPermissionsFixed = true; 9575 } 9576 9577 // Persist the runtime permissions state for users with changes. If permissions 9578 // were revoked because no app in the shared user declares them we have to 9579 // write synchronously to avoid losing runtime permissions state. 9580 for (int userId : changedRuntimePermissionUserIds) { 9581 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9582 } 9583 9584 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9585 } 9586 9587 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9588 boolean allowed = false; 9589 final int NP = PackageParser.NEW_PERMISSIONS.length; 9590 for (int ip=0; ip<NP; ip++) { 9591 final PackageParser.NewPermissionInfo npi 9592 = PackageParser.NEW_PERMISSIONS[ip]; 9593 if (npi.name.equals(perm) 9594 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9595 allowed = true; 9596 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9597 + pkg.packageName); 9598 break; 9599 } 9600 } 9601 return allowed; 9602 } 9603 9604 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9605 BasePermission bp, PermissionsState origPermissions) { 9606 boolean allowed; 9607 allowed = (compareSignatures( 9608 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9609 == PackageManager.SIGNATURE_MATCH) 9610 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9611 == PackageManager.SIGNATURE_MATCH); 9612 if (!allowed && (bp.protectionLevel 9613 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9614 if (isSystemApp(pkg)) { 9615 // For updated system applications, a system permission 9616 // is granted only if it had been defined by the original application. 9617 if (pkg.isUpdatedSystemApp()) { 9618 final PackageSetting sysPs = mSettings 9619 .getDisabledSystemPkgLPr(pkg.packageName); 9620 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9621 // If the original was granted this permission, we take 9622 // that grant decision as read and propagate it to the 9623 // update. 9624 if (sysPs.isPrivileged()) { 9625 allowed = true; 9626 } 9627 } else { 9628 // The system apk may have been updated with an older 9629 // version of the one on the data partition, but which 9630 // granted a new system permission that it didn't have 9631 // before. In this case we do want to allow the app to 9632 // now get the new permission if the ancestral apk is 9633 // privileged to get it. 9634 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9635 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9636 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9637 allowed = true; 9638 break; 9639 } 9640 } 9641 } 9642 // Also if a privileged parent package on the system image or any of 9643 // its children requested a privileged permission, the updated child 9644 // packages can also get the permission. 9645 if (pkg.parentPackage != null) { 9646 final PackageSetting disabledSysParentPs = mSettings 9647 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 9648 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 9649 && disabledSysParentPs.isPrivileged()) { 9650 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 9651 allowed = true; 9652 } else if (disabledSysParentPs.pkg.childPackages != null) { 9653 final int count = disabledSysParentPs.pkg.childPackages.size(); 9654 for (int i = 0; i < count; i++) { 9655 PackageParser.Package disabledSysChildPkg = 9656 disabledSysParentPs.pkg.childPackages.get(i); 9657 if (isPackageRequestingPermission(disabledSysChildPkg, 9658 perm)) { 9659 allowed = true; 9660 break; 9661 } 9662 } 9663 } 9664 } 9665 } 9666 } 9667 } else { 9668 allowed = isPrivilegedApp(pkg); 9669 } 9670 } 9671 } 9672 if (!allowed) { 9673 if (!allowed && (bp.protectionLevel 9674 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9675 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9676 // If this was a previously normal/dangerous permission that got moved 9677 // to a system permission as part of the runtime permission redesign, then 9678 // we still want to blindly grant it to old apps. 9679 allowed = true; 9680 } 9681 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9682 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9683 // If this permission is to be granted to the system installer and 9684 // this app is an installer, then it gets the permission. 9685 allowed = true; 9686 } 9687 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9688 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9689 // If this permission is to be granted to the system verifier and 9690 // this app is a verifier, then it gets the permission. 9691 allowed = true; 9692 } 9693 if (!allowed && (bp.protectionLevel 9694 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9695 && isSystemApp(pkg)) { 9696 // Any pre-installed system app is allowed to get this permission. 9697 allowed = true; 9698 } 9699 if (!allowed && (bp.protectionLevel 9700 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9701 // For development permissions, a development permission 9702 // is granted only if it was already granted. 9703 allowed = origPermissions.hasInstallPermission(perm); 9704 } 9705 } 9706 return allowed; 9707 } 9708 9709 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 9710 final int permCount = pkg.requestedPermissions.size(); 9711 for (int j = 0; j < permCount; j++) { 9712 String requestedPermission = pkg.requestedPermissions.get(j); 9713 if (permission.equals(requestedPermission)) { 9714 return true; 9715 } 9716 } 9717 return false; 9718 } 9719 9720 final class ActivityIntentResolver 9721 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9722 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9723 boolean defaultOnly, int userId) { 9724 if (!sUserManager.exists(userId)) return null; 9725 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9726 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9727 } 9728 9729 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9730 int userId) { 9731 if (!sUserManager.exists(userId)) return null; 9732 mFlags = flags; 9733 return super.queryIntent(intent, resolvedType, 9734 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9735 } 9736 9737 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9738 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9739 if (!sUserManager.exists(userId)) return null; 9740 if (packageActivities == null) { 9741 return null; 9742 } 9743 mFlags = flags; 9744 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9745 final int N = packageActivities.size(); 9746 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9747 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9748 9749 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9750 for (int i = 0; i < N; ++i) { 9751 intentFilters = packageActivities.get(i).intents; 9752 if (intentFilters != null && intentFilters.size() > 0) { 9753 PackageParser.ActivityIntentInfo[] array = 9754 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9755 intentFilters.toArray(array); 9756 listCut.add(array); 9757 } 9758 } 9759 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9760 } 9761 9762 public final void addActivity(PackageParser.Activity a, String type) { 9763 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 9764 mActivities.put(a.getComponentName(), a); 9765 if (DEBUG_SHOW_INFO) 9766 Log.v( 9767 TAG, " " + type + " " + 9768 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 9769 if (DEBUG_SHOW_INFO) 9770 Log.v(TAG, " Class=" + a.info.name); 9771 final int NI = a.intents.size(); 9772 for (int j=0; j<NI; j++) { 9773 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9774 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 9775 intent.setPriority(0); 9776 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 9777 + a.className + " with priority > 0, forcing to 0"); 9778 } 9779 if (DEBUG_SHOW_INFO) { 9780 Log.v(TAG, " IntentFilter:"); 9781 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9782 } 9783 if (!intent.debugCheck()) { 9784 Log.w(TAG, "==> For Activity " + a.info.name); 9785 } 9786 addFilter(intent); 9787 } 9788 } 9789 9790 public final void removeActivity(PackageParser.Activity a, String type) { 9791 mActivities.remove(a.getComponentName()); 9792 if (DEBUG_SHOW_INFO) { 9793 Log.v(TAG, " " + type + " " 9794 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 9795 : a.info.name) + ":"); 9796 Log.v(TAG, " Class=" + a.info.name); 9797 } 9798 final int NI = a.intents.size(); 9799 for (int j=0; j<NI; j++) { 9800 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9801 if (DEBUG_SHOW_INFO) { 9802 Log.v(TAG, " IntentFilter:"); 9803 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9804 } 9805 removeFilter(intent); 9806 } 9807 } 9808 9809 @Override 9810 protected boolean allowFilterResult( 9811 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 9812 ActivityInfo filterAi = filter.activity.info; 9813 for (int i=dest.size()-1; i>=0; i--) { 9814 ActivityInfo destAi = dest.get(i).activityInfo; 9815 if (destAi.name == filterAi.name 9816 && destAi.packageName == filterAi.packageName) { 9817 return false; 9818 } 9819 } 9820 return true; 9821 } 9822 9823 @Override 9824 protected ActivityIntentInfo[] newArray(int size) { 9825 return new ActivityIntentInfo[size]; 9826 } 9827 9828 @Override 9829 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 9830 if (!sUserManager.exists(userId)) return true; 9831 PackageParser.Package p = filter.activity.owner; 9832 if (p != null) { 9833 PackageSetting ps = (PackageSetting)p.mExtras; 9834 if (ps != null) { 9835 // System apps are never considered stopped for purposes of 9836 // filtering, because there may be no way for the user to 9837 // actually re-launch them. 9838 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 9839 && ps.getStopped(userId); 9840 } 9841 } 9842 return false; 9843 } 9844 9845 @Override 9846 protected boolean isPackageForFilter(String packageName, 9847 PackageParser.ActivityIntentInfo info) { 9848 return packageName.equals(info.activity.owner.packageName); 9849 } 9850 9851 @Override 9852 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 9853 int match, int userId) { 9854 if (!sUserManager.exists(userId)) return null; 9855 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 9856 return null; 9857 } 9858 final PackageParser.Activity activity = info.activity; 9859 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 9860 if (ps == null) { 9861 return null; 9862 } 9863 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 9864 ps.readUserState(userId), userId); 9865 if (ai == null) { 9866 return null; 9867 } 9868 final ResolveInfo res = new ResolveInfo(); 9869 res.activityInfo = ai; 9870 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9871 res.filter = info; 9872 } 9873 if (info != null) { 9874 res.handleAllWebDataURI = info.handleAllWebDataURI(); 9875 } 9876 res.priority = info.getPriority(); 9877 res.preferredOrder = activity.owner.mPreferredOrder; 9878 //System.out.println("Result: " + res.activityInfo.className + 9879 // " = " + res.priority); 9880 res.match = match; 9881 res.isDefault = info.hasDefault; 9882 res.labelRes = info.labelRes; 9883 res.nonLocalizedLabel = info.nonLocalizedLabel; 9884 if (userNeedsBadging(userId)) { 9885 res.noResourceId = true; 9886 } else { 9887 res.icon = info.icon; 9888 } 9889 res.iconResourceId = info.icon; 9890 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9891 return res; 9892 } 9893 9894 @Override 9895 protected void sortResults(List<ResolveInfo> results) { 9896 Collections.sort(results, mResolvePrioritySorter); 9897 } 9898 9899 @Override 9900 protected void dumpFilter(PrintWriter out, String prefix, 9901 PackageParser.ActivityIntentInfo filter) { 9902 out.print(prefix); out.print( 9903 Integer.toHexString(System.identityHashCode(filter.activity))); 9904 out.print(' '); 9905 filter.activity.printComponentShortName(out); 9906 out.print(" filter "); 9907 out.println(Integer.toHexString(System.identityHashCode(filter))); 9908 } 9909 9910 @Override 9911 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9912 return filter.activity; 9913 } 9914 9915 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9916 PackageParser.Activity activity = (PackageParser.Activity)label; 9917 out.print(prefix); out.print( 9918 Integer.toHexString(System.identityHashCode(activity))); 9919 out.print(' '); 9920 activity.printComponentShortName(out); 9921 if (count > 1) { 9922 out.print(" ("); out.print(count); out.print(" filters)"); 9923 } 9924 out.println(); 9925 } 9926 9927// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9928// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9929// final List<ResolveInfo> retList = Lists.newArrayList(); 9930// while (i.hasNext()) { 9931// final ResolveInfo resolveInfo = i.next(); 9932// if (isEnabledLP(resolveInfo.activityInfo)) { 9933// retList.add(resolveInfo); 9934// } 9935// } 9936// return retList; 9937// } 9938 9939 // Keys are String (activity class name), values are Activity. 9940 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9941 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9942 private int mFlags; 9943 } 9944 9945 private final class ServiceIntentResolver 9946 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9947 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9948 boolean defaultOnly, int userId) { 9949 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9950 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9951 } 9952 9953 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9954 int userId) { 9955 if (!sUserManager.exists(userId)) return null; 9956 mFlags = flags; 9957 return super.queryIntent(intent, resolvedType, 9958 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9959 } 9960 9961 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9962 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9963 if (!sUserManager.exists(userId)) return null; 9964 if (packageServices == null) { 9965 return null; 9966 } 9967 mFlags = flags; 9968 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9969 final int N = packageServices.size(); 9970 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9971 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9972 9973 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9974 for (int i = 0; i < N; ++i) { 9975 intentFilters = packageServices.get(i).intents; 9976 if (intentFilters != null && intentFilters.size() > 0) { 9977 PackageParser.ServiceIntentInfo[] array = 9978 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9979 intentFilters.toArray(array); 9980 listCut.add(array); 9981 } 9982 } 9983 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9984 } 9985 9986 public final void addService(PackageParser.Service s) { 9987 mServices.put(s.getComponentName(), s); 9988 if (DEBUG_SHOW_INFO) { 9989 Log.v(TAG, " " 9990 + (s.info.nonLocalizedLabel != null 9991 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9992 Log.v(TAG, " Class=" + s.info.name); 9993 } 9994 final int NI = s.intents.size(); 9995 int j; 9996 for (j=0; j<NI; j++) { 9997 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9998 if (DEBUG_SHOW_INFO) { 9999 Log.v(TAG, " IntentFilter:"); 10000 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10001 } 10002 if (!intent.debugCheck()) { 10003 Log.w(TAG, "==> For Service " + s.info.name); 10004 } 10005 addFilter(intent); 10006 } 10007 } 10008 10009 public final void removeService(PackageParser.Service s) { 10010 mServices.remove(s.getComponentName()); 10011 if (DEBUG_SHOW_INFO) { 10012 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10013 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10014 Log.v(TAG, " Class=" + s.info.name); 10015 } 10016 final int NI = s.intents.size(); 10017 int j; 10018 for (j=0; j<NI; j++) { 10019 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10020 if (DEBUG_SHOW_INFO) { 10021 Log.v(TAG, " IntentFilter:"); 10022 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10023 } 10024 removeFilter(intent); 10025 } 10026 } 10027 10028 @Override 10029 protected boolean allowFilterResult( 10030 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10031 ServiceInfo filterSi = filter.service.info; 10032 for (int i=dest.size()-1; i>=0; i--) { 10033 ServiceInfo destAi = dest.get(i).serviceInfo; 10034 if (destAi.name == filterSi.name 10035 && destAi.packageName == filterSi.packageName) { 10036 return false; 10037 } 10038 } 10039 return true; 10040 } 10041 10042 @Override 10043 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10044 return new PackageParser.ServiceIntentInfo[size]; 10045 } 10046 10047 @Override 10048 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10049 if (!sUserManager.exists(userId)) return true; 10050 PackageParser.Package p = filter.service.owner; 10051 if (p != null) { 10052 PackageSetting ps = (PackageSetting)p.mExtras; 10053 if (ps != null) { 10054 // System apps are never considered stopped for purposes of 10055 // filtering, because there may be no way for the user to 10056 // actually re-launch them. 10057 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10058 && ps.getStopped(userId); 10059 } 10060 } 10061 return false; 10062 } 10063 10064 @Override 10065 protected boolean isPackageForFilter(String packageName, 10066 PackageParser.ServiceIntentInfo info) { 10067 return packageName.equals(info.service.owner.packageName); 10068 } 10069 10070 @Override 10071 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10072 int match, int userId) { 10073 if (!sUserManager.exists(userId)) return null; 10074 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10075 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10076 return null; 10077 } 10078 final PackageParser.Service service = info.service; 10079 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10080 if (ps == null) { 10081 return null; 10082 } 10083 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10084 ps.readUserState(userId), userId); 10085 if (si == null) { 10086 return null; 10087 } 10088 final ResolveInfo res = new ResolveInfo(); 10089 res.serviceInfo = si; 10090 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10091 res.filter = filter; 10092 } 10093 res.priority = info.getPriority(); 10094 res.preferredOrder = service.owner.mPreferredOrder; 10095 res.match = match; 10096 res.isDefault = info.hasDefault; 10097 res.labelRes = info.labelRes; 10098 res.nonLocalizedLabel = info.nonLocalizedLabel; 10099 res.icon = info.icon; 10100 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10101 return res; 10102 } 10103 10104 @Override 10105 protected void sortResults(List<ResolveInfo> results) { 10106 Collections.sort(results, mResolvePrioritySorter); 10107 } 10108 10109 @Override 10110 protected void dumpFilter(PrintWriter out, String prefix, 10111 PackageParser.ServiceIntentInfo filter) { 10112 out.print(prefix); out.print( 10113 Integer.toHexString(System.identityHashCode(filter.service))); 10114 out.print(' '); 10115 filter.service.printComponentShortName(out); 10116 out.print(" filter "); 10117 out.println(Integer.toHexString(System.identityHashCode(filter))); 10118 } 10119 10120 @Override 10121 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10122 return filter.service; 10123 } 10124 10125 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10126 PackageParser.Service service = (PackageParser.Service)label; 10127 out.print(prefix); out.print( 10128 Integer.toHexString(System.identityHashCode(service))); 10129 out.print(' '); 10130 service.printComponentShortName(out); 10131 if (count > 1) { 10132 out.print(" ("); out.print(count); out.print(" filters)"); 10133 } 10134 out.println(); 10135 } 10136 10137// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10138// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10139// final List<ResolveInfo> retList = Lists.newArrayList(); 10140// while (i.hasNext()) { 10141// final ResolveInfo resolveInfo = (ResolveInfo) i; 10142// if (isEnabledLP(resolveInfo.serviceInfo)) { 10143// retList.add(resolveInfo); 10144// } 10145// } 10146// return retList; 10147// } 10148 10149 // Keys are String (activity class name), values are Activity. 10150 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10151 = new ArrayMap<ComponentName, PackageParser.Service>(); 10152 private int mFlags; 10153 }; 10154 10155 private final class ProviderIntentResolver 10156 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10157 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10158 boolean defaultOnly, int userId) { 10159 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10160 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10161 } 10162 10163 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10164 int userId) { 10165 if (!sUserManager.exists(userId)) 10166 return null; 10167 mFlags = flags; 10168 return super.queryIntent(intent, resolvedType, 10169 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10170 } 10171 10172 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10173 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10174 if (!sUserManager.exists(userId)) 10175 return null; 10176 if (packageProviders == null) { 10177 return null; 10178 } 10179 mFlags = flags; 10180 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10181 final int N = packageProviders.size(); 10182 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10183 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10184 10185 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10186 for (int i = 0; i < N; ++i) { 10187 intentFilters = packageProviders.get(i).intents; 10188 if (intentFilters != null && intentFilters.size() > 0) { 10189 PackageParser.ProviderIntentInfo[] array = 10190 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10191 intentFilters.toArray(array); 10192 listCut.add(array); 10193 } 10194 } 10195 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10196 } 10197 10198 public final void addProvider(PackageParser.Provider p) { 10199 if (mProviders.containsKey(p.getComponentName())) { 10200 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10201 return; 10202 } 10203 10204 mProviders.put(p.getComponentName(), p); 10205 if (DEBUG_SHOW_INFO) { 10206 Log.v(TAG, " " 10207 + (p.info.nonLocalizedLabel != null 10208 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10209 Log.v(TAG, " Class=" + p.info.name); 10210 } 10211 final int NI = p.intents.size(); 10212 int j; 10213 for (j = 0; j < NI; j++) { 10214 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10215 if (DEBUG_SHOW_INFO) { 10216 Log.v(TAG, " IntentFilter:"); 10217 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10218 } 10219 if (!intent.debugCheck()) { 10220 Log.w(TAG, "==> For Provider " + p.info.name); 10221 } 10222 addFilter(intent); 10223 } 10224 } 10225 10226 public final void removeProvider(PackageParser.Provider p) { 10227 mProviders.remove(p.getComponentName()); 10228 if (DEBUG_SHOW_INFO) { 10229 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10230 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10231 Log.v(TAG, " Class=" + p.info.name); 10232 } 10233 final int NI = p.intents.size(); 10234 int j; 10235 for (j = 0; j < NI; j++) { 10236 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10237 if (DEBUG_SHOW_INFO) { 10238 Log.v(TAG, " IntentFilter:"); 10239 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10240 } 10241 removeFilter(intent); 10242 } 10243 } 10244 10245 @Override 10246 protected boolean allowFilterResult( 10247 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10248 ProviderInfo filterPi = filter.provider.info; 10249 for (int i = dest.size() - 1; i >= 0; i--) { 10250 ProviderInfo destPi = dest.get(i).providerInfo; 10251 if (destPi.name == filterPi.name 10252 && destPi.packageName == filterPi.packageName) { 10253 return false; 10254 } 10255 } 10256 return true; 10257 } 10258 10259 @Override 10260 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10261 return new PackageParser.ProviderIntentInfo[size]; 10262 } 10263 10264 @Override 10265 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10266 if (!sUserManager.exists(userId)) 10267 return true; 10268 PackageParser.Package p = filter.provider.owner; 10269 if (p != null) { 10270 PackageSetting ps = (PackageSetting) p.mExtras; 10271 if (ps != null) { 10272 // System apps are never considered stopped for purposes of 10273 // filtering, because there may be no way for the user to 10274 // actually re-launch them. 10275 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10276 && ps.getStopped(userId); 10277 } 10278 } 10279 return false; 10280 } 10281 10282 @Override 10283 protected boolean isPackageForFilter(String packageName, 10284 PackageParser.ProviderIntentInfo info) { 10285 return packageName.equals(info.provider.owner.packageName); 10286 } 10287 10288 @Override 10289 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10290 int match, int userId) { 10291 if (!sUserManager.exists(userId)) 10292 return null; 10293 final PackageParser.ProviderIntentInfo info = filter; 10294 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10295 return null; 10296 } 10297 final PackageParser.Provider provider = info.provider; 10298 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10299 if (ps == null) { 10300 return null; 10301 } 10302 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10303 ps.readUserState(userId), userId); 10304 if (pi == null) { 10305 return null; 10306 } 10307 final ResolveInfo res = new ResolveInfo(); 10308 res.providerInfo = pi; 10309 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10310 res.filter = filter; 10311 } 10312 res.priority = info.getPriority(); 10313 res.preferredOrder = provider.owner.mPreferredOrder; 10314 res.match = match; 10315 res.isDefault = info.hasDefault; 10316 res.labelRes = info.labelRes; 10317 res.nonLocalizedLabel = info.nonLocalizedLabel; 10318 res.icon = info.icon; 10319 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10320 return res; 10321 } 10322 10323 @Override 10324 protected void sortResults(List<ResolveInfo> results) { 10325 Collections.sort(results, mResolvePrioritySorter); 10326 } 10327 10328 @Override 10329 protected void dumpFilter(PrintWriter out, String prefix, 10330 PackageParser.ProviderIntentInfo filter) { 10331 out.print(prefix); 10332 out.print( 10333 Integer.toHexString(System.identityHashCode(filter.provider))); 10334 out.print(' '); 10335 filter.provider.printComponentShortName(out); 10336 out.print(" filter "); 10337 out.println(Integer.toHexString(System.identityHashCode(filter))); 10338 } 10339 10340 @Override 10341 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 10342 return filter.provider; 10343 } 10344 10345 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10346 PackageParser.Provider provider = (PackageParser.Provider)label; 10347 out.print(prefix); out.print( 10348 Integer.toHexString(System.identityHashCode(provider))); 10349 out.print(' '); 10350 provider.printComponentShortName(out); 10351 if (count > 1) { 10352 out.print(" ("); out.print(count); out.print(" filters)"); 10353 } 10354 out.println(); 10355 } 10356 10357 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 10358 = new ArrayMap<ComponentName, PackageParser.Provider>(); 10359 private int mFlags; 10360 } 10361 10362 private static final class EphemeralIntentResolver 10363 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 10364 @Override 10365 protected EphemeralResolveIntentInfo[] newArray(int size) { 10366 return new EphemeralResolveIntentInfo[size]; 10367 } 10368 10369 @Override 10370 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 10371 return true; 10372 } 10373 10374 @Override 10375 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 10376 int userId) { 10377 if (!sUserManager.exists(userId)) { 10378 return null; 10379 } 10380 return info.getEphemeralResolveInfo(); 10381 } 10382 } 10383 10384 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 10385 new Comparator<ResolveInfo>() { 10386 public int compare(ResolveInfo r1, ResolveInfo r2) { 10387 int v1 = r1.priority; 10388 int v2 = r2.priority; 10389 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 10390 if (v1 != v2) { 10391 return (v1 > v2) ? -1 : 1; 10392 } 10393 v1 = r1.preferredOrder; 10394 v2 = r2.preferredOrder; 10395 if (v1 != v2) { 10396 return (v1 > v2) ? -1 : 1; 10397 } 10398 if (r1.isDefault != r2.isDefault) { 10399 return r1.isDefault ? -1 : 1; 10400 } 10401 v1 = r1.match; 10402 v2 = r2.match; 10403 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 10404 if (v1 != v2) { 10405 return (v1 > v2) ? -1 : 1; 10406 } 10407 if (r1.system != r2.system) { 10408 return r1.system ? -1 : 1; 10409 } 10410 if (r1.activityInfo != null) { 10411 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 10412 } 10413 if (r1.serviceInfo != null) { 10414 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 10415 } 10416 if (r1.providerInfo != null) { 10417 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 10418 } 10419 return 0; 10420 } 10421 }; 10422 10423 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 10424 new Comparator<ProviderInfo>() { 10425 public int compare(ProviderInfo p1, ProviderInfo p2) { 10426 final int v1 = p1.initOrder; 10427 final int v2 = p2.initOrder; 10428 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 10429 } 10430 }; 10431 10432 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 10433 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 10434 final int[] userIds) { 10435 mHandler.post(new Runnable() { 10436 @Override 10437 public void run() { 10438 try { 10439 final IActivityManager am = ActivityManagerNative.getDefault(); 10440 if (am == null) return; 10441 final int[] resolvedUserIds; 10442 if (userIds == null) { 10443 resolvedUserIds = am.getRunningUserIds(); 10444 } else { 10445 resolvedUserIds = userIds; 10446 } 10447 for (int id : resolvedUserIds) { 10448 final Intent intent = new Intent(action, 10449 pkg != null ? Uri.fromParts("package", pkg, null) : null); 10450 if (extras != null) { 10451 intent.putExtras(extras); 10452 } 10453 if (targetPkg != null) { 10454 intent.setPackage(targetPkg); 10455 } 10456 // Modify the UID when posting to other users 10457 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 10458 if (uid > 0 && UserHandle.getUserId(uid) != id) { 10459 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 10460 intent.putExtra(Intent.EXTRA_UID, uid); 10461 } 10462 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 10463 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 10464 if (DEBUG_BROADCASTS) { 10465 RuntimeException here = new RuntimeException("here"); 10466 here.fillInStackTrace(); 10467 Slog.d(TAG, "Sending to user " + id + ": " 10468 + intent.toShortString(false, true, false, false) 10469 + " " + intent.getExtras(), here); 10470 } 10471 am.broadcastIntent(null, intent, null, finishedReceiver, 10472 0, null, null, null, android.app.AppOpsManager.OP_NONE, 10473 null, finishedReceiver != null, false, id); 10474 } 10475 } catch (RemoteException ex) { 10476 } 10477 } 10478 }); 10479 } 10480 10481 /** 10482 * Check if the external storage media is available. This is true if there 10483 * is a mounted external storage medium or if the external storage is 10484 * emulated. 10485 */ 10486 private boolean isExternalMediaAvailable() { 10487 return mMediaMounted || Environment.isExternalStorageEmulated(); 10488 } 10489 10490 @Override 10491 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 10492 // writer 10493 synchronized (mPackages) { 10494 if (!isExternalMediaAvailable()) { 10495 // If the external storage is no longer mounted at this point, 10496 // the caller may not have been able to delete all of this 10497 // packages files and can not delete any more. Bail. 10498 return null; 10499 } 10500 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 10501 if (lastPackage != null) { 10502 pkgs.remove(lastPackage); 10503 } 10504 if (pkgs.size() > 0) { 10505 return pkgs.get(0); 10506 } 10507 } 10508 return null; 10509 } 10510 10511 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 10512 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 10513 userId, andCode ? 1 : 0, packageName); 10514 if (mSystemReady) { 10515 msg.sendToTarget(); 10516 } else { 10517 if (mPostSystemReadyMessages == null) { 10518 mPostSystemReadyMessages = new ArrayList<>(); 10519 } 10520 mPostSystemReadyMessages.add(msg); 10521 } 10522 } 10523 10524 void startCleaningPackages() { 10525 // reader 10526 if (!isExternalMediaAvailable()) { 10527 return; 10528 } 10529 synchronized (mPackages) { 10530 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 10531 return; 10532 } 10533 } 10534 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 10535 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 10536 IActivityManager am = ActivityManagerNative.getDefault(); 10537 if (am != null) { 10538 try { 10539 am.startService(null, intent, null, mContext.getOpPackageName(), 10540 UserHandle.USER_SYSTEM); 10541 } catch (RemoteException e) { 10542 } 10543 } 10544 } 10545 10546 @Override 10547 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 10548 int installFlags, String installerPackageName, int userId) { 10549 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 10550 10551 final int callingUid = Binder.getCallingUid(); 10552 enforceCrossUserPermission(callingUid, userId, 10553 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 10554 10555 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10556 try { 10557 if (observer != null) { 10558 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 10559 } 10560 } catch (RemoteException re) { 10561 } 10562 return; 10563 } 10564 10565 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 10566 installFlags |= PackageManager.INSTALL_FROM_ADB; 10567 10568 } else { 10569 // Caller holds INSTALL_PACKAGES permission, so we're less strict 10570 // about installerPackageName. 10571 10572 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 10573 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 10574 } 10575 10576 UserHandle user; 10577 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 10578 user = UserHandle.ALL; 10579 } else { 10580 user = new UserHandle(userId); 10581 } 10582 10583 // Only system components can circumvent runtime permissions when installing. 10584 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 10585 && mContext.checkCallingOrSelfPermission(Manifest.permission 10586 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 10587 throw new SecurityException("You need the " 10588 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 10589 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 10590 } 10591 10592 final File originFile = new File(originPath); 10593 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 10594 10595 final Message msg = mHandler.obtainMessage(INIT_COPY); 10596 final VerificationInfo verificationInfo = new VerificationInfo( 10597 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 10598 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 10599 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 10600 null /*packageAbiOverride*/, null /*grantedPermissions*/); 10601 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 10602 msg.obj = params; 10603 10604 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 10605 System.identityHashCode(msg.obj)); 10606 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10607 System.identityHashCode(msg.obj)); 10608 10609 mHandler.sendMessage(msg); 10610 } 10611 10612 void installStage(String packageName, File stagedDir, String stagedCid, 10613 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 10614 String installerPackageName, int installerUid, UserHandle user) { 10615 if (DEBUG_EPHEMERAL) { 10616 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10617 Slog.d(TAG, "Ephemeral install of " + packageName); 10618 } 10619 } 10620 final VerificationInfo verificationInfo = new VerificationInfo( 10621 sessionParams.originatingUri, sessionParams.referrerUri, 10622 sessionParams.originatingUid, installerUid); 10623 10624 final OriginInfo origin; 10625 if (stagedDir != null) { 10626 origin = OriginInfo.fromStagedFile(stagedDir); 10627 } else { 10628 origin = OriginInfo.fromStagedContainer(stagedCid); 10629 } 10630 10631 final Message msg = mHandler.obtainMessage(INIT_COPY); 10632 final InstallParams params = new InstallParams(origin, null, observer, 10633 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 10634 verificationInfo, user, sessionParams.abiOverride, 10635 sessionParams.grantedRuntimePermissions); 10636 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 10637 msg.obj = params; 10638 10639 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 10640 System.identityHashCode(msg.obj)); 10641 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10642 System.identityHashCode(msg.obj)); 10643 10644 mHandler.sendMessage(msg); 10645 } 10646 10647 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 10648 int userId) { 10649 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 10650 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 10651 } 10652 10653 private void sendPackageAddedForUser(String packageName, boolean isSystem, 10654 int appId, int userId) { 10655 Bundle extras = new Bundle(1); 10656 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 10657 10658 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 10659 packageName, extras, 0, null, null, new int[] {userId}); 10660 try { 10661 IActivityManager am = ActivityManagerNative.getDefault(); 10662 if (isSystem && am.isUserRunning(userId, 0)) { 10663 // The just-installed/enabled app is bundled on the system, so presumed 10664 // to be able to run automatically without needing an explicit launch. 10665 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 10666 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 10667 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 10668 .setPackage(packageName); 10669 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 10670 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 10671 } 10672 } catch (RemoteException e) { 10673 // shouldn't happen 10674 Slog.w(TAG, "Unable to bootstrap installed package", e); 10675 } 10676 } 10677 10678 @Override 10679 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 10680 int userId) { 10681 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10682 PackageSetting pkgSetting; 10683 final int uid = Binder.getCallingUid(); 10684 enforceCrossUserPermission(uid, userId, 10685 true /* requireFullPermission */, true /* checkShell */, 10686 "setApplicationHiddenSetting for user " + userId); 10687 10688 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 10689 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 10690 return false; 10691 } 10692 10693 long callingId = Binder.clearCallingIdentity(); 10694 try { 10695 boolean sendAdded = false; 10696 boolean sendRemoved = false; 10697 // writer 10698 synchronized (mPackages) { 10699 pkgSetting = mSettings.mPackages.get(packageName); 10700 if (pkgSetting == null) { 10701 return false; 10702 } 10703 if (pkgSetting.getHidden(userId) != hidden) { 10704 pkgSetting.setHidden(hidden, userId); 10705 mSettings.writePackageRestrictionsLPr(userId); 10706 if (hidden) { 10707 sendRemoved = true; 10708 } else { 10709 sendAdded = true; 10710 } 10711 } 10712 } 10713 if (sendAdded) { 10714 sendPackageAddedForUser(packageName, pkgSetting, userId); 10715 return true; 10716 } 10717 if (sendRemoved) { 10718 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 10719 "hiding pkg"); 10720 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 10721 return true; 10722 } 10723 } finally { 10724 Binder.restoreCallingIdentity(callingId); 10725 } 10726 return false; 10727 } 10728 10729 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 10730 int userId) { 10731 final PackageRemovedInfo info = new PackageRemovedInfo(); 10732 info.removedPackage = packageName; 10733 info.removedUsers = new int[] {userId}; 10734 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 10735 info.sendPackageRemovedBroadcasts(true /*killApp*/); 10736 } 10737 10738 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 10739 if (pkgList.length > 0) { 10740 Bundle extras = new Bundle(1); 10741 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 10742 10743 sendPackageBroadcast( 10744 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 10745 : Intent.ACTION_PACKAGES_UNSUSPENDED, 10746 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 10747 new int[] {userId}); 10748 } 10749 } 10750 10751 /** 10752 * Returns true if application is not found or there was an error. Otherwise it returns 10753 * the hidden state of the package for the given user. 10754 */ 10755 @Override 10756 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 10757 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10758 enforceCrossUserPermission(Binder.getCallingUid(), userId, 10759 true /* requireFullPermission */, false /* checkShell */, 10760 "getApplicationHidden for user " + userId); 10761 PackageSetting pkgSetting; 10762 long callingId = Binder.clearCallingIdentity(); 10763 try { 10764 // writer 10765 synchronized (mPackages) { 10766 pkgSetting = mSettings.mPackages.get(packageName); 10767 if (pkgSetting == null) { 10768 return true; 10769 } 10770 return pkgSetting.getHidden(userId); 10771 } 10772 } finally { 10773 Binder.restoreCallingIdentity(callingId); 10774 } 10775 } 10776 10777 /** 10778 * @hide 10779 */ 10780 @Override 10781 public int installExistingPackageAsUser(String packageName, int userId) { 10782 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 10783 null); 10784 PackageSetting pkgSetting; 10785 final int uid = Binder.getCallingUid(); 10786 enforceCrossUserPermission(uid, userId, 10787 true /* requireFullPermission */, true /* checkShell */, 10788 "installExistingPackage for user " + userId); 10789 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10790 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 10791 } 10792 10793 long callingId = Binder.clearCallingIdentity(); 10794 try { 10795 boolean installed = false; 10796 10797 // writer 10798 synchronized (mPackages) { 10799 pkgSetting = mSettings.mPackages.get(packageName); 10800 if (pkgSetting == null) { 10801 return PackageManager.INSTALL_FAILED_INVALID_URI; 10802 } 10803 if (!pkgSetting.getInstalled(userId)) { 10804 pkgSetting.setInstalled(true, userId); 10805 pkgSetting.setHidden(false, userId); 10806 mSettings.writePackageRestrictionsLPr(userId); 10807 installed = true; 10808 } 10809 } 10810 10811 if (installed) { 10812 if (pkgSetting.pkg != null) { 10813 prepareAppDataAfterInstall(pkgSetting.pkg); 10814 } 10815 sendPackageAddedForUser(packageName, pkgSetting, userId); 10816 } 10817 } finally { 10818 Binder.restoreCallingIdentity(callingId); 10819 } 10820 10821 return PackageManager.INSTALL_SUCCEEDED; 10822 } 10823 10824 boolean isUserRestricted(int userId, String restrictionKey) { 10825 Bundle restrictions = sUserManager.getUserRestrictions(userId); 10826 if (restrictions.getBoolean(restrictionKey, false)) { 10827 Log.w(TAG, "User is restricted: " + restrictionKey); 10828 return true; 10829 } 10830 return false; 10831 } 10832 10833 @Override 10834 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 10835 int userId) { 10836 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10837 enforceCrossUserPermission(Binder.getCallingUid(), userId, 10838 true /* requireFullPermission */, true /* checkShell */, 10839 "setPackagesSuspended for user " + userId); 10840 10841 if (ArrayUtils.isEmpty(packageNames)) { 10842 return packageNames; 10843 } 10844 10845 // List of package names for whom the suspended state has changed. 10846 List<String> changedPackages = new ArrayList<>(packageNames.length); 10847 // List of package names for whom the suspended state is not set as requested in this 10848 // method. 10849 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 10850 for (int i = 0; i < packageNames.length; i++) { 10851 String packageName = packageNames[i]; 10852 long callingId = Binder.clearCallingIdentity(); 10853 try { 10854 boolean changed = false; 10855 final int appId; 10856 synchronized (mPackages) { 10857 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10858 if (pkgSetting == null) { 10859 Slog.w(TAG, "Could not find package setting for package \"" + packageName 10860 + "\". Skipping suspending/un-suspending."); 10861 unactionedPackages.add(packageName); 10862 continue; 10863 } 10864 appId = pkgSetting.appId; 10865 if (pkgSetting.getSuspended(userId) != suspended) { 10866 if (!canSuspendPackageForUserLocked(packageName, userId)) { 10867 unactionedPackages.add(packageName); 10868 continue; 10869 } 10870 pkgSetting.setSuspended(suspended, userId); 10871 mSettings.writePackageRestrictionsLPr(userId); 10872 changed = true; 10873 changedPackages.add(packageName); 10874 } 10875 } 10876 10877 if (changed && suspended) { 10878 killApplication(packageName, UserHandle.getUid(userId, appId), 10879 "suspending package"); 10880 } 10881 } finally { 10882 Binder.restoreCallingIdentity(callingId); 10883 } 10884 } 10885 10886 if (!changedPackages.isEmpty()) { 10887 sendPackagesSuspendedForUser(changedPackages.toArray( 10888 new String[changedPackages.size()]), userId, suspended); 10889 } 10890 10891 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 10892 } 10893 10894 @Override 10895 public boolean isPackageSuspendedForUser(String packageName, int userId) { 10896 enforceCrossUserPermission(Binder.getCallingUid(), userId, 10897 true /* requireFullPermission */, false /* checkShell */, 10898 "isPackageSuspendedForUser for user " + userId); 10899 synchronized (mPackages) { 10900 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10901 return pkgSetting != null && pkgSetting.getSuspended(userId); 10902 } 10903 } 10904 10905 /** 10906 * TODO: cache and disallow blocking the active dialer. 10907 * 10908 * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions 10909 */ 10910 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 10911 if (isPackageDeviceAdmin(packageName, userId)) { 10912 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 10913 + "\": has an active device admin"); 10914 return false; 10915 } 10916 10917 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 10918 if (packageName.equals(activeLauncherPackageName)) { 10919 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 10920 + "\": contains the active launcher"); 10921 return false; 10922 } 10923 10924 if (packageName.equals(mRequiredInstallerPackage)) { 10925 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 10926 + "\": required for package installation"); 10927 return false; 10928 } 10929 10930 if (packageName.equals(mRequiredVerifierPackage)) { 10931 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 10932 + "\": required for package verification"); 10933 return false; 10934 } 10935 10936 final PackageParser.Package pkg = mPackages.get(packageName); 10937 if (pkg != null && isPrivilegedApp(pkg)) { 10938 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 10939 + "\": is a privileged app"); 10940 return false; 10941 } 10942 10943 return true; 10944 } 10945 10946 private String getActiveLauncherPackageName(int userId) { 10947 Intent intent = new Intent(Intent.ACTION_MAIN); 10948 intent.addCategory(Intent.CATEGORY_HOME); 10949 ResolveInfo resolveInfo = resolveIntent( 10950 intent, 10951 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 10952 PackageManager.MATCH_DEFAULT_ONLY, 10953 userId); 10954 10955 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 10956 } 10957 10958 @Override 10959 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 10960 mContext.enforceCallingOrSelfPermission( 10961 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10962 "Only package verification agents can verify applications"); 10963 10964 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10965 final PackageVerificationResponse response = new PackageVerificationResponse( 10966 verificationCode, Binder.getCallingUid()); 10967 msg.arg1 = id; 10968 msg.obj = response; 10969 mHandler.sendMessage(msg); 10970 } 10971 10972 @Override 10973 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 10974 long millisecondsToDelay) { 10975 mContext.enforceCallingOrSelfPermission( 10976 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10977 "Only package verification agents can extend verification timeouts"); 10978 10979 final PackageVerificationState state = mPendingVerification.get(id); 10980 final PackageVerificationResponse response = new PackageVerificationResponse( 10981 verificationCodeAtTimeout, Binder.getCallingUid()); 10982 10983 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 10984 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 10985 } 10986 if (millisecondsToDelay < 0) { 10987 millisecondsToDelay = 0; 10988 } 10989 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 10990 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 10991 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 10992 } 10993 10994 if ((state != null) && !state.timeoutExtended()) { 10995 state.extendTimeout(); 10996 10997 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10998 msg.arg1 = id; 10999 msg.obj = response; 11000 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11001 } 11002 } 11003 11004 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11005 int verificationCode, UserHandle user) { 11006 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11007 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11008 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11009 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11010 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11011 11012 mContext.sendBroadcastAsUser(intent, user, 11013 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11014 } 11015 11016 private ComponentName matchComponentForVerifier(String packageName, 11017 List<ResolveInfo> receivers) { 11018 ActivityInfo targetReceiver = null; 11019 11020 final int NR = receivers.size(); 11021 for (int i = 0; i < NR; i++) { 11022 final ResolveInfo info = receivers.get(i); 11023 if (info.activityInfo == null) { 11024 continue; 11025 } 11026 11027 if (packageName.equals(info.activityInfo.packageName)) { 11028 targetReceiver = info.activityInfo; 11029 break; 11030 } 11031 } 11032 11033 if (targetReceiver == null) { 11034 return null; 11035 } 11036 11037 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11038 } 11039 11040 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11041 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11042 if (pkgInfo.verifiers.length == 0) { 11043 return null; 11044 } 11045 11046 final int N = pkgInfo.verifiers.length; 11047 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11048 for (int i = 0; i < N; i++) { 11049 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11050 11051 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11052 receivers); 11053 if (comp == null) { 11054 continue; 11055 } 11056 11057 final int verifierUid = getUidForVerifier(verifierInfo); 11058 if (verifierUid == -1) { 11059 continue; 11060 } 11061 11062 if (DEBUG_VERIFY) { 11063 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11064 + " with the correct signature"); 11065 } 11066 sufficientVerifiers.add(comp); 11067 verificationState.addSufficientVerifier(verifierUid); 11068 } 11069 11070 return sufficientVerifiers; 11071 } 11072 11073 private int getUidForVerifier(VerifierInfo verifierInfo) { 11074 synchronized (mPackages) { 11075 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11076 if (pkg == null) { 11077 return -1; 11078 } else if (pkg.mSignatures.length != 1) { 11079 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11080 + " has more than one signature; ignoring"); 11081 return -1; 11082 } 11083 11084 /* 11085 * If the public key of the package's signature does not match 11086 * our expected public key, then this is a different package and 11087 * we should skip. 11088 */ 11089 11090 final byte[] expectedPublicKey; 11091 try { 11092 final Signature verifierSig = pkg.mSignatures[0]; 11093 final PublicKey publicKey = verifierSig.getPublicKey(); 11094 expectedPublicKey = publicKey.getEncoded(); 11095 } catch (CertificateException e) { 11096 return -1; 11097 } 11098 11099 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11100 11101 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11102 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11103 + " does not have the expected public key; ignoring"); 11104 return -1; 11105 } 11106 11107 return pkg.applicationInfo.uid; 11108 } 11109 } 11110 11111 @Override 11112 public void finishPackageInstall(int token) { 11113 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11114 11115 if (DEBUG_INSTALL) { 11116 Slog.v(TAG, "BM finishing package install for " + token); 11117 } 11118 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11119 11120 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11121 mHandler.sendMessage(msg); 11122 } 11123 11124 /** 11125 * Get the verification agent timeout. 11126 * 11127 * @return verification timeout in milliseconds 11128 */ 11129 private long getVerificationTimeout() { 11130 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11131 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11132 DEFAULT_VERIFICATION_TIMEOUT); 11133 } 11134 11135 /** 11136 * Get the default verification agent response code. 11137 * 11138 * @return default verification response code 11139 */ 11140 private int getDefaultVerificationResponse() { 11141 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11142 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11143 DEFAULT_VERIFICATION_RESPONSE); 11144 } 11145 11146 /** 11147 * Check whether or not package verification has been enabled. 11148 * 11149 * @return true if verification should be performed 11150 */ 11151 private boolean isVerificationEnabled(int userId, int installFlags) { 11152 if (!DEFAULT_VERIFY_ENABLE) { 11153 return false; 11154 } 11155 // Ephemeral apps don't get the full verification treatment 11156 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11157 if (DEBUG_EPHEMERAL) { 11158 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11159 } 11160 return false; 11161 } 11162 11163 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11164 11165 // Check if installing from ADB 11166 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11167 // Do not run verification in a test harness environment 11168 if (ActivityManager.isRunningInTestHarness()) { 11169 return false; 11170 } 11171 if (ensureVerifyAppsEnabled) { 11172 return true; 11173 } 11174 // Check if the developer does not want package verification for ADB installs 11175 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11176 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11177 return false; 11178 } 11179 } 11180 11181 if (ensureVerifyAppsEnabled) { 11182 return true; 11183 } 11184 11185 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11186 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11187 } 11188 11189 @Override 11190 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11191 throws RemoteException { 11192 mContext.enforceCallingOrSelfPermission( 11193 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11194 "Only intentfilter verification agents can verify applications"); 11195 11196 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11197 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11198 Binder.getCallingUid(), verificationCode, failedDomains); 11199 msg.arg1 = id; 11200 msg.obj = response; 11201 mHandler.sendMessage(msg); 11202 } 11203 11204 @Override 11205 public int getIntentVerificationStatus(String packageName, int userId) { 11206 synchronized (mPackages) { 11207 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11208 } 11209 } 11210 11211 @Override 11212 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11213 mContext.enforceCallingOrSelfPermission( 11214 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11215 11216 boolean result = false; 11217 synchronized (mPackages) { 11218 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11219 } 11220 if (result) { 11221 scheduleWritePackageRestrictionsLocked(userId); 11222 } 11223 return result; 11224 } 11225 11226 @Override 11227 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11228 String packageName) { 11229 synchronized (mPackages) { 11230 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11231 } 11232 } 11233 11234 @Override 11235 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11236 if (TextUtils.isEmpty(packageName)) { 11237 return ParceledListSlice.emptyList(); 11238 } 11239 synchronized (mPackages) { 11240 PackageParser.Package pkg = mPackages.get(packageName); 11241 if (pkg == null || pkg.activities == null) { 11242 return ParceledListSlice.emptyList(); 11243 } 11244 final int count = pkg.activities.size(); 11245 ArrayList<IntentFilter> result = new ArrayList<>(); 11246 for (int n=0; n<count; n++) { 11247 PackageParser.Activity activity = pkg.activities.get(n); 11248 if (activity.intents != null && activity.intents.size() > 0) { 11249 result.addAll(activity.intents); 11250 } 11251 } 11252 return new ParceledListSlice<>(result); 11253 } 11254 } 11255 11256 @Override 11257 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11258 mContext.enforceCallingOrSelfPermission( 11259 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11260 11261 synchronized (mPackages) { 11262 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11263 if (packageName != null) { 11264 result |= updateIntentVerificationStatus(packageName, 11265 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11266 userId); 11267 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11268 packageName, userId); 11269 } 11270 return result; 11271 } 11272 } 11273 11274 @Override 11275 public String getDefaultBrowserPackageName(int userId) { 11276 synchronized (mPackages) { 11277 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11278 } 11279 } 11280 11281 /** 11282 * Get the "allow unknown sources" setting. 11283 * 11284 * @return the current "allow unknown sources" setting 11285 */ 11286 private int getUnknownSourcesSettings() { 11287 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11288 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 11289 -1); 11290 } 11291 11292 @Override 11293 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11294 final int uid = Binder.getCallingUid(); 11295 // writer 11296 synchronized (mPackages) { 11297 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11298 if (targetPackageSetting == null) { 11299 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11300 } 11301 11302 PackageSetting installerPackageSetting; 11303 if (installerPackageName != null) { 11304 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11305 if (installerPackageSetting == null) { 11306 throw new IllegalArgumentException("Unknown installer package: " 11307 + installerPackageName); 11308 } 11309 } else { 11310 installerPackageSetting = null; 11311 } 11312 11313 Signature[] callerSignature; 11314 Object obj = mSettings.getUserIdLPr(uid); 11315 if (obj != null) { 11316 if (obj instanceof SharedUserSetting) { 11317 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11318 } else if (obj instanceof PackageSetting) { 11319 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11320 } else { 11321 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11322 } 11323 } else { 11324 throw new SecurityException("Unknown calling UID: " + uid); 11325 } 11326 11327 // Verify: can't set installerPackageName to a package that is 11328 // not signed with the same cert as the caller. 11329 if (installerPackageSetting != null) { 11330 if (compareSignatures(callerSignature, 11331 installerPackageSetting.signatures.mSignatures) 11332 != PackageManager.SIGNATURE_MATCH) { 11333 throw new SecurityException( 11334 "Caller does not have same cert as new installer package " 11335 + installerPackageName); 11336 } 11337 } 11338 11339 // Verify: if target already has an installer package, it must 11340 // be signed with the same cert as the caller. 11341 if (targetPackageSetting.installerPackageName != null) { 11342 PackageSetting setting = mSettings.mPackages.get( 11343 targetPackageSetting.installerPackageName); 11344 // If the currently set package isn't valid, then it's always 11345 // okay to change it. 11346 if (setting != null) { 11347 if (compareSignatures(callerSignature, 11348 setting.signatures.mSignatures) 11349 != PackageManager.SIGNATURE_MATCH) { 11350 throw new SecurityException( 11351 "Caller does not have same cert as old installer package " 11352 + targetPackageSetting.installerPackageName); 11353 } 11354 } 11355 } 11356 11357 // Okay! 11358 targetPackageSetting.installerPackageName = installerPackageName; 11359 scheduleWriteSettingsLocked(); 11360 } 11361 } 11362 11363 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 11364 // Queue up an async operation since the package installation may take a little while. 11365 mHandler.post(new Runnable() { 11366 public void run() { 11367 mHandler.removeCallbacks(this); 11368 // Result object to be returned 11369 PackageInstalledInfo res = new PackageInstalledInfo(); 11370 res.setReturnCode(currentStatus); 11371 res.uid = -1; 11372 res.pkg = null; 11373 res.removedInfo = null; 11374 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11375 args.doPreInstall(res.returnCode); 11376 synchronized (mInstallLock) { 11377 installPackageTracedLI(args, res); 11378 } 11379 args.doPostInstall(res.returnCode, res.uid); 11380 } 11381 11382 // A restore should be performed at this point if (a) the install 11383 // succeeded, (b) the operation is not an update, and (c) the new 11384 // package has not opted out of backup participation. 11385 final boolean update = res.removedInfo != null 11386 && res.removedInfo.removedPackage != null; 11387 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 11388 boolean doRestore = !update 11389 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 11390 11391 // Set up the post-install work request bookkeeping. This will be used 11392 // and cleaned up by the post-install event handling regardless of whether 11393 // there's a restore pass performed. Token values are >= 1. 11394 int token; 11395 if (mNextInstallToken < 0) mNextInstallToken = 1; 11396 token = mNextInstallToken++; 11397 11398 PostInstallData data = new PostInstallData(args, res); 11399 mRunningInstalls.put(token, data); 11400 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 11401 11402 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 11403 // Pass responsibility to the Backup Manager. It will perform a 11404 // restore if appropriate, then pass responsibility back to the 11405 // Package Manager to run the post-install observer callbacks 11406 // and broadcasts. 11407 IBackupManager bm = IBackupManager.Stub.asInterface( 11408 ServiceManager.getService(Context.BACKUP_SERVICE)); 11409 if (bm != null) { 11410 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 11411 + " to BM for possible restore"); 11412 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11413 try { 11414 // TODO: http://b/22388012 11415 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 11416 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 11417 } else { 11418 doRestore = false; 11419 } 11420 } catch (RemoteException e) { 11421 // can't happen; the backup manager is local 11422 } catch (Exception e) { 11423 Slog.e(TAG, "Exception trying to enqueue restore", e); 11424 doRestore = false; 11425 } 11426 } else { 11427 Slog.e(TAG, "Backup Manager not found!"); 11428 doRestore = false; 11429 } 11430 } 11431 11432 if (!doRestore) { 11433 // No restore possible, or the Backup Manager was mysteriously not 11434 // available -- just fire the post-install work request directly. 11435 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 11436 11437 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 11438 11439 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11440 mHandler.sendMessage(msg); 11441 } 11442 } 11443 }); 11444 } 11445 11446 private abstract class HandlerParams { 11447 private static final int MAX_RETRIES = 4; 11448 11449 /** 11450 * Number of times startCopy() has been attempted and had a non-fatal 11451 * error. 11452 */ 11453 private int mRetries = 0; 11454 11455 /** User handle for the user requesting the information or installation. */ 11456 private final UserHandle mUser; 11457 String traceMethod; 11458 int traceCookie; 11459 11460 HandlerParams(UserHandle user) { 11461 mUser = user; 11462 } 11463 11464 UserHandle getUser() { 11465 return mUser; 11466 } 11467 11468 HandlerParams setTraceMethod(String traceMethod) { 11469 this.traceMethod = traceMethod; 11470 return this; 11471 } 11472 11473 HandlerParams setTraceCookie(int traceCookie) { 11474 this.traceCookie = traceCookie; 11475 return this; 11476 } 11477 11478 final boolean startCopy() { 11479 boolean res; 11480 try { 11481 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 11482 11483 if (++mRetries > MAX_RETRIES) { 11484 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 11485 mHandler.sendEmptyMessage(MCS_GIVE_UP); 11486 handleServiceError(); 11487 return false; 11488 } else { 11489 handleStartCopy(); 11490 res = true; 11491 } 11492 } catch (RemoteException e) { 11493 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 11494 mHandler.sendEmptyMessage(MCS_RECONNECT); 11495 res = false; 11496 } 11497 handleReturnCode(); 11498 return res; 11499 } 11500 11501 final void serviceError() { 11502 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 11503 handleServiceError(); 11504 handleReturnCode(); 11505 } 11506 11507 abstract void handleStartCopy() throws RemoteException; 11508 abstract void handleServiceError(); 11509 abstract void handleReturnCode(); 11510 } 11511 11512 class MeasureParams extends HandlerParams { 11513 private final PackageStats mStats; 11514 private boolean mSuccess; 11515 11516 private final IPackageStatsObserver mObserver; 11517 11518 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 11519 super(new UserHandle(stats.userHandle)); 11520 mObserver = observer; 11521 mStats = stats; 11522 } 11523 11524 @Override 11525 public String toString() { 11526 return "MeasureParams{" 11527 + Integer.toHexString(System.identityHashCode(this)) 11528 + " " + mStats.packageName + "}"; 11529 } 11530 11531 @Override 11532 void handleStartCopy() throws RemoteException { 11533 synchronized (mInstallLock) { 11534 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 11535 } 11536 11537 if (mSuccess) { 11538 final boolean mounted; 11539 if (Environment.isExternalStorageEmulated()) { 11540 mounted = true; 11541 } else { 11542 final String status = Environment.getExternalStorageState(); 11543 mounted = (Environment.MEDIA_MOUNTED.equals(status) 11544 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 11545 } 11546 11547 if (mounted) { 11548 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 11549 11550 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 11551 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 11552 11553 mStats.externalDataSize = calculateDirectorySize(mContainerService, 11554 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 11555 11556 // Always subtract cache size, since it's a subdirectory 11557 mStats.externalDataSize -= mStats.externalCacheSize; 11558 11559 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 11560 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 11561 11562 mStats.externalObbSize = calculateDirectorySize(mContainerService, 11563 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 11564 } 11565 } 11566 } 11567 11568 @Override 11569 void handleReturnCode() { 11570 if (mObserver != null) { 11571 try { 11572 mObserver.onGetStatsCompleted(mStats, mSuccess); 11573 } catch (RemoteException e) { 11574 Slog.i(TAG, "Observer no longer exists."); 11575 } 11576 } 11577 } 11578 11579 @Override 11580 void handleServiceError() { 11581 Slog.e(TAG, "Could not measure application " + mStats.packageName 11582 + " external storage"); 11583 } 11584 } 11585 11586 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 11587 throws RemoteException { 11588 long result = 0; 11589 for (File path : paths) { 11590 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 11591 } 11592 return result; 11593 } 11594 11595 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 11596 for (File path : paths) { 11597 try { 11598 mcs.clearDirectory(path.getAbsolutePath()); 11599 } catch (RemoteException e) { 11600 } 11601 } 11602 } 11603 11604 static class OriginInfo { 11605 /** 11606 * Location where install is coming from, before it has been 11607 * copied/renamed into place. This could be a single monolithic APK 11608 * file, or a cluster directory. This location may be untrusted. 11609 */ 11610 final File file; 11611 final String cid; 11612 11613 /** 11614 * Flag indicating that {@link #file} or {@link #cid} has already been 11615 * staged, meaning downstream users don't need to defensively copy the 11616 * contents. 11617 */ 11618 final boolean staged; 11619 11620 /** 11621 * Flag indicating that {@link #file} or {@link #cid} is an already 11622 * installed app that is being moved. 11623 */ 11624 final boolean existing; 11625 11626 final String resolvedPath; 11627 final File resolvedFile; 11628 11629 static OriginInfo fromNothing() { 11630 return new OriginInfo(null, null, false, false); 11631 } 11632 11633 static OriginInfo fromUntrustedFile(File file) { 11634 return new OriginInfo(file, null, false, false); 11635 } 11636 11637 static OriginInfo fromExistingFile(File file) { 11638 return new OriginInfo(file, null, false, true); 11639 } 11640 11641 static OriginInfo fromStagedFile(File file) { 11642 return new OriginInfo(file, null, true, false); 11643 } 11644 11645 static OriginInfo fromStagedContainer(String cid) { 11646 return new OriginInfo(null, cid, true, false); 11647 } 11648 11649 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 11650 this.file = file; 11651 this.cid = cid; 11652 this.staged = staged; 11653 this.existing = existing; 11654 11655 if (cid != null) { 11656 resolvedPath = PackageHelper.getSdDir(cid); 11657 resolvedFile = new File(resolvedPath); 11658 } else if (file != null) { 11659 resolvedPath = file.getAbsolutePath(); 11660 resolvedFile = file; 11661 } else { 11662 resolvedPath = null; 11663 resolvedFile = null; 11664 } 11665 } 11666 } 11667 11668 static class MoveInfo { 11669 final int moveId; 11670 final String fromUuid; 11671 final String toUuid; 11672 final String packageName; 11673 final String dataAppName; 11674 final int appId; 11675 final String seinfo; 11676 final int targetSdkVersion; 11677 11678 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 11679 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 11680 this.moveId = moveId; 11681 this.fromUuid = fromUuid; 11682 this.toUuid = toUuid; 11683 this.packageName = packageName; 11684 this.dataAppName = dataAppName; 11685 this.appId = appId; 11686 this.seinfo = seinfo; 11687 this.targetSdkVersion = targetSdkVersion; 11688 } 11689 } 11690 11691 static class VerificationInfo { 11692 /** A constant used to indicate that a uid value is not present. */ 11693 public static final int NO_UID = -1; 11694 11695 /** URI referencing where the package was downloaded from. */ 11696 final Uri originatingUri; 11697 11698 /** HTTP referrer URI associated with the originatingURI. */ 11699 final Uri referrer; 11700 11701 /** UID of the application that the install request originated from. */ 11702 final int originatingUid; 11703 11704 /** UID of application requesting the install */ 11705 final int installerUid; 11706 11707 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 11708 this.originatingUri = originatingUri; 11709 this.referrer = referrer; 11710 this.originatingUid = originatingUid; 11711 this.installerUid = installerUid; 11712 } 11713 } 11714 11715 class InstallParams extends HandlerParams { 11716 final OriginInfo origin; 11717 final MoveInfo move; 11718 final IPackageInstallObserver2 observer; 11719 int installFlags; 11720 final String installerPackageName; 11721 final String volumeUuid; 11722 private InstallArgs mArgs; 11723 private int mRet; 11724 final String packageAbiOverride; 11725 final String[] grantedRuntimePermissions; 11726 final VerificationInfo verificationInfo; 11727 11728 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11729 int installFlags, String installerPackageName, String volumeUuid, 11730 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 11731 String[] grantedPermissions) { 11732 super(user); 11733 this.origin = origin; 11734 this.move = move; 11735 this.observer = observer; 11736 this.installFlags = installFlags; 11737 this.installerPackageName = installerPackageName; 11738 this.volumeUuid = volumeUuid; 11739 this.verificationInfo = verificationInfo; 11740 this.packageAbiOverride = packageAbiOverride; 11741 this.grantedRuntimePermissions = grantedPermissions; 11742 } 11743 11744 @Override 11745 public String toString() { 11746 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 11747 + " file=" + origin.file + " cid=" + origin.cid + "}"; 11748 } 11749 11750 private int installLocationPolicy(PackageInfoLite pkgLite) { 11751 String packageName = pkgLite.packageName; 11752 int installLocation = pkgLite.installLocation; 11753 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11754 // reader 11755 synchronized (mPackages) { 11756 // Currently installed package which the new package is attempting to replace or 11757 // null if no such package is installed. 11758 PackageParser.Package installedPkg = mPackages.get(packageName); 11759 // Package which currently owns the data which the new package will own if installed. 11760 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 11761 // will be null whereas dataOwnerPkg will contain information about the package 11762 // which was uninstalled while keeping its data. 11763 PackageParser.Package dataOwnerPkg = installedPkg; 11764 if (dataOwnerPkg == null) { 11765 PackageSetting ps = mSettings.mPackages.get(packageName); 11766 if (ps != null) { 11767 dataOwnerPkg = ps.pkg; 11768 } 11769 } 11770 11771 if (dataOwnerPkg != null) { 11772 // If installed, the package will get access to data left on the device by its 11773 // predecessor. As a security measure, this is permited only if this is not a 11774 // version downgrade or if the predecessor package is marked as debuggable and 11775 // a downgrade is explicitly requested. 11776 if (((dataOwnerPkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) 11777 || ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0)) { 11778 try { 11779 checkDowngrade(dataOwnerPkg, pkgLite); 11780 } catch (PackageManagerException e) { 11781 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 11782 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 11783 } 11784 } 11785 } 11786 11787 if (installedPkg != null) { 11788 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11789 // Check for updated system application. 11790 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11791 if (onSd) { 11792 Slog.w(TAG, "Cannot install update to system app on sdcard"); 11793 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 11794 } 11795 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11796 } else { 11797 if (onSd) { 11798 // Install flag overrides everything. 11799 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11800 } 11801 // If current upgrade specifies particular preference 11802 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 11803 // Application explicitly specified internal. 11804 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11805 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 11806 // App explictly prefers external. Let policy decide 11807 } else { 11808 // Prefer previous location 11809 if (isExternal(installedPkg)) { 11810 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11811 } 11812 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11813 } 11814 } 11815 } else { 11816 // Invalid install. Return error code 11817 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 11818 } 11819 } 11820 } 11821 // All the special cases have been taken care of. 11822 // Return result based on recommended install location. 11823 if (onSd) { 11824 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11825 } 11826 return pkgLite.recommendedInstallLocation; 11827 } 11828 11829 /* 11830 * Invoke remote method to get package information and install 11831 * location values. Override install location based on default 11832 * policy if needed and then create install arguments based 11833 * on the install location. 11834 */ 11835 public void handleStartCopy() throws RemoteException { 11836 int ret = PackageManager.INSTALL_SUCCEEDED; 11837 11838 // If we're already staged, we've firmly committed to an install location 11839 if (origin.staged) { 11840 if (origin.file != null) { 11841 installFlags |= PackageManager.INSTALL_INTERNAL; 11842 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11843 } else if (origin.cid != null) { 11844 installFlags |= PackageManager.INSTALL_EXTERNAL; 11845 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11846 } else { 11847 throw new IllegalStateException("Invalid stage location"); 11848 } 11849 } 11850 11851 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11852 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 11853 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11854 PackageInfoLite pkgLite = null; 11855 11856 if (onInt && onSd) { 11857 // Check if both bits are set. 11858 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 11859 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11860 } else if (onSd && ephemeral) { 11861 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 11862 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11863 } else { 11864 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 11865 packageAbiOverride); 11866 11867 if (DEBUG_EPHEMERAL && ephemeral) { 11868 Slog.v(TAG, "pkgLite for install: " + pkgLite); 11869 } 11870 11871 /* 11872 * If we have too little free space, try to free cache 11873 * before giving up. 11874 */ 11875 if (!origin.staged && pkgLite.recommendedInstallLocation 11876 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11877 // TODO: focus freeing disk space on the target device 11878 final StorageManager storage = StorageManager.from(mContext); 11879 final long lowThreshold = storage.getStorageLowBytes( 11880 Environment.getDataDirectory()); 11881 11882 final long sizeBytes = mContainerService.calculateInstalledSize( 11883 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 11884 11885 try { 11886 mInstaller.freeCache(null, sizeBytes + lowThreshold); 11887 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 11888 installFlags, packageAbiOverride); 11889 } catch (InstallerException e) { 11890 Slog.w(TAG, "Failed to free cache", e); 11891 } 11892 11893 /* 11894 * The cache free must have deleted the file we 11895 * downloaded to install. 11896 * 11897 * TODO: fix the "freeCache" call to not delete 11898 * the file we care about. 11899 */ 11900 if (pkgLite.recommendedInstallLocation 11901 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11902 pkgLite.recommendedInstallLocation 11903 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 11904 } 11905 } 11906 } 11907 11908 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11909 int loc = pkgLite.recommendedInstallLocation; 11910 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 11911 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11912 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 11913 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 11914 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11915 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11916 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 11917 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 11918 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11919 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 11920 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 11921 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 11922 } else { 11923 // Override with defaults if needed. 11924 loc = installLocationPolicy(pkgLite); 11925 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 11926 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 11927 } else if (!onSd && !onInt) { 11928 // Override install location with flags 11929 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 11930 // Set the flag to install on external media. 11931 installFlags |= PackageManager.INSTALL_EXTERNAL; 11932 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11933 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 11934 if (DEBUG_EPHEMERAL) { 11935 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 11936 } 11937 installFlags |= PackageManager.INSTALL_EPHEMERAL; 11938 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 11939 |PackageManager.INSTALL_INTERNAL); 11940 } else { 11941 // Make sure the flag for installing on external 11942 // media is unset 11943 installFlags |= PackageManager.INSTALL_INTERNAL; 11944 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11945 } 11946 } 11947 } 11948 } 11949 11950 final InstallArgs args = createInstallArgs(this); 11951 mArgs = args; 11952 11953 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11954 // TODO: http://b/22976637 11955 // Apps installed for "all" users use the device owner to verify the app 11956 UserHandle verifierUser = getUser(); 11957 if (verifierUser == UserHandle.ALL) { 11958 verifierUser = UserHandle.SYSTEM; 11959 } 11960 11961 /* 11962 * Determine if we have any installed package verifiers. If we 11963 * do, then we'll defer to them to verify the packages. 11964 */ 11965 final int requiredUid = mRequiredVerifierPackage == null ? -1 11966 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 11967 verifierUser.getIdentifier()); 11968 if (!origin.existing && requiredUid != -1 11969 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 11970 final Intent verification = new Intent( 11971 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 11972 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 11973 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 11974 PACKAGE_MIME_TYPE); 11975 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11976 11977 // Query all live verifiers based on current user state 11978 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 11979 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 11980 11981 if (DEBUG_VERIFY) { 11982 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 11983 + verification.toString() + " with " + pkgLite.verifiers.length 11984 + " optional verifiers"); 11985 } 11986 11987 final int verificationId = mPendingVerificationToken++; 11988 11989 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11990 11991 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 11992 installerPackageName); 11993 11994 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 11995 installFlags); 11996 11997 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 11998 pkgLite.packageName); 11999 12000 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12001 pkgLite.versionCode); 12002 12003 if (verificationInfo != null) { 12004 if (verificationInfo.originatingUri != null) { 12005 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12006 verificationInfo.originatingUri); 12007 } 12008 if (verificationInfo.referrer != null) { 12009 verification.putExtra(Intent.EXTRA_REFERRER, 12010 verificationInfo.referrer); 12011 } 12012 if (verificationInfo.originatingUid >= 0) { 12013 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12014 verificationInfo.originatingUid); 12015 } 12016 if (verificationInfo.installerUid >= 0) { 12017 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12018 verificationInfo.installerUid); 12019 } 12020 } 12021 12022 final PackageVerificationState verificationState = new PackageVerificationState( 12023 requiredUid, args); 12024 12025 mPendingVerification.append(verificationId, verificationState); 12026 12027 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12028 receivers, verificationState); 12029 12030 /* 12031 * If any sufficient verifiers were listed in the package 12032 * manifest, attempt to ask them. 12033 */ 12034 if (sufficientVerifiers != null) { 12035 final int N = sufficientVerifiers.size(); 12036 if (N == 0) { 12037 Slog.i(TAG, "Additional verifiers required, but none installed."); 12038 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12039 } else { 12040 for (int i = 0; i < N; i++) { 12041 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12042 12043 final Intent sufficientIntent = new Intent(verification); 12044 sufficientIntent.setComponent(verifierComponent); 12045 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12046 } 12047 } 12048 } 12049 12050 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12051 mRequiredVerifierPackage, receivers); 12052 if (ret == PackageManager.INSTALL_SUCCEEDED 12053 && mRequiredVerifierPackage != null) { 12054 Trace.asyncTraceBegin( 12055 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12056 /* 12057 * Send the intent to the required verification agent, 12058 * but only start the verification timeout after the 12059 * target BroadcastReceivers have run. 12060 */ 12061 verification.setComponent(requiredVerifierComponent); 12062 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12063 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12064 new BroadcastReceiver() { 12065 @Override 12066 public void onReceive(Context context, Intent intent) { 12067 final Message msg = mHandler 12068 .obtainMessage(CHECK_PENDING_VERIFICATION); 12069 msg.arg1 = verificationId; 12070 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12071 } 12072 }, null, 0, null, null); 12073 12074 /* 12075 * We don't want the copy to proceed until verification 12076 * succeeds, so null out this field. 12077 */ 12078 mArgs = null; 12079 } 12080 } else { 12081 /* 12082 * No package verification is enabled, so immediately start 12083 * the remote call to initiate copy using temporary file. 12084 */ 12085 ret = args.copyApk(mContainerService, true); 12086 } 12087 } 12088 12089 mRet = ret; 12090 } 12091 12092 @Override 12093 void handleReturnCode() { 12094 // If mArgs is null, then MCS couldn't be reached. When it 12095 // reconnects, it will try again to install. At that point, this 12096 // will succeed. 12097 if (mArgs != null) { 12098 processPendingInstall(mArgs, mRet); 12099 } 12100 } 12101 12102 @Override 12103 void handleServiceError() { 12104 mArgs = createInstallArgs(this); 12105 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12106 } 12107 12108 public boolean isForwardLocked() { 12109 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12110 } 12111 } 12112 12113 /** 12114 * Used during creation of InstallArgs 12115 * 12116 * @param installFlags package installation flags 12117 * @return true if should be installed on external storage 12118 */ 12119 private static boolean installOnExternalAsec(int installFlags) { 12120 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12121 return false; 12122 } 12123 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12124 return true; 12125 } 12126 return false; 12127 } 12128 12129 /** 12130 * Used during creation of InstallArgs 12131 * 12132 * @param installFlags package installation flags 12133 * @return true if should be installed as forward locked 12134 */ 12135 private static boolean installForwardLocked(int installFlags) { 12136 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12137 } 12138 12139 private InstallArgs createInstallArgs(InstallParams params) { 12140 if (params.move != null) { 12141 return new MoveInstallArgs(params); 12142 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12143 return new AsecInstallArgs(params); 12144 } else { 12145 return new FileInstallArgs(params); 12146 } 12147 } 12148 12149 /** 12150 * Create args that describe an existing installed package. Typically used 12151 * when cleaning up old installs, or used as a move source. 12152 */ 12153 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12154 String resourcePath, String[] instructionSets) { 12155 final boolean isInAsec; 12156 if (installOnExternalAsec(installFlags)) { 12157 /* Apps on SD card are always in ASEC containers. */ 12158 isInAsec = true; 12159 } else if (installForwardLocked(installFlags) 12160 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12161 /* 12162 * Forward-locked apps are only in ASEC containers if they're the 12163 * new style 12164 */ 12165 isInAsec = true; 12166 } else { 12167 isInAsec = false; 12168 } 12169 12170 if (isInAsec) { 12171 return new AsecInstallArgs(codePath, instructionSets, 12172 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12173 } else { 12174 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12175 } 12176 } 12177 12178 static abstract class InstallArgs { 12179 /** @see InstallParams#origin */ 12180 final OriginInfo origin; 12181 /** @see InstallParams#move */ 12182 final MoveInfo move; 12183 12184 final IPackageInstallObserver2 observer; 12185 // Always refers to PackageManager flags only 12186 final int installFlags; 12187 final String installerPackageName; 12188 final String volumeUuid; 12189 final UserHandle user; 12190 final String abiOverride; 12191 final String[] installGrantPermissions; 12192 /** If non-null, drop an async trace when the install completes */ 12193 final String traceMethod; 12194 final int traceCookie; 12195 12196 // The list of instruction sets supported by this app. This is currently 12197 // only used during the rmdex() phase to clean up resources. We can get rid of this 12198 // if we move dex files under the common app path. 12199 /* nullable */ String[] instructionSets; 12200 12201 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12202 int installFlags, String installerPackageName, String volumeUuid, 12203 UserHandle user, String[] instructionSets, 12204 String abiOverride, String[] installGrantPermissions, 12205 String traceMethod, int traceCookie) { 12206 this.origin = origin; 12207 this.move = move; 12208 this.installFlags = installFlags; 12209 this.observer = observer; 12210 this.installerPackageName = installerPackageName; 12211 this.volumeUuid = volumeUuid; 12212 this.user = user; 12213 this.instructionSets = instructionSets; 12214 this.abiOverride = abiOverride; 12215 this.installGrantPermissions = installGrantPermissions; 12216 this.traceMethod = traceMethod; 12217 this.traceCookie = traceCookie; 12218 } 12219 12220 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12221 abstract int doPreInstall(int status); 12222 12223 /** 12224 * Rename package into final resting place. All paths on the given 12225 * scanned package should be updated to reflect the rename. 12226 */ 12227 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12228 abstract int doPostInstall(int status, int uid); 12229 12230 /** @see PackageSettingBase#codePathString */ 12231 abstract String getCodePath(); 12232 /** @see PackageSettingBase#resourcePathString */ 12233 abstract String getResourcePath(); 12234 12235 // Need installer lock especially for dex file removal. 12236 abstract void cleanUpResourcesLI(); 12237 abstract boolean doPostDeleteLI(boolean delete); 12238 12239 /** 12240 * Called before the source arguments are copied. This is used mostly 12241 * for MoveParams when it needs to read the source file to put it in the 12242 * destination. 12243 */ 12244 int doPreCopy() { 12245 return PackageManager.INSTALL_SUCCEEDED; 12246 } 12247 12248 /** 12249 * Called after the source arguments are copied. This is used mostly for 12250 * MoveParams when it needs to read the source file to put it in the 12251 * destination. 12252 * 12253 * @return 12254 */ 12255 int doPostCopy(int uid) { 12256 return PackageManager.INSTALL_SUCCEEDED; 12257 } 12258 12259 protected boolean isFwdLocked() { 12260 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12261 } 12262 12263 protected boolean isExternalAsec() { 12264 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12265 } 12266 12267 protected boolean isEphemeral() { 12268 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12269 } 12270 12271 UserHandle getUser() { 12272 return user; 12273 } 12274 } 12275 12276 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 12277 if (!allCodePaths.isEmpty()) { 12278 if (instructionSets == null) { 12279 throw new IllegalStateException("instructionSet == null"); 12280 } 12281 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 12282 for (String codePath : allCodePaths) { 12283 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 12284 try { 12285 mInstaller.rmdex(codePath, dexCodeInstructionSet); 12286 } catch (InstallerException ignored) { 12287 } 12288 } 12289 } 12290 } 12291 } 12292 12293 /** 12294 * Logic to handle installation of non-ASEC applications, including copying 12295 * and renaming logic. 12296 */ 12297 class FileInstallArgs extends InstallArgs { 12298 private File codeFile; 12299 private File resourceFile; 12300 12301 // Example topology: 12302 // /data/app/com.example/base.apk 12303 // /data/app/com.example/split_foo.apk 12304 // /data/app/com.example/lib/arm/libfoo.so 12305 // /data/app/com.example/lib/arm64/libfoo.so 12306 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 12307 12308 /** New install */ 12309 FileInstallArgs(InstallParams params) { 12310 super(params.origin, params.move, params.observer, params.installFlags, 12311 params.installerPackageName, params.volumeUuid, 12312 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12313 params.grantedRuntimePermissions, 12314 params.traceMethod, params.traceCookie); 12315 if (isFwdLocked()) { 12316 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 12317 } 12318 } 12319 12320 /** Existing install */ 12321 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 12322 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 12323 null, null, null, 0); 12324 this.codeFile = (codePath != null) ? new File(codePath) : null; 12325 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 12326 } 12327 12328 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12329 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 12330 try { 12331 return doCopyApk(imcs, temp); 12332 } finally { 12333 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12334 } 12335 } 12336 12337 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12338 if (origin.staged) { 12339 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 12340 codeFile = origin.file; 12341 resourceFile = origin.file; 12342 return PackageManager.INSTALL_SUCCEEDED; 12343 } 12344 12345 try { 12346 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12347 final File tempDir = 12348 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 12349 codeFile = tempDir; 12350 resourceFile = tempDir; 12351 } catch (IOException e) { 12352 Slog.w(TAG, "Failed to create copy file: " + e); 12353 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12354 } 12355 12356 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 12357 @Override 12358 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 12359 if (!FileUtils.isValidExtFilename(name)) { 12360 throw new IllegalArgumentException("Invalid filename: " + name); 12361 } 12362 try { 12363 final File file = new File(codeFile, name); 12364 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 12365 O_RDWR | O_CREAT, 0644); 12366 Os.chmod(file.getAbsolutePath(), 0644); 12367 return new ParcelFileDescriptor(fd); 12368 } catch (ErrnoException e) { 12369 throw new RemoteException("Failed to open: " + e.getMessage()); 12370 } 12371 } 12372 }; 12373 12374 int ret = PackageManager.INSTALL_SUCCEEDED; 12375 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 12376 if (ret != PackageManager.INSTALL_SUCCEEDED) { 12377 Slog.e(TAG, "Failed to copy package"); 12378 return ret; 12379 } 12380 12381 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 12382 NativeLibraryHelper.Handle handle = null; 12383 try { 12384 handle = NativeLibraryHelper.Handle.create(codeFile); 12385 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 12386 abiOverride); 12387 } catch (IOException e) { 12388 Slog.e(TAG, "Copying native libraries failed", e); 12389 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12390 } finally { 12391 IoUtils.closeQuietly(handle); 12392 } 12393 12394 return ret; 12395 } 12396 12397 int doPreInstall(int status) { 12398 if (status != PackageManager.INSTALL_SUCCEEDED) { 12399 cleanUp(); 12400 } 12401 return status; 12402 } 12403 12404 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12405 if (status != PackageManager.INSTALL_SUCCEEDED) { 12406 cleanUp(); 12407 return false; 12408 } 12409 12410 final File targetDir = codeFile.getParentFile(); 12411 final File beforeCodeFile = codeFile; 12412 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 12413 12414 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 12415 try { 12416 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 12417 } catch (ErrnoException e) { 12418 Slog.w(TAG, "Failed to rename", e); 12419 return false; 12420 } 12421 12422 if (!SELinux.restoreconRecursive(afterCodeFile)) { 12423 Slog.w(TAG, "Failed to restorecon"); 12424 return false; 12425 } 12426 12427 // Reflect the rename internally 12428 codeFile = afterCodeFile; 12429 resourceFile = afterCodeFile; 12430 12431 // Reflect the rename in scanned details 12432 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12433 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12434 afterCodeFile, pkg.baseCodePath)); 12435 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12436 afterCodeFile, pkg.splitCodePaths)); 12437 12438 // Reflect the rename in app info 12439 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12440 pkg.setApplicationInfoCodePath(pkg.codePath); 12441 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12442 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12443 pkg.setApplicationInfoResourcePath(pkg.codePath); 12444 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12445 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12446 12447 return true; 12448 } 12449 12450 int doPostInstall(int status, int uid) { 12451 if (status != PackageManager.INSTALL_SUCCEEDED) { 12452 cleanUp(); 12453 } 12454 return status; 12455 } 12456 12457 @Override 12458 String getCodePath() { 12459 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12460 } 12461 12462 @Override 12463 String getResourcePath() { 12464 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12465 } 12466 12467 private boolean cleanUp() { 12468 if (codeFile == null || !codeFile.exists()) { 12469 return false; 12470 } 12471 12472 removeCodePathLI(codeFile); 12473 12474 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 12475 resourceFile.delete(); 12476 } 12477 12478 return true; 12479 } 12480 12481 void cleanUpResourcesLI() { 12482 // Try enumerating all code paths before deleting 12483 List<String> allCodePaths = Collections.EMPTY_LIST; 12484 if (codeFile != null && codeFile.exists()) { 12485 try { 12486 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12487 allCodePaths = pkg.getAllCodePaths(); 12488 } catch (PackageParserException e) { 12489 // Ignored; we tried our best 12490 } 12491 } 12492 12493 cleanUp(); 12494 removeDexFiles(allCodePaths, instructionSets); 12495 } 12496 12497 boolean doPostDeleteLI(boolean delete) { 12498 // XXX err, shouldn't we respect the delete flag? 12499 cleanUpResourcesLI(); 12500 return true; 12501 } 12502 } 12503 12504 private boolean isAsecExternal(String cid) { 12505 final String asecPath = PackageHelper.getSdFilesystem(cid); 12506 return !asecPath.startsWith(mAsecInternalPath); 12507 } 12508 12509 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 12510 PackageManagerException { 12511 if (copyRet < 0) { 12512 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 12513 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 12514 throw new PackageManagerException(copyRet, message); 12515 } 12516 } 12517 } 12518 12519 /** 12520 * Extract the MountService "container ID" from the full code path of an 12521 * .apk. 12522 */ 12523 static String cidFromCodePath(String fullCodePath) { 12524 int eidx = fullCodePath.lastIndexOf("/"); 12525 String subStr1 = fullCodePath.substring(0, eidx); 12526 int sidx = subStr1.lastIndexOf("/"); 12527 return subStr1.substring(sidx+1, eidx); 12528 } 12529 12530 /** 12531 * Logic to handle installation of ASEC applications, including copying and 12532 * renaming logic. 12533 */ 12534 class AsecInstallArgs extends InstallArgs { 12535 static final String RES_FILE_NAME = "pkg.apk"; 12536 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 12537 12538 String cid; 12539 String packagePath; 12540 String resourcePath; 12541 12542 /** New install */ 12543 AsecInstallArgs(InstallParams params) { 12544 super(params.origin, params.move, params.observer, params.installFlags, 12545 params.installerPackageName, params.volumeUuid, 12546 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12547 params.grantedRuntimePermissions, 12548 params.traceMethod, params.traceCookie); 12549 } 12550 12551 /** Existing install */ 12552 AsecInstallArgs(String fullCodePath, String[] instructionSets, 12553 boolean isExternal, boolean isForwardLocked) { 12554 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 12555 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12556 instructionSets, null, null, null, 0); 12557 // Hackily pretend we're still looking at a full code path 12558 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 12559 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 12560 } 12561 12562 // Extract cid from fullCodePath 12563 int eidx = fullCodePath.lastIndexOf("/"); 12564 String subStr1 = fullCodePath.substring(0, eidx); 12565 int sidx = subStr1.lastIndexOf("/"); 12566 cid = subStr1.substring(sidx+1, eidx); 12567 setMountPath(subStr1); 12568 } 12569 12570 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 12571 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 12572 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12573 instructionSets, null, null, null, 0); 12574 this.cid = cid; 12575 setMountPath(PackageHelper.getSdDir(cid)); 12576 } 12577 12578 void createCopyFile() { 12579 cid = mInstallerService.allocateExternalStageCidLegacy(); 12580 } 12581 12582 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12583 if (origin.staged && origin.cid != null) { 12584 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 12585 cid = origin.cid; 12586 setMountPath(PackageHelper.getSdDir(cid)); 12587 return PackageManager.INSTALL_SUCCEEDED; 12588 } 12589 12590 if (temp) { 12591 createCopyFile(); 12592 } else { 12593 /* 12594 * Pre-emptively destroy the container since it's destroyed if 12595 * copying fails due to it existing anyway. 12596 */ 12597 PackageHelper.destroySdDir(cid); 12598 } 12599 12600 final String newMountPath = imcs.copyPackageToContainer( 12601 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 12602 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 12603 12604 if (newMountPath != null) { 12605 setMountPath(newMountPath); 12606 return PackageManager.INSTALL_SUCCEEDED; 12607 } else { 12608 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12609 } 12610 } 12611 12612 @Override 12613 String getCodePath() { 12614 return packagePath; 12615 } 12616 12617 @Override 12618 String getResourcePath() { 12619 return resourcePath; 12620 } 12621 12622 int doPreInstall(int status) { 12623 if (status != PackageManager.INSTALL_SUCCEEDED) { 12624 // Destroy container 12625 PackageHelper.destroySdDir(cid); 12626 } else { 12627 boolean mounted = PackageHelper.isContainerMounted(cid); 12628 if (!mounted) { 12629 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 12630 Process.SYSTEM_UID); 12631 if (newMountPath != null) { 12632 setMountPath(newMountPath); 12633 } else { 12634 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12635 } 12636 } 12637 } 12638 return status; 12639 } 12640 12641 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12642 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 12643 String newMountPath = null; 12644 if (PackageHelper.isContainerMounted(cid)) { 12645 // Unmount the container 12646 if (!PackageHelper.unMountSdDir(cid)) { 12647 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 12648 return false; 12649 } 12650 } 12651 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 12652 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 12653 " which might be stale. Will try to clean up."); 12654 // Clean up the stale container and proceed to recreate. 12655 if (!PackageHelper.destroySdDir(newCacheId)) { 12656 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 12657 return false; 12658 } 12659 // Successfully cleaned up stale container. Try to rename again. 12660 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 12661 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 12662 + " inspite of cleaning it up."); 12663 return false; 12664 } 12665 } 12666 if (!PackageHelper.isContainerMounted(newCacheId)) { 12667 Slog.w(TAG, "Mounting container " + newCacheId); 12668 newMountPath = PackageHelper.mountSdDir(newCacheId, 12669 getEncryptKey(), Process.SYSTEM_UID); 12670 } else { 12671 newMountPath = PackageHelper.getSdDir(newCacheId); 12672 } 12673 if (newMountPath == null) { 12674 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 12675 return false; 12676 } 12677 Log.i(TAG, "Succesfully renamed " + cid + 12678 " to " + newCacheId + 12679 " at new path: " + newMountPath); 12680 cid = newCacheId; 12681 12682 final File beforeCodeFile = new File(packagePath); 12683 setMountPath(newMountPath); 12684 final File afterCodeFile = new File(packagePath); 12685 12686 // Reflect the rename in scanned details 12687 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12688 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12689 afterCodeFile, pkg.baseCodePath)); 12690 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12691 afterCodeFile, pkg.splitCodePaths)); 12692 12693 // Reflect the rename in app info 12694 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12695 pkg.setApplicationInfoCodePath(pkg.codePath); 12696 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12697 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12698 pkg.setApplicationInfoResourcePath(pkg.codePath); 12699 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12700 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12701 12702 return true; 12703 } 12704 12705 private void setMountPath(String mountPath) { 12706 final File mountFile = new File(mountPath); 12707 12708 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 12709 if (monolithicFile.exists()) { 12710 packagePath = monolithicFile.getAbsolutePath(); 12711 if (isFwdLocked()) { 12712 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 12713 } else { 12714 resourcePath = packagePath; 12715 } 12716 } else { 12717 packagePath = mountFile.getAbsolutePath(); 12718 resourcePath = packagePath; 12719 } 12720 } 12721 12722 int doPostInstall(int status, int uid) { 12723 if (status != PackageManager.INSTALL_SUCCEEDED) { 12724 cleanUp(); 12725 } else { 12726 final int groupOwner; 12727 final String protectedFile; 12728 if (isFwdLocked()) { 12729 groupOwner = UserHandle.getSharedAppGid(uid); 12730 protectedFile = RES_FILE_NAME; 12731 } else { 12732 groupOwner = -1; 12733 protectedFile = null; 12734 } 12735 12736 if (uid < Process.FIRST_APPLICATION_UID 12737 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 12738 Slog.e(TAG, "Failed to finalize " + cid); 12739 PackageHelper.destroySdDir(cid); 12740 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12741 } 12742 12743 boolean mounted = PackageHelper.isContainerMounted(cid); 12744 if (!mounted) { 12745 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 12746 } 12747 } 12748 return status; 12749 } 12750 12751 private void cleanUp() { 12752 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 12753 12754 // Destroy secure container 12755 PackageHelper.destroySdDir(cid); 12756 } 12757 12758 private List<String> getAllCodePaths() { 12759 final File codeFile = new File(getCodePath()); 12760 if (codeFile != null && codeFile.exists()) { 12761 try { 12762 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12763 return pkg.getAllCodePaths(); 12764 } catch (PackageParserException e) { 12765 // Ignored; we tried our best 12766 } 12767 } 12768 return Collections.EMPTY_LIST; 12769 } 12770 12771 void cleanUpResourcesLI() { 12772 // Enumerate all code paths before deleting 12773 cleanUpResourcesLI(getAllCodePaths()); 12774 } 12775 12776 private void cleanUpResourcesLI(List<String> allCodePaths) { 12777 cleanUp(); 12778 removeDexFiles(allCodePaths, instructionSets); 12779 } 12780 12781 String getPackageName() { 12782 return getAsecPackageName(cid); 12783 } 12784 12785 boolean doPostDeleteLI(boolean delete) { 12786 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 12787 final List<String> allCodePaths = getAllCodePaths(); 12788 boolean mounted = PackageHelper.isContainerMounted(cid); 12789 if (mounted) { 12790 // Unmount first 12791 if (PackageHelper.unMountSdDir(cid)) { 12792 mounted = false; 12793 } 12794 } 12795 if (!mounted && delete) { 12796 cleanUpResourcesLI(allCodePaths); 12797 } 12798 return !mounted; 12799 } 12800 12801 @Override 12802 int doPreCopy() { 12803 if (isFwdLocked()) { 12804 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 12805 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 12806 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12807 } 12808 } 12809 12810 return PackageManager.INSTALL_SUCCEEDED; 12811 } 12812 12813 @Override 12814 int doPostCopy(int uid) { 12815 if (isFwdLocked()) { 12816 if (uid < Process.FIRST_APPLICATION_UID 12817 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 12818 RES_FILE_NAME)) { 12819 Slog.e(TAG, "Failed to finalize " + cid); 12820 PackageHelper.destroySdDir(cid); 12821 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12822 } 12823 } 12824 12825 return PackageManager.INSTALL_SUCCEEDED; 12826 } 12827 } 12828 12829 /** 12830 * Logic to handle movement of existing installed applications. 12831 */ 12832 class MoveInstallArgs extends InstallArgs { 12833 private File codeFile; 12834 private File resourceFile; 12835 12836 /** New install */ 12837 MoveInstallArgs(InstallParams params) { 12838 super(params.origin, params.move, params.observer, params.installFlags, 12839 params.installerPackageName, params.volumeUuid, 12840 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12841 params.grantedRuntimePermissions, 12842 params.traceMethod, params.traceCookie); 12843 } 12844 12845 int copyApk(IMediaContainerService imcs, boolean temp) { 12846 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 12847 + move.fromUuid + " to " + move.toUuid); 12848 synchronized (mInstaller) { 12849 try { 12850 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 12851 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 12852 } catch (InstallerException e) { 12853 Slog.w(TAG, "Failed to move app", e); 12854 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12855 } 12856 } 12857 12858 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 12859 resourceFile = codeFile; 12860 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 12861 12862 return PackageManager.INSTALL_SUCCEEDED; 12863 } 12864 12865 int doPreInstall(int status) { 12866 if (status != PackageManager.INSTALL_SUCCEEDED) { 12867 cleanUp(move.toUuid); 12868 } 12869 return status; 12870 } 12871 12872 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12873 if (status != PackageManager.INSTALL_SUCCEEDED) { 12874 cleanUp(move.toUuid); 12875 return false; 12876 } 12877 12878 // Reflect the move in app info 12879 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12880 pkg.setApplicationInfoCodePath(pkg.codePath); 12881 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12882 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12883 pkg.setApplicationInfoResourcePath(pkg.codePath); 12884 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12885 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12886 12887 return true; 12888 } 12889 12890 int doPostInstall(int status, int uid) { 12891 if (status == PackageManager.INSTALL_SUCCEEDED) { 12892 cleanUp(move.fromUuid); 12893 } else { 12894 cleanUp(move.toUuid); 12895 } 12896 return status; 12897 } 12898 12899 @Override 12900 String getCodePath() { 12901 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12902 } 12903 12904 @Override 12905 String getResourcePath() { 12906 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12907 } 12908 12909 private boolean cleanUp(String volumeUuid) { 12910 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 12911 move.dataAppName); 12912 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 12913 synchronized (mInstallLock) { 12914 // Clean up both app data and code 12915 removeDataDirsLI(volumeUuid, move.packageName); 12916 removeCodePathLI(codeFile); 12917 } 12918 return true; 12919 } 12920 12921 void cleanUpResourcesLI() { 12922 throw new UnsupportedOperationException(); 12923 } 12924 12925 boolean doPostDeleteLI(boolean delete) { 12926 throw new UnsupportedOperationException(); 12927 } 12928 } 12929 12930 static String getAsecPackageName(String packageCid) { 12931 int idx = packageCid.lastIndexOf("-"); 12932 if (idx == -1) { 12933 return packageCid; 12934 } 12935 return packageCid.substring(0, idx); 12936 } 12937 12938 // Utility method used to create code paths based on package name and available index. 12939 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 12940 String idxStr = ""; 12941 int idx = 1; 12942 // Fall back to default value of idx=1 if prefix is not 12943 // part of oldCodePath 12944 if (oldCodePath != null) { 12945 String subStr = oldCodePath; 12946 // Drop the suffix right away 12947 if (suffix != null && subStr.endsWith(suffix)) { 12948 subStr = subStr.substring(0, subStr.length() - suffix.length()); 12949 } 12950 // If oldCodePath already contains prefix find out the 12951 // ending index to either increment or decrement. 12952 int sidx = subStr.lastIndexOf(prefix); 12953 if (sidx != -1) { 12954 subStr = subStr.substring(sidx + prefix.length()); 12955 if (subStr != null) { 12956 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 12957 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 12958 } 12959 try { 12960 idx = Integer.parseInt(subStr); 12961 if (idx <= 1) { 12962 idx++; 12963 } else { 12964 idx--; 12965 } 12966 } catch(NumberFormatException e) { 12967 } 12968 } 12969 } 12970 } 12971 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 12972 return prefix + idxStr; 12973 } 12974 12975 private File getNextCodePath(File targetDir, String packageName) { 12976 int suffix = 1; 12977 File result; 12978 do { 12979 result = new File(targetDir, packageName + "-" + suffix); 12980 suffix++; 12981 } while (result.exists()); 12982 return result; 12983 } 12984 12985 // Utility method that returns the relative package path with respect 12986 // to the installation directory. Like say for /data/data/com.test-1.apk 12987 // string com.test-1 is returned. 12988 static String deriveCodePathName(String codePath) { 12989 if (codePath == null) { 12990 return null; 12991 } 12992 final File codeFile = new File(codePath); 12993 final String name = codeFile.getName(); 12994 if (codeFile.isDirectory()) { 12995 return name; 12996 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 12997 final int lastDot = name.lastIndexOf('.'); 12998 return name.substring(0, lastDot); 12999 } else { 13000 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13001 return null; 13002 } 13003 } 13004 13005 static class PackageInstalledInfo { 13006 String name; 13007 int uid; 13008 // The set of users that originally had this package installed. 13009 int[] origUsers; 13010 // The set of users that now have this package installed. 13011 int[] newUsers; 13012 PackageParser.Package pkg; 13013 int returnCode; 13014 String returnMsg; 13015 PackageRemovedInfo removedInfo; 13016 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13017 13018 public void setError(int code, String msg) { 13019 setReturnCode(code); 13020 setReturnMessage(msg); 13021 Slog.w(TAG, msg); 13022 } 13023 13024 public void setError(String msg, PackageParserException e) { 13025 setReturnCode(e.error); 13026 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13027 Slog.w(TAG, msg, e); 13028 } 13029 13030 public void setError(String msg, PackageManagerException e) { 13031 returnCode = e.error; 13032 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13033 Slog.w(TAG, msg, e); 13034 } 13035 13036 public void setReturnCode(int returnCode) { 13037 this.returnCode = returnCode; 13038 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13039 for (int i = 0; i < childCount; i++) { 13040 addedChildPackages.valueAt(i).returnCode = returnCode; 13041 } 13042 } 13043 13044 private void setReturnMessage(String returnMsg) { 13045 this.returnMsg = returnMsg; 13046 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13047 for (int i = 0; i < childCount; i++) { 13048 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13049 } 13050 } 13051 13052 // In some error cases we want to convey more info back to the observer 13053 String origPackage; 13054 String origPermission; 13055 } 13056 13057 /* 13058 * Install a non-existing package. 13059 */ 13060 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 13061 UserHandle user, String installerPackageName, String volumeUuid, 13062 PackageInstalledInfo res) { 13063 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13064 13065 // Remember this for later, in case we need to rollback this install 13066 String pkgName = pkg.packageName; 13067 13068 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13069 13070 synchronized(mPackages) { 13071 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13072 // A package with the same name is already installed, though 13073 // it has been renamed to an older name. The package we 13074 // are trying to install should be installed as an update to 13075 // the existing one, but that has not been requested, so bail. 13076 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13077 + " without first uninstalling package running as " 13078 + mSettings.mRenamedPackages.get(pkgName)); 13079 return; 13080 } 13081 if (mPackages.containsKey(pkgName)) { 13082 // Don't allow installation over an existing package with the same name. 13083 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13084 + " without first uninstalling."); 13085 return; 13086 } 13087 } 13088 13089 try { 13090 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 13091 System.currentTimeMillis(), user); 13092 13093 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13094 13095 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13096 prepareAppDataAfterInstall(newPackage); 13097 13098 } else { 13099 // Remove package from internal structures, but keep around any 13100 // data that might have already existed 13101 deletePackageLI(pkgName, UserHandle.ALL, false, null, 13102 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13103 } 13104 } catch (PackageManagerException e) { 13105 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13106 } 13107 13108 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13109 } 13110 13111 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13112 // Can't rotate keys during boot or if sharedUser. 13113 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13114 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13115 return false; 13116 } 13117 // app is using upgradeKeySets; make sure all are valid 13118 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13119 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13120 for (int i = 0; i < upgradeKeySets.length; i++) { 13121 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13122 Slog.wtf(TAG, "Package " 13123 + (oldPs.name != null ? oldPs.name : "<null>") 13124 + " contains upgrade-key-set reference to unknown key-set: " 13125 + upgradeKeySets[i] 13126 + " reverting to signatures check."); 13127 return false; 13128 } 13129 } 13130 return true; 13131 } 13132 13133 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13134 // Upgrade keysets are being used. Determine if new package has a superset of the 13135 // required keys. 13136 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13137 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13138 for (int i = 0; i < upgradeKeySets.length; i++) { 13139 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13140 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13141 return true; 13142 } 13143 } 13144 return false; 13145 } 13146 13147 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 13148 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13149 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13150 13151 final PackageParser.Package oldPackage; 13152 final String pkgName = pkg.packageName; 13153 final int[] allUsers; 13154 final boolean weFroze; 13155 13156 // First find the old package info and check signatures 13157 synchronized(mPackages) { 13158 oldPackage = mPackages.get(pkgName); 13159 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13160 if (isEphemeral && !oldIsEphemeral) { 13161 // can't downgrade from full to ephemeral 13162 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13163 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13164 return; 13165 } 13166 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13167 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13168 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13169 if (!checkUpgradeKeySetLP(ps, pkg)) { 13170 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13171 "New package not signed by keys specified by upgrade-keysets: " 13172 + pkgName); 13173 return; 13174 } 13175 } else { 13176 // default to original signature matching 13177 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13178 != PackageManager.SIGNATURE_MATCH) { 13179 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13180 "New package has a different signature: " + pkgName); 13181 return; 13182 } 13183 } 13184 13185 // In case of rollback, remember per-user/profile install state 13186 allUsers = sUserManager.getUserIds(); 13187 13188 // Mark the app as frozen to prevent launching during the upgrade 13189 // process, and then kill all running instances 13190 if (!ps.frozen) { 13191 ps.frozen = true; 13192 weFroze = true; 13193 } else { 13194 weFroze = false; 13195 } 13196 } 13197 13198 try { 13199 replacePackageDirtyLI(pkg, oldPackage, parseFlags, scanFlags, user, allUsers, 13200 installerPackageName, res); 13201 } finally { 13202 // Regardless of success or failure of upgrade steps above, always 13203 // unfreeze the package if we froze it 13204 if (weFroze) { 13205 unfreezePackage(pkgName); 13206 } 13207 } 13208 } 13209 13210 private void replacePackageDirtyLI(PackageParser.Package pkg, PackageParser.Package oldPackage, 13211 int parseFlags, int scanFlags, UserHandle user, int[] allUsers, 13212 String installerPackageName, PackageInstalledInfo res) { 13213 // Update what is removed 13214 res.removedInfo = new PackageRemovedInfo(); 13215 res.removedInfo.uid = oldPackage.applicationInfo.uid; 13216 res.removedInfo.removedPackage = oldPackage.packageName; 13217 res.removedInfo.isUpdate = true; 13218 final int childCount = (oldPackage.childPackages != null) 13219 ? oldPackage.childPackages.size() : 0; 13220 for (int i = 0; i < childCount; i++) { 13221 boolean childPackageUpdated = false; 13222 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 13223 if (res.addedChildPackages != null) { 13224 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13225 if (childRes != null) { 13226 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 13227 childRes.removedInfo.removedPackage = childPkg.packageName; 13228 childRes.removedInfo.isUpdate = true; 13229 childPackageUpdated = true; 13230 } 13231 } 13232 if (!childPackageUpdated) { 13233 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 13234 childRemovedRes.removedPackage = childPkg.packageName; 13235 childRemovedRes.isUpdate = false; 13236 childRemovedRes.dataRemoved = true; 13237 synchronized (mPackages) { 13238 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13239 if (childPs != null) { 13240 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 13241 } 13242 } 13243 if (res.removedInfo.removedChildPackages == null) { 13244 res.removedInfo.removedChildPackages = new ArrayMap<>(); 13245 } 13246 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 13247 } 13248 } 13249 13250 boolean sysPkg = (isSystemApp(oldPackage)); 13251 if (sysPkg) { 13252 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 13253 user, allUsers, installerPackageName, res); 13254 } else { 13255 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 13256 user, allUsers, installerPackageName, res); 13257 } 13258 } 13259 13260 public List<String> getPreviousCodePaths(String packageName) { 13261 final PackageSetting ps = mSettings.mPackages.get(packageName); 13262 final List<String> result = new ArrayList<String>(); 13263 if (ps != null && ps.oldCodePaths != null) { 13264 result.addAll(ps.oldCodePaths); 13265 } 13266 return result; 13267 } 13268 13269 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 13270 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13271 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13272 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 13273 + deletedPackage); 13274 13275 String pkgName = deletedPackage.packageName; 13276 boolean deletedPkg = true; 13277 boolean addedPkg = false; 13278 boolean updatedSettings = false; 13279 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 13280 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 13281 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 13282 13283 final long origUpdateTime = (pkg.mExtras != null) 13284 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 13285 13286 // First delete the existing package while retaining the data directory 13287 if (!deletePackageLI(pkgName, null, true, allUsers, deleteFlags, 13288 res.removedInfo, true, pkg)) { 13289 // If the existing package wasn't successfully deleted 13290 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 13291 deletedPkg = false; 13292 } else { 13293 // Successfully deleted the old package; proceed with replace. 13294 13295 // If deleted package lived in a container, give users a chance to 13296 // relinquish resources before killing. 13297 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 13298 if (DEBUG_INSTALL) { 13299 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 13300 } 13301 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 13302 final ArrayList<String> pkgList = new ArrayList<String>(1); 13303 pkgList.add(deletedPackage.applicationInfo.packageName); 13304 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 13305 } 13306 13307 deleteCodeCacheDirsLI(pkg); 13308 deleteProfilesLI(pkg, /*destroy*/ false); 13309 13310 try { 13311 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 13312 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 13313 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13314 13315 // Update the in-memory copy of the previous code paths. 13316 PackageSetting ps = mSettings.mPackages.get(pkgName); 13317 if (!killApp) { 13318 if (ps.oldCodePaths == null) { 13319 ps.oldCodePaths = new ArraySet<>(); 13320 } 13321 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 13322 if (deletedPackage.splitCodePaths != null) { 13323 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 13324 } 13325 } else { 13326 ps.oldCodePaths = null; 13327 } 13328 if (ps.childPackageNames != null) { 13329 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 13330 final String childPkgName = ps.childPackageNames.get(i); 13331 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 13332 childPs.oldCodePaths = ps.oldCodePaths; 13333 } 13334 } 13335 prepareAppDataAfterInstall(newPackage); 13336 addedPkg = true; 13337 } catch (PackageManagerException e) { 13338 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13339 } 13340 } 13341 13342 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13343 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 13344 13345 // Revert all internal state mutations and added folders for the failed install 13346 if (addedPkg) { 13347 deletePackageLI(pkgName, null, true, allUsers, deleteFlags, 13348 res.removedInfo, true, null); 13349 } 13350 13351 // Restore the old package 13352 if (deletedPkg) { 13353 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 13354 File restoreFile = new File(deletedPackage.codePath); 13355 // Parse old package 13356 boolean oldExternal = isExternal(deletedPackage); 13357 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 13358 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 13359 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 13360 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 13361 try { 13362 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 13363 null); 13364 } catch (PackageManagerException e) { 13365 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 13366 + e.getMessage()); 13367 return; 13368 } 13369 13370 synchronized (mPackages) { 13371 // Ensure the installer package name up to date 13372 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13373 13374 // Update permissions for restored package 13375 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13376 13377 mSettings.writeLPr(); 13378 } 13379 13380 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 13381 } 13382 } else { 13383 synchronized (mPackages) { 13384 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 13385 if (ps != null) { 13386 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 13387 if (res.removedInfo.removedChildPackages != null) { 13388 final int childCount = res.removedInfo.removedChildPackages.size(); 13389 // Iterate in reverse as we may modify the collection 13390 for (int i = childCount - 1; i >= 0; i--) { 13391 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 13392 if (res.addedChildPackages.containsKey(childPackageName)) { 13393 res.removedInfo.removedChildPackages.removeAt(i); 13394 } else { 13395 PackageRemovedInfo childInfo = res.removedInfo 13396 .removedChildPackages.valueAt(i); 13397 childInfo.removedForAllUsers = mPackages.get( 13398 childInfo.removedPackage) == null; 13399 } 13400 } 13401 } 13402 } 13403 } 13404 } 13405 } 13406 13407 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 13408 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13409 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13410 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 13411 + ", old=" + deletedPackage); 13412 13413 final boolean disabledSystem; 13414 13415 // Set the system/privileged flags as needed 13416 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 13417 if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 13418 != 0) { 13419 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13420 } 13421 13422 // Kill package processes including services, providers, etc. 13423 killPackage(deletedPackage, "replace sys pkg"); 13424 13425 // Remove existing system package 13426 removePackageLI(deletedPackage, true); 13427 13428 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 13429 if (!disabledSystem) { 13430 // We didn't need to disable the .apk as a current system package, 13431 // which means we are replacing another update that is already 13432 // installed. We need to make sure to delete the older one's .apk. 13433 res.removedInfo.args = createInstallArgsForExisting(0, 13434 deletedPackage.applicationInfo.getCodePath(), 13435 deletedPackage.applicationInfo.getResourcePath(), 13436 getAppDexInstructionSets(deletedPackage.applicationInfo)); 13437 } else { 13438 res.removedInfo.args = null; 13439 } 13440 13441 // Successfully disabled the old package. Now proceed with re-installation 13442 deleteCodeCacheDirsLI(pkg); 13443 deleteProfilesLI(pkg, /*destroy*/ false); 13444 13445 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13446 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 13447 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 13448 13449 PackageParser.Package newPackage = null; 13450 try { 13451 // Add the package to the internal data structures 13452 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 13453 13454 // Set the update and install times 13455 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 13456 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 13457 System.currentTimeMillis()); 13458 13459 // Check for shared user id changes 13460 String invalidPackageName = getParentOrChildPackageChangedSharedUser( 13461 deletedPackage, newPackage); 13462 if (invalidPackageName != null) { 13463 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13464 "Forbidding shared user change from " + deletedPkgSetting.sharedUser 13465 + " to " + invalidPackageName); 13466 } 13467 13468 // Update the package dynamic state if succeeded 13469 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13470 // Now that the install succeeded make sure we remove data 13471 // directories for any child package the update removed. 13472 final int deletedChildCount = (deletedPackage.childPackages != null) 13473 ? deletedPackage.childPackages.size() : 0; 13474 final int newChildCount = (newPackage.childPackages != null) 13475 ? newPackage.childPackages.size() : 0; 13476 for (int i = 0; i < deletedChildCount; i++) { 13477 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 13478 boolean childPackageDeleted = true; 13479 for (int j = 0; j < newChildCount; j++) { 13480 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 13481 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 13482 childPackageDeleted = false; 13483 break; 13484 } 13485 } 13486 if (childPackageDeleted) { 13487 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 13488 deletedChildPkg.packageName); 13489 if (ps != null && res.removedInfo.removedChildPackages != null) { 13490 PackageRemovedInfo removedChildRes = res.removedInfo 13491 .removedChildPackages.get(deletedChildPkg.packageName); 13492 removePackageDataLI(ps, allUsers, removedChildRes, 0, false); 13493 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 13494 } 13495 } 13496 } 13497 13498 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13499 prepareAppDataAfterInstall(newPackage); 13500 } 13501 } catch (PackageManagerException e) { 13502 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 13503 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13504 } 13505 13506 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13507 // Re installation failed. Restore old information 13508 // Remove new pkg information 13509 if (newPackage != null) { 13510 removeInstalledPackageLI(newPackage, true); 13511 } 13512 // Add back the old system package 13513 try { 13514 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 13515 } catch (PackageManagerException e) { 13516 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 13517 } 13518 13519 synchronized (mPackages) { 13520 if (disabledSystem) { 13521 enableSystemPackageLPw(deletedPackage); 13522 } 13523 13524 // Ensure the installer package name up to date 13525 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13526 13527 // Update permissions for restored package 13528 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13529 13530 mSettings.writeLPr(); 13531 } 13532 13533 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 13534 + " after failed upgrade"); 13535 } 13536 } 13537 13538 /** 13539 * Checks whether the parent or any of the child packages have a change shared 13540 * user. For a package to be a valid update the shred users of the parent and 13541 * the children should match. We may later support changing child shared users. 13542 * @param oldPkg The updated package. 13543 * @param newPkg The update package. 13544 * @return The shared user that change between the versions. 13545 */ 13546 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 13547 PackageParser.Package newPkg) { 13548 // Check parent shared user 13549 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 13550 return newPkg.packageName; 13551 } 13552 // Check child shared users 13553 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13554 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 13555 for (int i = 0; i < newChildCount; i++) { 13556 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 13557 // If this child was present, did it have the same shared user? 13558 for (int j = 0; j < oldChildCount; j++) { 13559 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 13560 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 13561 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 13562 return newChildPkg.packageName; 13563 } 13564 } 13565 } 13566 return null; 13567 } 13568 13569 private void removeNativeBinariesLI(PackageSetting ps) { 13570 // Remove the lib path for the parent package 13571 if (ps != null) { 13572 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 13573 // Remove the lib path for the child packages 13574 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 13575 for (int i = 0; i < childCount; i++) { 13576 PackageSetting childPs = null; 13577 synchronized (mPackages) { 13578 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 13579 } 13580 if (childPs != null) { 13581 NativeLibraryHelper.removeNativeBinariesLI(childPs 13582 .legacyNativeLibraryPathString); 13583 } 13584 } 13585 } 13586 } 13587 13588 private void enableSystemPackageLPw(PackageParser.Package pkg) { 13589 // Enable the parent package 13590 mSettings.enableSystemPackageLPw(pkg.packageName); 13591 // Enable the child packages 13592 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13593 for (int i = 0; i < childCount; i++) { 13594 PackageParser.Package childPkg = pkg.childPackages.get(i); 13595 mSettings.enableSystemPackageLPw(childPkg.packageName); 13596 } 13597 } 13598 13599 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 13600 PackageParser.Package newPkg) { 13601 // Disable the parent package (parent always replaced) 13602 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 13603 // Disable the child packages 13604 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13605 for (int i = 0; i < childCount; i++) { 13606 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 13607 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 13608 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 13609 } 13610 return disabled; 13611 } 13612 13613 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 13614 String installerPackageName) { 13615 // Enable the parent package 13616 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 13617 // Enable the child packages 13618 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13619 for (int i = 0; i < childCount; i++) { 13620 PackageParser.Package childPkg = pkg.childPackages.get(i); 13621 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 13622 } 13623 } 13624 13625 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 13626 // Collect all used permissions in the UID 13627 ArraySet<String> usedPermissions = new ArraySet<>(); 13628 final int packageCount = su.packages.size(); 13629 for (int i = 0; i < packageCount; i++) { 13630 PackageSetting ps = su.packages.valueAt(i); 13631 if (ps.pkg == null) { 13632 continue; 13633 } 13634 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 13635 for (int j = 0; j < requestedPermCount; j++) { 13636 String permission = ps.pkg.requestedPermissions.get(j); 13637 BasePermission bp = mSettings.mPermissions.get(permission); 13638 if (bp != null) { 13639 usedPermissions.add(permission); 13640 } 13641 } 13642 } 13643 13644 PermissionsState permissionsState = su.getPermissionsState(); 13645 // Prune install permissions 13646 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 13647 final int installPermCount = installPermStates.size(); 13648 for (int i = installPermCount - 1; i >= 0; i--) { 13649 PermissionState permissionState = installPermStates.get(i); 13650 if (!usedPermissions.contains(permissionState.getName())) { 13651 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 13652 if (bp != null) { 13653 permissionsState.revokeInstallPermission(bp); 13654 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 13655 PackageManager.MASK_PERMISSION_FLAGS, 0); 13656 } 13657 } 13658 } 13659 13660 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 13661 13662 // Prune runtime permissions 13663 for (int userId : allUserIds) { 13664 List<PermissionState> runtimePermStates = permissionsState 13665 .getRuntimePermissionStates(userId); 13666 final int runtimePermCount = runtimePermStates.size(); 13667 for (int i = runtimePermCount - 1; i >= 0; i--) { 13668 PermissionState permissionState = runtimePermStates.get(i); 13669 if (!usedPermissions.contains(permissionState.getName())) { 13670 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 13671 if (bp != null) { 13672 permissionsState.revokeRuntimePermission(bp, userId); 13673 permissionsState.updatePermissionFlags(bp, userId, 13674 PackageManager.MASK_PERMISSION_FLAGS, 0); 13675 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 13676 runtimePermissionChangedUserIds, userId); 13677 } 13678 } 13679 } 13680 } 13681 13682 return runtimePermissionChangedUserIds; 13683 } 13684 13685 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 13686 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 13687 // Update the parent package setting 13688 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 13689 res, user); 13690 // Update the child packages setting 13691 final int childCount = (newPackage.childPackages != null) 13692 ? newPackage.childPackages.size() : 0; 13693 for (int i = 0; i < childCount; i++) { 13694 PackageParser.Package childPackage = newPackage.childPackages.get(i); 13695 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 13696 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 13697 childRes.origUsers, childRes, user); 13698 } 13699 } 13700 13701 private void updateSettingsInternalLI(PackageParser.Package newPackage, 13702 String installerPackageName, int[] allUsers, int[] installedForUsers, 13703 PackageInstalledInfo res, UserHandle user) { 13704 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 13705 13706 String pkgName = newPackage.packageName; 13707 synchronized (mPackages) { 13708 //write settings. the installStatus will be incomplete at this stage. 13709 //note that the new package setting would have already been 13710 //added to mPackages. It hasn't been persisted yet. 13711 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 13712 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 13713 mSettings.writeLPr(); 13714 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13715 } 13716 13717 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 13718 synchronized (mPackages) { 13719 updatePermissionsLPw(newPackage.packageName, newPackage, 13720 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 13721 ? UPDATE_PERMISSIONS_ALL : 0)); 13722 // For system-bundled packages, we assume that installing an upgraded version 13723 // of the package implies that the user actually wants to run that new code, 13724 // so we enable the package. 13725 PackageSetting ps = mSettings.mPackages.get(pkgName); 13726 final int userId = user.getIdentifier(); 13727 if (ps != null) { 13728 if (isSystemApp(newPackage)) { 13729 if (DEBUG_INSTALL) { 13730 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 13731 } 13732 // Enable system package for requested users 13733 if (res.origUsers != null) { 13734 for (int origUserId : res.origUsers) { 13735 if (userId == UserHandle.USER_ALL || userId == origUserId) { 13736 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 13737 origUserId, installerPackageName); 13738 } 13739 } 13740 } 13741 // Also convey the prior install/uninstall state 13742 if (allUsers != null && installedForUsers != null) { 13743 for (int currentUserId : allUsers) { 13744 final boolean installed = ArrayUtils.contains( 13745 installedForUsers, currentUserId); 13746 if (DEBUG_INSTALL) { 13747 Slog.d(TAG, " user " + currentUserId + " => " + installed); 13748 } 13749 ps.setInstalled(installed, currentUserId); 13750 } 13751 // these install state changes will be persisted in the 13752 // upcoming call to mSettings.writeLPr(). 13753 } 13754 } 13755 // It's implied that when a user requests installation, they want the app to be 13756 // installed and enabled. 13757 if (userId != UserHandle.USER_ALL) { 13758 ps.setInstalled(true, userId); 13759 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 13760 } 13761 } 13762 res.name = pkgName; 13763 res.uid = newPackage.applicationInfo.uid; 13764 res.pkg = newPackage; 13765 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 13766 mSettings.setInstallerPackageName(pkgName, installerPackageName); 13767 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13768 //to update install status 13769 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 13770 mSettings.writeLPr(); 13771 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13772 } 13773 13774 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13775 } 13776 13777 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 13778 try { 13779 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 13780 installPackageLI(args, res); 13781 } finally { 13782 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13783 } 13784 } 13785 13786 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 13787 final int installFlags = args.installFlags; 13788 final String installerPackageName = args.installerPackageName; 13789 final String volumeUuid = args.volumeUuid; 13790 final File tmpPackageFile = new File(args.getCodePath()); 13791 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 13792 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 13793 || (args.volumeUuid != null)); 13794 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 13795 boolean replace = false; 13796 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 13797 if (args.move != null) { 13798 // moving a complete application; perform an initial scan on the new install location 13799 scanFlags |= SCAN_INITIAL; 13800 } 13801 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 13802 scanFlags |= SCAN_DONT_KILL_APP; 13803 } 13804 13805 // Result object to be returned 13806 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13807 13808 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 13809 13810 // Sanity check 13811 if (ephemeral && (forwardLocked || onExternal)) { 13812 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 13813 + " external=" + onExternal); 13814 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13815 return; 13816 } 13817 13818 // Retrieve PackageSettings and parse package 13819 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 13820 | PackageParser.PARSE_ENFORCE_CODE 13821 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 13822 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 13823 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 13824 PackageParser pp = new PackageParser(); 13825 pp.setSeparateProcesses(mSeparateProcesses); 13826 pp.setDisplayMetrics(mMetrics); 13827 13828 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 13829 final PackageParser.Package pkg; 13830 try { 13831 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 13832 } catch (PackageParserException e) { 13833 res.setError("Failed parse during installPackageLI", e); 13834 return; 13835 } finally { 13836 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13837 } 13838 13839 // If we are installing a clustered package add results for the children 13840 if (pkg.childPackages != null) { 13841 synchronized (mPackages) { 13842 final int childCount = pkg.childPackages.size(); 13843 for (int i = 0; i < childCount; i++) { 13844 PackageParser.Package childPkg = pkg.childPackages.get(i); 13845 PackageInstalledInfo childRes = new PackageInstalledInfo(); 13846 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13847 childRes.pkg = childPkg; 13848 childRes.name = childPkg.packageName; 13849 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13850 if (childPs != null) { 13851 childRes.origUsers = childPs.queryInstalledUsers( 13852 sUserManager.getUserIds(), true); 13853 } 13854 if ((mPackages.containsKey(childPkg.packageName))) { 13855 childRes.removedInfo = new PackageRemovedInfo(); 13856 childRes.removedInfo.removedPackage = childPkg.packageName; 13857 } 13858 if (res.addedChildPackages == null) { 13859 res.addedChildPackages = new ArrayMap<>(); 13860 } 13861 res.addedChildPackages.put(childPkg.packageName, childRes); 13862 } 13863 } 13864 } 13865 13866 // If package doesn't declare API override, mark that we have an install 13867 // time CPU ABI override. 13868 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 13869 pkg.cpuAbiOverride = args.abiOverride; 13870 } 13871 13872 String pkgName = res.name = pkg.packageName; 13873 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 13874 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 13875 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 13876 return; 13877 } 13878 } 13879 13880 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 13881 try { 13882 PackageParser.collectCertificates(pkg, parseFlags); 13883 } catch (PackageParserException e) { 13884 res.setError("Failed collect during installPackageLI", e); 13885 return; 13886 } finally { 13887 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13888 } 13889 13890 // Get rid of all references to package scan path via parser. 13891 pp = null; 13892 String oldCodePath = null; 13893 boolean systemApp = false; 13894 synchronized (mPackages) { 13895 // Check if installing already existing package 13896 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 13897 String oldName = mSettings.mRenamedPackages.get(pkgName); 13898 if (pkg.mOriginalPackages != null 13899 && pkg.mOriginalPackages.contains(oldName) 13900 && mPackages.containsKey(oldName)) { 13901 // This package is derived from an original package, 13902 // and this device has been updating from that original 13903 // name. We must continue using the original name, so 13904 // rename the new package here. 13905 pkg.setPackageName(oldName); 13906 pkgName = pkg.packageName; 13907 replace = true; 13908 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 13909 + oldName + " pkgName=" + pkgName); 13910 } else if (mPackages.containsKey(pkgName)) { 13911 // This package, under its official name, already exists 13912 // on the device; we should replace it. 13913 replace = true; 13914 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 13915 } 13916 13917 // Child packages are installed through the parent package 13918 if (pkg.parentPackage != null) { 13919 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 13920 "Package " + pkg.packageName + " is child of package " 13921 + pkg.parentPackage.parentPackage + ". Child packages " 13922 + "can be updated only through the parent package."); 13923 return; 13924 } 13925 13926 if (replace) { 13927 // Prevent apps opting out from runtime permissions 13928 PackageParser.Package oldPackage = mPackages.get(pkgName); 13929 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 13930 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 13931 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 13932 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 13933 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 13934 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 13935 + " doesn't support runtime permissions but the old" 13936 + " target SDK " + oldTargetSdk + " does."); 13937 return; 13938 } 13939 13940 // Prevent installing of child packages 13941 if (oldPackage.parentPackage != null) { 13942 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 13943 "Package " + pkg.packageName + " is child of package " 13944 + oldPackage.parentPackage + ". Child packages " 13945 + "can be updated only through the parent package."); 13946 return; 13947 } 13948 } 13949 } 13950 13951 PackageSetting ps = mSettings.mPackages.get(pkgName); 13952 if (ps != null) { 13953 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 13954 13955 // Quick sanity check that we're signed correctly if updating; 13956 // we'll check this again later when scanning, but we want to 13957 // bail early here before tripping over redefined permissions. 13958 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13959 if (!checkUpgradeKeySetLP(ps, pkg)) { 13960 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 13961 + pkg.packageName + " upgrade keys do not match the " 13962 + "previously installed version"); 13963 return; 13964 } 13965 } else { 13966 try { 13967 verifySignaturesLP(ps, pkg); 13968 } catch (PackageManagerException e) { 13969 res.setError(e.error, e.getMessage()); 13970 return; 13971 } 13972 } 13973 13974 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 13975 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 13976 systemApp = (ps.pkg.applicationInfo.flags & 13977 ApplicationInfo.FLAG_SYSTEM) != 0; 13978 } 13979 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13980 } 13981 13982 // Check whether the newly-scanned package wants to define an already-defined perm 13983 int N = pkg.permissions.size(); 13984 for (int i = N-1; i >= 0; i--) { 13985 PackageParser.Permission perm = pkg.permissions.get(i); 13986 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 13987 if (bp != null) { 13988 // If the defining package is signed with our cert, it's okay. This 13989 // also includes the "updating the same package" case, of course. 13990 // "updating same package" could also involve key-rotation. 13991 final boolean sigsOk; 13992 if (bp.sourcePackage.equals(pkg.packageName) 13993 && (bp.packageSetting instanceof PackageSetting) 13994 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 13995 scanFlags))) { 13996 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 13997 } else { 13998 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 13999 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14000 } 14001 if (!sigsOk) { 14002 // If the owning package is the system itself, we log but allow 14003 // install to proceed; we fail the install on all other permission 14004 // redefinitions. 14005 if (!bp.sourcePackage.equals("android")) { 14006 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14007 + pkg.packageName + " attempting to redeclare permission " 14008 + perm.info.name + " already owned by " + bp.sourcePackage); 14009 res.origPermission = perm.info.name; 14010 res.origPackage = bp.sourcePackage; 14011 return; 14012 } else { 14013 Slog.w(TAG, "Package " + pkg.packageName 14014 + " attempting to redeclare system permission " 14015 + perm.info.name + "; ignoring new declaration"); 14016 pkg.permissions.remove(i); 14017 } 14018 } 14019 } 14020 } 14021 } 14022 14023 if (systemApp) { 14024 if (onExternal) { 14025 // Abort update; system app can't be replaced with app on sdcard 14026 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14027 "Cannot install updates to system apps on sdcard"); 14028 return; 14029 } else if (ephemeral) { 14030 // Abort update; system app can't be replaced with an ephemeral app 14031 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14032 "Cannot update a system app with an ephemeral app"); 14033 return; 14034 } 14035 } 14036 14037 if (args.move != null) { 14038 // We did an in-place move, so dex is ready to roll 14039 scanFlags |= SCAN_NO_DEX; 14040 scanFlags |= SCAN_MOVE; 14041 14042 synchronized (mPackages) { 14043 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14044 if (ps == null) { 14045 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14046 "Missing settings for moved package " + pkgName); 14047 } 14048 14049 // We moved the entire application as-is, so bring over the 14050 // previously derived ABI information. 14051 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14052 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14053 } 14054 14055 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14056 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14057 scanFlags |= SCAN_NO_DEX; 14058 14059 try { 14060 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14061 args.abiOverride : pkg.cpuAbiOverride); 14062 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14063 true /* extract libs */); 14064 } catch (PackageManagerException pme) { 14065 Slog.e(TAG, "Error deriving application ABI", pme); 14066 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14067 return; 14068 } 14069 14070 14071 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14072 // Do not run PackageDexOptimizer through the local performDexOpt 14073 // method because `pkg` is not in `mPackages` yet. 14074 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 14075 false /* checkProfiles */, getCompilerFilterForReason(REASON_INSTALL)); 14076 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14077 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14078 String msg = "Extracking package failed for " + pkgName; 14079 res.setError(INSTALL_FAILED_DEXOPT, msg); 14080 return; 14081 } 14082 } 14083 14084 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14085 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14086 return; 14087 } 14088 14089 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14090 14091 if (replace) { 14092 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14093 installerPackageName, res); 14094 } else { 14095 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14096 args.user, installerPackageName, volumeUuid, res); 14097 } 14098 synchronized (mPackages) { 14099 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14100 if (ps != null) { 14101 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14102 } 14103 14104 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14105 for (int i = 0; i < childCount; i++) { 14106 PackageParser.Package childPkg = pkg.childPackages.get(i); 14107 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14108 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14109 if (childPs != null) { 14110 childRes.newUsers = childPs.queryInstalledUsers( 14111 sUserManager.getUserIds(), true); 14112 } 14113 } 14114 } 14115 } 14116 14117 private void startIntentFilterVerifications(int userId, boolean replacing, 14118 PackageParser.Package pkg) { 14119 if (mIntentFilterVerifierComponent == null) { 14120 Slog.w(TAG, "No IntentFilter verification will not be done as " 14121 + "there is no IntentFilterVerifier available!"); 14122 return; 14123 } 14124 14125 final int verifierUid = getPackageUid( 14126 mIntentFilterVerifierComponent.getPackageName(), 14127 MATCH_DEBUG_TRIAGED_MISSING, 14128 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 14129 14130 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14131 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14132 mHandler.sendMessage(msg); 14133 14134 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14135 for (int i = 0; i < childCount; i++) { 14136 PackageParser.Package childPkg = pkg.childPackages.get(i); 14137 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14138 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 14139 mHandler.sendMessage(msg); 14140 } 14141 } 14142 14143 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 14144 PackageParser.Package pkg) { 14145 int size = pkg.activities.size(); 14146 if (size == 0) { 14147 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14148 "No activity, so no need to verify any IntentFilter!"); 14149 return; 14150 } 14151 14152 final boolean hasDomainURLs = hasDomainURLs(pkg); 14153 if (!hasDomainURLs) { 14154 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14155 "No domain URLs, so no need to verify any IntentFilter!"); 14156 return; 14157 } 14158 14159 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 14160 + " if any IntentFilter from the " + size 14161 + " Activities needs verification ..."); 14162 14163 int count = 0; 14164 final String packageName = pkg.packageName; 14165 14166 synchronized (mPackages) { 14167 // If this is a new install and we see that we've already run verification for this 14168 // package, we have nothing to do: it means the state was restored from backup. 14169 if (!replacing) { 14170 IntentFilterVerificationInfo ivi = 14171 mSettings.getIntentFilterVerificationLPr(packageName); 14172 if (ivi != null) { 14173 if (DEBUG_DOMAIN_VERIFICATION) { 14174 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 14175 + ivi.getStatusString()); 14176 } 14177 return; 14178 } 14179 } 14180 14181 // If any filters need to be verified, then all need to be. 14182 boolean needToVerify = false; 14183 for (PackageParser.Activity a : pkg.activities) { 14184 for (ActivityIntentInfo filter : a.intents) { 14185 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 14186 if (DEBUG_DOMAIN_VERIFICATION) { 14187 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 14188 } 14189 needToVerify = true; 14190 break; 14191 } 14192 } 14193 } 14194 14195 if (needToVerify) { 14196 final int verificationId = mIntentFilterVerificationToken++; 14197 for (PackageParser.Activity a : pkg.activities) { 14198 for (ActivityIntentInfo filter : a.intents) { 14199 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 14200 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14201 "Verification needed for IntentFilter:" + filter.toString()); 14202 mIntentFilterVerifier.addOneIntentFilterVerification( 14203 verifierUid, userId, verificationId, filter, packageName); 14204 count++; 14205 } 14206 } 14207 } 14208 } 14209 } 14210 14211 if (count > 0) { 14212 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 14213 + " IntentFilter verification" + (count > 1 ? "s" : "") 14214 + " for userId:" + userId); 14215 mIntentFilterVerifier.startVerifications(userId); 14216 } else { 14217 if (DEBUG_DOMAIN_VERIFICATION) { 14218 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 14219 } 14220 } 14221 } 14222 14223 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 14224 final ComponentName cn = filter.activity.getComponentName(); 14225 final String packageName = cn.getPackageName(); 14226 14227 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 14228 packageName); 14229 if (ivi == null) { 14230 return true; 14231 } 14232 int status = ivi.getStatus(); 14233 switch (status) { 14234 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 14235 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 14236 return true; 14237 14238 default: 14239 // Nothing to do 14240 return false; 14241 } 14242 } 14243 14244 private static boolean isMultiArch(ApplicationInfo info) { 14245 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 14246 } 14247 14248 private static boolean isExternal(PackageParser.Package pkg) { 14249 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14250 } 14251 14252 private static boolean isExternal(PackageSetting ps) { 14253 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14254 } 14255 14256 private static boolean isEphemeral(PackageParser.Package pkg) { 14257 return pkg.applicationInfo.isEphemeralApp(); 14258 } 14259 14260 private static boolean isEphemeral(PackageSetting ps) { 14261 return ps.pkg != null && isEphemeral(ps.pkg); 14262 } 14263 14264 private static boolean isSystemApp(PackageParser.Package pkg) { 14265 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 14266 } 14267 14268 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 14269 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14270 } 14271 14272 private static boolean hasDomainURLs(PackageParser.Package pkg) { 14273 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 14274 } 14275 14276 private static boolean isSystemApp(PackageSetting ps) { 14277 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 14278 } 14279 14280 private static boolean isUpdatedSystemApp(PackageSetting ps) { 14281 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 14282 } 14283 14284 private int packageFlagsToInstallFlags(PackageSetting ps) { 14285 int installFlags = 0; 14286 if (isEphemeral(ps)) { 14287 installFlags |= PackageManager.INSTALL_EPHEMERAL; 14288 } 14289 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 14290 // This existing package was an external ASEC install when we have 14291 // the external flag without a UUID 14292 installFlags |= PackageManager.INSTALL_EXTERNAL; 14293 } 14294 if (ps.isForwardLocked()) { 14295 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 14296 } 14297 return installFlags; 14298 } 14299 14300 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 14301 if (isExternal(pkg)) { 14302 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14303 return StorageManager.UUID_PRIMARY_PHYSICAL; 14304 } else { 14305 return pkg.volumeUuid; 14306 } 14307 } else { 14308 return StorageManager.UUID_PRIVATE_INTERNAL; 14309 } 14310 } 14311 14312 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 14313 if (isExternal(pkg)) { 14314 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14315 return mSettings.getExternalVersion(); 14316 } else { 14317 return mSettings.findOrCreateVersion(pkg.volumeUuid); 14318 } 14319 } else { 14320 return mSettings.getInternalVersion(); 14321 } 14322 } 14323 14324 private void deleteTempPackageFiles() { 14325 final FilenameFilter filter = new FilenameFilter() { 14326 public boolean accept(File dir, String name) { 14327 return name.startsWith("vmdl") && name.endsWith(".tmp"); 14328 } 14329 }; 14330 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 14331 file.delete(); 14332 } 14333 } 14334 14335 @Override 14336 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 14337 int flags) { 14338 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 14339 flags); 14340 } 14341 14342 @Override 14343 public void deletePackage(final String packageName, 14344 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 14345 mContext.enforceCallingOrSelfPermission( 14346 android.Manifest.permission.DELETE_PACKAGES, null); 14347 Preconditions.checkNotNull(packageName); 14348 Preconditions.checkNotNull(observer); 14349 final int uid = Binder.getCallingUid(); 14350 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 14351 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 14352 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 14353 mContext.enforceCallingOrSelfPermission( 14354 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14355 "deletePackage for user " + userId); 14356 } 14357 14358 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 14359 try { 14360 observer.onPackageDeleted(packageName, 14361 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 14362 } catch (RemoteException re) { 14363 } 14364 return; 14365 } 14366 14367 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 14368 try { 14369 observer.onPackageDeleted(packageName, 14370 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 14371 } catch (RemoteException re) { 14372 } 14373 return; 14374 } 14375 14376 if (DEBUG_REMOVE) { 14377 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 14378 + " deleteAllUsers: " + deleteAllUsers ); 14379 } 14380 // Queue up an async operation since the package deletion may take a little while. 14381 mHandler.post(new Runnable() { 14382 public void run() { 14383 mHandler.removeCallbacks(this); 14384 int returnCode; 14385 if (!deleteAllUsers) { 14386 returnCode = deletePackageX(packageName, userId, flags); 14387 } else { 14388 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 14389 // If nobody is blocking uninstall, proceed with delete for all users 14390 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 14391 returnCode = deletePackageX(packageName, userId, flags); 14392 } else { 14393 // Otherwise uninstall individually for users with blockUninstalls=false 14394 final int userFlags = flags & ~PackageManager.DELETE_ALL_USERS; 14395 for (int userId : users) { 14396 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 14397 returnCode = deletePackageX(packageName, userId, userFlags); 14398 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 14399 Slog.w(TAG, "Package delete failed for user " + userId 14400 + ", returnCode " + returnCode); 14401 } 14402 } 14403 } 14404 // The app has only been marked uninstalled for certain users. 14405 // We still need to report that delete was blocked 14406 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 14407 } 14408 } 14409 try { 14410 observer.onPackageDeleted(packageName, returnCode, null); 14411 } catch (RemoteException e) { 14412 Log.i(TAG, "Observer no longer exists."); 14413 } //end catch 14414 } //end run 14415 }); 14416 } 14417 14418 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 14419 int[] result = EMPTY_INT_ARRAY; 14420 for (int userId : userIds) { 14421 if (getBlockUninstallForUser(packageName, userId)) { 14422 result = ArrayUtils.appendInt(result, userId); 14423 } 14424 } 14425 return result; 14426 } 14427 14428 @Override 14429 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 14430 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 14431 } 14432 14433 private boolean isPackageDeviceAdmin(String packageName, int userId) { 14434 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 14435 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 14436 try { 14437 if (dpm != null) { 14438 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 14439 /* callingUserOnly =*/ false); 14440 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 14441 : deviceOwnerComponentName.getPackageName(); 14442 // Does the package contains the device owner? 14443 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 14444 // this check is probably not needed, since DO should be registered as a device 14445 // admin on some user too. (Original bug for this: b/17657954) 14446 if (packageName.equals(deviceOwnerPackageName)) { 14447 return true; 14448 } 14449 // Does it contain a device admin for any user? 14450 int[] users; 14451 if (userId == UserHandle.USER_ALL) { 14452 users = sUserManager.getUserIds(); 14453 } else { 14454 users = new int[]{userId}; 14455 } 14456 for (int i = 0; i < users.length; ++i) { 14457 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 14458 return true; 14459 } 14460 } 14461 } 14462 } catch (RemoteException e) { 14463 } 14464 return false; 14465 } 14466 14467 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 14468 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 14469 } 14470 14471 /** 14472 * This method is an internal method that could be get invoked either 14473 * to delete an installed package or to clean up a failed installation. 14474 * After deleting an installed package, a broadcast is sent to notify any 14475 * listeners that the package has been installed. For cleaning up a failed 14476 * installation, the broadcast is not necessary since the package's 14477 * installation wouldn't have sent the initial broadcast either 14478 * The key steps in deleting a package are 14479 * deleting the package information in internal structures like mPackages, 14480 * deleting the packages base directories through installd 14481 * updating mSettings to reflect current status 14482 * persisting settings for later use 14483 * sending a broadcast if necessary 14484 */ 14485 private int deletePackageX(String packageName, int userId, int flags) { 14486 final PackageRemovedInfo info = new PackageRemovedInfo(); 14487 final boolean res; 14488 14489 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 14490 ? UserHandle.ALL : new UserHandle(userId); 14491 14492 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 14493 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 14494 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 14495 } 14496 14497 PackageSetting uninstalledPs = null; 14498 14499 // for the uninstall-updates case and restricted profiles, remember the per- 14500 // user handle installed state 14501 int[] allUsers; 14502 synchronized (mPackages) { 14503 uninstalledPs = mSettings.mPackages.get(packageName); 14504 if (uninstalledPs == null) { 14505 Slog.w(TAG, "Not removing non-existent package " + packageName); 14506 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14507 } 14508 allUsers = sUserManager.getUserIds(); 14509 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 14510 } 14511 14512 synchronized (mInstallLock) { 14513 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 14514 res = deletePackageLI(packageName, removeForUser, true, allUsers, 14515 flags | REMOVE_CHATTY, info, true, null); 14516 synchronized (mPackages) { 14517 if (res) { 14518 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 14519 } 14520 } 14521 } 14522 14523 if (res) { 14524 final boolean killApp = (flags & PackageManager.INSTALL_DONT_KILL_APP) == 0; 14525 info.sendPackageRemovedBroadcasts(killApp); 14526 info.sendSystemPackageUpdatedBroadcasts(); 14527 info.sendSystemPackageAppearedBroadcasts(); 14528 } 14529 // Force a gc here. 14530 Runtime.getRuntime().gc(); 14531 // Delete the resources here after sending the broadcast to let 14532 // other processes clean up before deleting resources. 14533 if (info.args != null) { 14534 synchronized (mInstallLock) { 14535 info.args.doPostDeleteLI(true); 14536 } 14537 } 14538 14539 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14540 } 14541 14542 class PackageRemovedInfo { 14543 String removedPackage; 14544 int uid = -1; 14545 int removedAppId = -1; 14546 int[] origUsers; 14547 int[] removedUsers = null; 14548 boolean isRemovedPackageSystemUpdate = false; 14549 boolean isUpdate; 14550 boolean dataRemoved; 14551 boolean removedForAllUsers; 14552 // Clean up resources deleted packages. 14553 InstallArgs args = null; 14554 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 14555 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 14556 14557 void sendPackageRemovedBroadcasts(boolean killApp) { 14558 sendPackageRemovedBroadcastInternal(killApp); 14559 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 14560 for (int i = 0; i < childCount; i++) { 14561 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 14562 childInfo.sendPackageRemovedBroadcastInternal(killApp); 14563 } 14564 } 14565 14566 void sendSystemPackageUpdatedBroadcasts() { 14567 if (isRemovedPackageSystemUpdate) { 14568 sendSystemPackageUpdatedBroadcastsInternal(); 14569 final int childCount = (removedChildPackages != null) 14570 ? removedChildPackages.size() : 0; 14571 for (int i = 0; i < childCount; i++) { 14572 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 14573 if (childInfo.isRemovedPackageSystemUpdate) { 14574 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 14575 } 14576 } 14577 } 14578 } 14579 14580 void sendSystemPackageAppearedBroadcasts() { 14581 final int packageCount = (appearedChildPackages != null) 14582 ? appearedChildPackages.size() : 0; 14583 for (int i = 0; i < packageCount; i++) { 14584 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 14585 for (int userId : installedInfo.newUsers) { 14586 sendPackageAddedForUser(installedInfo.name, true, 14587 UserHandle.getAppId(installedInfo.uid), userId); 14588 } 14589 } 14590 } 14591 14592 private void sendSystemPackageUpdatedBroadcastsInternal() { 14593 Bundle extras = new Bundle(2); 14594 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 14595 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14596 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 14597 extras, 0, null, null, null); 14598 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 14599 extras, 0, null, null, null); 14600 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 14601 null, 0, removedPackage, null, null); 14602 } 14603 14604 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 14605 Bundle extras = new Bundle(2); 14606 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 14607 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 14608 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 14609 if (isUpdate || isRemovedPackageSystemUpdate) { 14610 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14611 } 14612 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 14613 if (removedPackage != null) { 14614 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 14615 extras, 0, null, null, removedUsers); 14616 if (dataRemoved && !isRemovedPackageSystemUpdate) { 14617 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 14618 removedPackage, extras, 0, null, null, removedUsers); 14619 } 14620 } 14621 if (removedAppId >= 0) { 14622 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 14623 removedUsers); 14624 } 14625 } 14626 } 14627 14628 /* 14629 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 14630 * flag is not set, the data directory is removed as well. 14631 * make sure this flag is set for partially installed apps. If not its meaningless to 14632 * delete a partially installed application. 14633 */ 14634 private void removePackageDataLI(PackageSetting ps, int[] allUserHandles, 14635 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 14636 String packageName = ps.name; 14637 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 14638 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 14639 // Retrieve object to delete permissions for shared user later on 14640 final PackageSetting deletedPs; 14641 // reader 14642 synchronized (mPackages) { 14643 deletedPs = mSettings.mPackages.get(packageName); 14644 if (outInfo != null) { 14645 outInfo.removedPackage = packageName; 14646 outInfo.removedUsers = deletedPs != null 14647 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 14648 : null; 14649 } 14650 } 14651 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 14652 removeDataDirsLI(ps.volumeUuid, packageName); 14653 if (outInfo != null) { 14654 outInfo.dataRemoved = true; 14655 } 14656 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 14657 } 14658 // writer 14659 synchronized (mPackages) { 14660 if (deletedPs != null) { 14661 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 14662 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 14663 clearDefaultBrowserIfNeeded(packageName); 14664 if (outInfo != null) { 14665 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 14666 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 14667 } 14668 updatePermissionsLPw(deletedPs.name, null, 0); 14669 if (deletedPs.sharedUser != null) { 14670 // Remove permissions associated with package. Since runtime 14671 // permissions are per user we have to kill the removed package 14672 // or packages running under the shared user of the removed 14673 // package if revoking the permissions requested only by the removed 14674 // package is successful and this causes a change in gids. 14675 for (int userId : UserManagerService.getInstance().getUserIds()) { 14676 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 14677 userId); 14678 if (userIdToKill == UserHandle.USER_ALL 14679 || userIdToKill >= UserHandle.USER_SYSTEM) { 14680 // If gids changed for this user, kill all affected packages. 14681 mHandler.post(new Runnable() { 14682 @Override 14683 public void run() { 14684 // This has to happen with no lock held. 14685 killApplication(deletedPs.name, deletedPs.appId, 14686 KILL_APP_REASON_GIDS_CHANGED); 14687 } 14688 }); 14689 break; 14690 } 14691 } 14692 } 14693 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 14694 } 14695 // make sure to preserve per-user disabled state if this removal was just 14696 // a downgrade of a system app to the factory package 14697 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 14698 if (DEBUG_REMOVE) { 14699 Slog.d(TAG, "Propagating install state across downgrade"); 14700 } 14701 for (int userId : allUserHandles) { 14702 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 14703 if (DEBUG_REMOVE) { 14704 Slog.d(TAG, " user " + userId + " => " + installed); 14705 } 14706 ps.setInstalled(installed, userId); 14707 } 14708 } 14709 } 14710 // can downgrade to reader 14711 if (writeSettings) { 14712 // Save settings now 14713 mSettings.writeLPr(); 14714 } 14715 } 14716 if (outInfo != null) { 14717 // A user ID was deleted here. Go through all users and remove it 14718 // from KeyStore. 14719 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 14720 } 14721 } 14722 14723 static boolean locationIsPrivileged(File path) { 14724 try { 14725 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 14726 .getCanonicalPath(); 14727 return path.getCanonicalPath().startsWith(privilegedAppDir); 14728 } catch (IOException e) { 14729 Slog.e(TAG, "Unable to access code path " + path); 14730 } 14731 return false; 14732 } 14733 14734 /* 14735 * Tries to delete system package. 14736 */ 14737 private boolean deleteSystemPackageLI(PackageParser.Package deletedPkg, 14738 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 14739 boolean writeSettings) { 14740 if (deletedPs.parentPackageName != null) { 14741 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 14742 return false; 14743 } 14744 14745 final boolean applyUserRestrictions 14746 = (allUserHandles != null) && (outInfo.origUsers != null); 14747 final PackageSetting disabledPs; 14748 // Confirm if the system package has been updated 14749 // An updated system app can be deleted. This will also have to restore 14750 // the system pkg from system partition 14751 // reader 14752 synchronized (mPackages) { 14753 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 14754 } 14755 14756 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 14757 + " disabledPs=" + disabledPs); 14758 14759 if (disabledPs == null) { 14760 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 14761 return false; 14762 } else if (DEBUG_REMOVE) { 14763 Slog.d(TAG, "Deleting system pkg from data partition"); 14764 } 14765 14766 if (DEBUG_REMOVE) { 14767 if (applyUserRestrictions) { 14768 Slog.d(TAG, "Remembering install states:"); 14769 for (int userId : allUserHandles) { 14770 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 14771 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 14772 } 14773 } 14774 } 14775 14776 // Delete the updated package 14777 outInfo.isRemovedPackageSystemUpdate = true; 14778 if (outInfo.removedChildPackages != null) { 14779 final int childCount = (deletedPs.childPackageNames != null) 14780 ? deletedPs.childPackageNames.size() : 0; 14781 for (int i = 0; i < childCount; i++) { 14782 String childPackageName = deletedPs.childPackageNames.get(i); 14783 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 14784 .contains(childPackageName)) { 14785 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 14786 childPackageName); 14787 if (childInfo != null) { 14788 childInfo.isRemovedPackageSystemUpdate = true; 14789 } 14790 } 14791 } 14792 } 14793 14794 if (disabledPs.versionCode < deletedPs.versionCode) { 14795 // Delete data for downgrades 14796 flags &= ~PackageManager.DELETE_KEEP_DATA; 14797 } else { 14798 // Preserve data by setting flag 14799 flags |= PackageManager.DELETE_KEEP_DATA; 14800 } 14801 14802 boolean ret = deleteInstalledPackageLI(deletedPs, true, flags, allUserHandles, 14803 outInfo, writeSettings, disabledPs.pkg); 14804 if (!ret) { 14805 return false; 14806 } 14807 14808 // writer 14809 synchronized (mPackages) { 14810 // Reinstate the old system package 14811 enableSystemPackageLPw(disabledPs.pkg); 14812 // Remove any native libraries from the upgraded package. 14813 removeNativeBinariesLI(deletedPs); 14814 } 14815 14816 // Install the system package 14817 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 14818 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 14819 if (locationIsPrivileged(disabledPs.codePath)) { 14820 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 14821 } 14822 14823 final PackageParser.Package newPkg; 14824 try { 14825 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 14826 } catch (PackageManagerException e) { 14827 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 14828 + e.getMessage()); 14829 return false; 14830 } 14831 14832 prepareAppDataAfterInstall(newPkg); 14833 14834 // writer 14835 synchronized (mPackages) { 14836 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 14837 14838 // Propagate the permissions state as we do not want to drop on the floor 14839 // runtime permissions. The update permissions method below will take 14840 // care of removing obsolete permissions and grant install permissions. 14841 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 14842 updatePermissionsLPw(newPkg.packageName, newPkg, 14843 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 14844 14845 if (applyUserRestrictions) { 14846 if (DEBUG_REMOVE) { 14847 Slog.d(TAG, "Propagating install state across reinstall"); 14848 } 14849 for (int userId : allUserHandles) { 14850 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 14851 if (DEBUG_REMOVE) { 14852 Slog.d(TAG, " user " + userId + " => " + installed); 14853 } 14854 ps.setInstalled(installed, userId); 14855 14856 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 14857 } 14858 // Regardless of writeSettings we need to ensure that this restriction 14859 // state propagation is persisted 14860 mSettings.writeAllUsersPackageRestrictionsLPr(); 14861 } 14862 // can downgrade to reader here 14863 if (writeSettings) { 14864 mSettings.writeLPr(); 14865 } 14866 } 14867 return true; 14868 } 14869 14870 private boolean deleteInstalledPackageLI(PackageSetting ps, 14871 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 14872 PackageRemovedInfo outInfo, boolean writeSettings, 14873 PackageParser.Package replacingPackage) { 14874 synchronized (mPackages) { 14875 if (outInfo != null) { 14876 outInfo.uid = ps.appId; 14877 } 14878 14879 if (outInfo != null && outInfo.removedChildPackages != null) { 14880 final int childCount = (ps.childPackageNames != null) 14881 ? ps.childPackageNames.size() : 0; 14882 for (int i = 0; i < childCount; i++) { 14883 String childPackageName = ps.childPackageNames.get(i); 14884 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 14885 if (childPs == null) { 14886 return false; 14887 } 14888 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 14889 childPackageName); 14890 if (childInfo != null) { 14891 childInfo.uid = childPs.appId; 14892 } 14893 } 14894 } 14895 } 14896 14897 // Delete package data from internal structures and also remove data if flag is set 14898 removePackageDataLI(ps, allUserHandles, outInfo, flags, writeSettings); 14899 14900 // Delete the child packages data 14901 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14902 for (int i = 0; i < childCount; i++) { 14903 PackageSetting childPs; 14904 synchronized (mPackages) { 14905 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14906 } 14907 if (childPs != null) { 14908 PackageRemovedInfo childOutInfo = (outInfo != null 14909 && outInfo.removedChildPackages != null) 14910 ? outInfo.removedChildPackages.get(childPs.name) : null; 14911 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 14912 && (replacingPackage != null 14913 && !replacingPackage.hasChildPackage(childPs.name)) 14914 ? flags & ~DELETE_KEEP_DATA : flags; 14915 removePackageDataLI(childPs, allUserHandles, childOutInfo, 14916 deleteFlags, writeSettings); 14917 } 14918 } 14919 14920 // Delete application code and resources only for parent packages 14921 if (ps.parentPackageName == null) { 14922 if (deleteCodeAndResources && (outInfo != null)) { 14923 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 14924 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 14925 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 14926 } 14927 } 14928 14929 return true; 14930 } 14931 14932 @Override 14933 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 14934 int userId) { 14935 mContext.enforceCallingOrSelfPermission( 14936 android.Manifest.permission.DELETE_PACKAGES, null); 14937 synchronized (mPackages) { 14938 PackageSetting ps = mSettings.mPackages.get(packageName); 14939 if (ps == null) { 14940 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 14941 return false; 14942 } 14943 if (!ps.getInstalled(userId)) { 14944 // Can't block uninstall for an app that is not installed or enabled. 14945 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 14946 return false; 14947 } 14948 ps.setBlockUninstall(blockUninstall, userId); 14949 mSettings.writePackageRestrictionsLPr(userId); 14950 } 14951 return true; 14952 } 14953 14954 @Override 14955 public boolean getBlockUninstallForUser(String packageName, int userId) { 14956 synchronized (mPackages) { 14957 PackageSetting ps = mSettings.mPackages.get(packageName); 14958 if (ps == null) { 14959 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 14960 return false; 14961 } 14962 return ps.getBlockUninstall(userId); 14963 } 14964 } 14965 14966 @Override 14967 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 14968 int callingUid = Binder.getCallingUid(); 14969 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 14970 throw new SecurityException( 14971 "setRequiredForSystemUser can only be run by the system or root"); 14972 } 14973 synchronized (mPackages) { 14974 PackageSetting ps = mSettings.mPackages.get(packageName); 14975 if (ps == null) { 14976 Log.w(TAG, "Package doesn't exist: " + packageName); 14977 return false; 14978 } 14979 if (systemUserApp) { 14980 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 14981 } else { 14982 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 14983 } 14984 mSettings.writeLPr(); 14985 } 14986 return true; 14987 } 14988 14989 /* 14990 * This method handles package deletion in general 14991 */ 14992 private boolean deletePackageLI(String packageName, UserHandle user, 14993 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 14994 PackageRemovedInfo outInfo, boolean writeSettings, 14995 PackageParser.Package replacingPackage) { 14996 if (packageName == null) { 14997 Slog.w(TAG, "Attempt to delete null packageName."); 14998 return false; 14999 } 15000 15001 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15002 15003 PackageSetting ps; 15004 15005 synchronized (mPackages) { 15006 ps = mSettings.mPackages.get(packageName); 15007 if (ps == null) { 15008 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15009 return false; 15010 } 15011 15012 if (ps.parentPackageName != null && (!isSystemApp(ps) 15013 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15014 if (DEBUG_REMOVE) { 15015 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15016 + ((user == null) ? UserHandle.USER_ALL : user)); 15017 } 15018 final int removedUserId = (user != null) ? user.getIdentifier() 15019 : UserHandle.USER_ALL; 15020 if (!clearPackageStateForUser(ps, removedUserId, outInfo)) { 15021 return false; 15022 } 15023 markPackageUninstalledForUserLPw(ps, user); 15024 scheduleWritePackageRestrictionsLocked(user); 15025 return true; 15026 } 15027 } 15028 15029 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15030 && user.getIdentifier() != UserHandle.USER_ALL)) { 15031 // The caller is asking that the package only be deleted for a single 15032 // user. To do this, we just mark its uninstalled state and delete 15033 // its data. If this is a system app, we only allow this to happen if 15034 // they have set the special DELETE_SYSTEM_APP which requests different 15035 // semantics than normal for uninstalling system apps. 15036 markPackageUninstalledForUserLPw(ps, user); 15037 15038 if (!isSystemApp(ps)) { 15039 // Do not uninstall the APK if an app should be cached 15040 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15041 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15042 // Other user still have this package installed, so all 15043 // we need to do is clear this user's data and save that 15044 // it is uninstalled. 15045 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15046 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 15047 return false; 15048 } 15049 scheduleWritePackageRestrictionsLocked(user); 15050 return true; 15051 } else { 15052 // We need to set it back to 'installed' so the uninstall 15053 // broadcasts will be sent correctly. 15054 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15055 ps.setInstalled(true, user.getIdentifier()); 15056 } 15057 } else { 15058 // This is a system app, so we assume that the 15059 // other users still have this package installed, so all 15060 // we need to do is clear this user's data and save that 15061 // it is uninstalled. 15062 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15063 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 15064 return false; 15065 } 15066 scheduleWritePackageRestrictionsLocked(user); 15067 return true; 15068 } 15069 } 15070 15071 // If we are deleting a composite package for all users, keep track 15072 // of result for each child. 15073 if (ps.childPackageNames != null && outInfo != null) { 15074 synchronized (mPackages) { 15075 final int childCount = ps.childPackageNames.size(); 15076 outInfo.removedChildPackages = new ArrayMap<>(childCount); 15077 for (int i = 0; i < childCount; i++) { 15078 String childPackageName = ps.childPackageNames.get(i); 15079 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 15080 childInfo.removedPackage = childPackageName; 15081 outInfo.removedChildPackages.put(childPackageName, childInfo); 15082 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15083 if (childPs != null) { 15084 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 15085 } 15086 } 15087 } 15088 } 15089 15090 boolean ret = false; 15091 if (isSystemApp(ps)) { 15092 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 15093 // When an updated system application is deleted we delete the existing resources 15094 // as well and fall back to existing code in system partition 15095 ret = deleteSystemPackageLI(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 15096 } else { 15097 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 15098 // Kill application pre-emptively especially for apps on sd. 15099 final boolean killApp = (flags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15100 if (killApp) { 15101 killApplication(packageName, ps.appId, "uninstall pkg"); 15102 } 15103 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, allUserHandles, 15104 outInfo, writeSettings, replacingPackage); 15105 } 15106 15107 // Take a note whether we deleted the package for all users 15108 if (outInfo != null) { 15109 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15110 if (outInfo.removedChildPackages != null) { 15111 synchronized (mPackages) { 15112 final int childCount = outInfo.removedChildPackages.size(); 15113 for (int i = 0; i < childCount; i++) { 15114 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 15115 if (childInfo != null) { 15116 childInfo.removedForAllUsers = mPackages.get( 15117 childInfo.removedPackage) == null; 15118 } 15119 } 15120 } 15121 } 15122 // If we uninstalled an update to a system app there may be some 15123 // child packages that appeared as they are declared in the system 15124 // app but were not declared in the update. 15125 if (isSystemApp(ps)) { 15126 synchronized (mPackages) { 15127 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 15128 final int childCount = (updatedPs.childPackageNames != null) 15129 ? updatedPs.childPackageNames.size() : 0; 15130 for (int i = 0; i < childCount; i++) { 15131 String childPackageName = updatedPs.childPackageNames.get(i); 15132 if (outInfo.removedChildPackages == null 15133 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 15134 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15135 if (childPs == null) { 15136 continue; 15137 } 15138 PackageInstalledInfo installRes = new PackageInstalledInfo(); 15139 installRes.name = childPackageName; 15140 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 15141 installRes.pkg = mPackages.get(childPackageName); 15142 installRes.uid = childPs.pkg.applicationInfo.uid; 15143 if (outInfo.appearedChildPackages == null) { 15144 outInfo.appearedChildPackages = new ArrayMap<>(); 15145 } 15146 outInfo.appearedChildPackages.put(childPackageName, installRes); 15147 } 15148 } 15149 } 15150 } 15151 } 15152 15153 return ret; 15154 } 15155 15156 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 15157 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 15158 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 15159 for (int nextUserId : userIds) { 15160 if (DEBUG_REMOVE) { 15161 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 15162 } 15163 ps.setUserState(nextUserId, COMPONENT_ENABLED_STATE_DEFAULT, 15164 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 15165 false /*hidden*/, false /*suspended*/, null, null, null, 15166 false /*blockUninstall*/, 15167 ps.readUserState(nextUserId).domainVerificationStatus, 0); 15168 } 15169 } 15170 15171 private boolean clearPackageStateForUser(PackageSetting ps, int userId, 15172 PackageRemovedInfo outInfo) { 15173 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 15174 : new int[] {userId}; 15175 for (int nextUserId : userIds) { 15176 if (DEBUG_REMOVE) { 15177 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 15178 + nextUserId); 15179 } 15180 final int flags = StorageManager.FLAG_STORAGE_CE| StorageManager.FLAG_STORAGE_DE; 15181 try { 15182 mInstaller.destroyAppData(ps.volumeUuid, ps.name, nextUserId, flags); 15183 } catch (InstallerException e) { 15184 Slog.w(TAG, "Couldn't remove cache files for package " + ps.name, e); 15185 return false; 15186 } 15187 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 15188 schedulePackageCleaning(ps.name, nextUserId, false); 15189 synchronized (mPackages) { 15190 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 15191 scheduleWritePackageRestrictionsLocked(nextUserId); 15192 } 15193 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 15194 } 15195 } 15196 15197 if (outInfo != null) { 15198 outInfo.removedPackage = ps.name; 15199 outInfo.removedAppId = ps.appId; 15200 outInfo.removedUsers = userIds; 15201 } 15202 15203 return true; 15204 } 15205 15206 private final class ClearStorageConnection implements ServiceConnection { 15207 IMediaContainerService mContainerService; 15208 15209 @Override 15210 public void onServiceConnected(ComponentName name, IBinder service) { 15211 synchronized (this) { 15212 mContainerService = IMediaContainerService.Stub.asInterface(service); 15213 notifyAll(); 15214 } 15215 } 15216 15217 @Override 15218 public void onServiceDisconnected(ComponentName name) { 15219 } 15220 } 15221 15222 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 15223 final boolean mounted; 15224 if (Environment.isExternalStorageEmulated()) { 15225 mounted = true; 15226 } else { 15227 final String status = Environment.getExternalStorageState(); 15228 15229 mounted = status.equals(Environment.MEDIA_MOUNTED) 15230 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 15231 } 15232 15233 if (!mounted) { 15234 return; 15235 } 15236 15237 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 15238 int[] users; 15239 if (userId == UserHandle.USER_ALL) { 15240 users = sUserManager.getUserIds(); 15241 } else { 15242 users = new int[] { userId }; 15243 } 15244 final ClearStorageConnection conn = new ClearStorageConnection(); 15245 if (mContext.bindServiceAsUser( 15246 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 15247 try { 15248 for (int curUser : users) { 15249 long timeout = SystemClock.uptimeMillis() + 5000; 15250 synchronized (conn) { 15251 long now = SystemClock.uptimeMillis(); 15252 while (conn.mContainerService == null && now < timeout) { 15253 try { 15254 conn.wait(timeout - now); 15255 } catch (InterruptedException e) { 15256 } 15257 } 15258 } 15259 if (conn.mContainerService == null) { 15260 return; 15261 } 15262 15263 final UserEnvironment userEnv = new UserEnvironment(curUser); 15264 clearDirectory(conn.mContainerService, 15265 userEnv.buildExternalStorageAppCacheDirs(packageName)); 15266 if (allData) { 15267 clearDirectory(conn.mContainerService, 15268 userEnv.buildExternalStorageAppDataDirs(packageName)); 15269 clearDirectory(conn.mContainerService, 15270 userEnv.buildExternalStorageAppMediaDirs(packageName)); 15271 } 15272 } 15273 } finally { 15274 mContext.unbindService(conn); 15275 } 15276 } 15277 } 15278 15279 @Override 15280 public void clearApplicationProfileData(String packageName) { 15281 enforceSystemOrRoot("Only the system can clear all profile data"); 15282 try { 15283 mInstaller.clearAppProfiles(packageName); 15284 } catch (InstallerException ex) { 15285 Log.e(TAG, "Could not clear profile data of package " + packageName); 15286 } 15287 } 15288 15289 @Override 15290 public void clearApplicationUserData(final String packageName, 15291 final IPackageDataObserver observer, final int userId) { 15292 mContext.enforceCallingOrSelfPermission( 15293 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 15294 15295 enforceCrossUserPermission(Binder.getCallingUid(), userId, 15296 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 15297 15298 final DevicePolicyManagerInternal dpmi = LocalServices 15299 .getService(DevicePolicyManagerInternal.class); 15300 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 15301 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 15302 } 15303 // Queue up an async operation since the package deletion may take a little while. 15304 mHandler.post(new Runnable() { 15305 public void run() { 15306 mHandler.removeCallbacks(this); 15307 final boolean succeeded; 15308 synchronized (mInstallLock) { 15309 succeeded = clearApplicationUserDataLI(packageName, userId); 15310 } 15311 clearExternalStorageDataSync(packageName, userId, true); 15312 if (succeeded) { 15313 // invoke DeviceStorageMonitor's update method to clear any notifications 15314 DeviceStorageMonitorInternal dsm = LocalServices 15315 .getService(DeviceStorageMonitorInternal.class); 15316 if (dsm != null) { 15317 dsm.checkMemory(); 15318 } 15319 } 15320 if(observer != null) { 15321 try { 15322 observer.onRemoveCompleted(packageName, succeeded); 15323 } catch (RemoteException e) { 15324 Log.i(TAG, "Observer no longer exists."); 15325 } 15326 } //end if observer 15327 } //end run 15328 }); 15329 } 15330 15331 private boolean clearApplicationUserDataLI(String packageName, int userId) { 15332 if (packageName == null) { 15333 Slog.w(TAG, "Attempt to delete null packageName."); 15334 return false; 15335 } 15336 15337 // Try finding details about the requested package 15338 PackageParser.Package pkg; 15339 synchronized (mPackages) { 15340 pkg = mPackages.get(packageName); 15341 if (pkg == null) { 15342 final PackageSetting ps = mSettings.mPackages.get(packageName); 15343 if (ps != null) { 15344 pkg = ps.pkg; 15345 } 15346 } 15347 15348 if (pkg == null) { 15349 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15350 return false; 15351 } 15352 15353 PackageSetting ps = (PackageSetting) pkg.mExtras; 15354 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15355 } 15356 15357 // Always delete data directories for package, even if we found no other 15358 // record of app. This helps users recover from UID mismatches without 15359 // resorting to a full data wipe. 15360 // TODO: triage flags as part of 26466827 15361 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15362 try { 15363 mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags); 15364 } catch (InstallerException e) { 15365 Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e); 15366 return false; 15367 } 15368 15369 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15370 removeKeystoreDataIfNeeded(userId, appId); 15371 15372 // Create a native library symlink only if we have native libraries 15373 // and if the native libraries are 32 bit libraries. We do not provide 15374 // this symlink for 64 bit libraries. 15375 if (pkg.applicationInfo.primaryCpuAbi != null && 15376 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 15377 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 15378 try { 15379 mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 15380 nativeLibPath, userId); 15381 } catch (InstallerException e) { 15382 Slog.w(TAG, "Failed linking native library dir", e); 15383 return false; 15384 } 15385 } 15386 15387 return true; 15388 } 15389 15390 /** 15391 * Reverts user permission state changes (permissions and flags) in 15392 * all packages for a given user. 15393 * 15394 * @param userId The device user for which to do a reset. 15395 */ 15396 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 15397 final int packageCount = mPackages.size(); 15398 for (int i = 0; i < packageCount; i++) { 15399 PackageParser.Package pkg = mPackages.valueAt(i); 15400 PackageSetting ps = (PackageSetting) pkg.mExtras; 15401 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15402 } 15403 } 15404 15405 /** 15406 * Reverts user permission state changes (permissions and flags). 15407 * 15408 * @param ps The package for which to reset. 15409 * @param userId The device user for which to do a reset. 15410 */ 15411 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 15412 final PackageSetting ps, final int userId) { 15413 if (ps.pkg == null) { 15414 return; 15415 } 15416 15417 // These are flags that can change base on user actions. 15418 final int userSettableMask = FLAG_PERMISSION_USER_SET 15419 | FLAG_PERMISSION_USER_FIXED 15420 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 15421 | FLAG_PERMISSION_REVIEW_REQUIRED; 15422 15423 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 15424 | FLAG_PERMISSION_POLICY_FIXED; 15425 15426 boolean writeInstallPermissions = false; 15427 boolean writeRuntimePermissions = false; 15428 15429 final int permissionCount = ps.pkg.requestedPermissions.size(); 15430 for (int i = 0; i < permissionCount; i++) { 15431 String permission = ps.pkg.requestedPermissions.get(i); 15432 15433 BasePermission bp = mSettings.mPermissions.get(permission); 15434 if (bp == null) { 15435 continue; 15436 } 15437 15438 // If shared user we just reset the state to which only this app contributed. 15439 if (ps.sharedUser != null) { 15440 boolean used = false; 15441 final int packageCount = ps.sharedUser.packages.size(); 15442 for (int j = 0; j < packageCount; j++) { 15443 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 15444 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 15445 && pkg.pkg.requestedPermissions.contains(permission)) { 15446 used = true; 15447 break; 15448 } 15449 } 15450 if (used) { 15451 continue; 15452 } 15453 } 15454 15455 PermissionsState permissionsState = ps.getPermissionsState(); 15456 15457 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 15458 15459 // Always clear the user settable flags. 15460 final boolean hasInstallState = permissionsState.getInstallPermissionState( 15461 bp.name) != null; 15462 // If permission review is enabled and this is a legacy app, mark the 15463 // permission as requiring a review as this is the initial state. 15464 int flags = 0; 15465 if (Build.PERMISSIONS_REVIEW_REQUIRED 15466 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 15467 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 15468 } 15469 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 15470 if (hasInstallState) { 15471 writeInstallPermissions = true; 15472 } else { 15473 writeRuntimePermissions = true; 15474 } 15475 } 15476 15477 // Below is only runtime permission handling. 15478 if (!bp.isRuntime()) { 15479 continue; 15480 } 15481 15482 // Never clobber system or policy. 15483 if ((oldFlags & policyOrSystemFlags) != 0) { 15484 continue; 15485 } 15486 15487 // If this permission was granted by default, make sure it is. 15488 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 15489 if (permissionsState.grantRuntimePermission(bp, userId) 15490 != PERMISSION_OPERATION_FAILURE) { 15491 writeRuntimePermissions = true; 15492 } 15493 // If permission review is enabled the permissions for a legacy apps 15494 // are represented as constantly granted runtime ones, so don't revoke. 15495 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 15496 // Otherwise, reset the permission. 15497 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 15498 switch (revokeResult) { 15499 case PERMISSION_OPERATION_SUCCESS: { 15500 writeRuntimePermissions = true; 15501 } break; 15502 15503 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 15504 writeRuntimePermissions = true; 15505 final int appId = ps.appId; 15506 mHandler.post(new Runnable() { 15507 @Override 15508 public void run() { 15509 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 15510 } 15511 }); 15512 } break; 15513 } 15514 } 15515 } 15516 15517 // Synchronously write as we are taking permissions away. 15518 if (writeRuntimePermissions) { 15519 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 15520 } 15521 15522 // Synchronously write as we are taking permissions away. 15523 if (writeInstallPermissions) { 15524 mSettings.writeLPr(); 15525 } 15526 } 15527 15528 /** 15529 * Remove entries from the keystore daemon. Will only remove it if the 15530 * {@code appId} is valid. 15531 */ 15532 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 15533 if (appId < 0) { 15534 return; 15535 } 15536 15537 final KeyStore keyStore = KeyStore.getInstance(); 15538 if (keyStore != null) { 15539 if (userId == UserHandle.USER_ALL) { 15540 for (final int individual : sUserManager.getUserIds()) { 15541 keyStore.clearUid(UserHandle.getUid(individual, appId)); 15542 } 15543 } else { 15544 keyStore.clearUid(UserHandle.getUid(userId, appId)); 15545 } 15546 } else { 15547 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 15548 } 15549 } 15550 15551 @Override 15552 public void deleteApplicationCacheFiles(final String packageName, 15553 final IPackageDataObserver observer) { 15554 mContext.enforceCallingOrSelfPermission( 15555 android.Manifest.permission.DELETE_CACHE_FILES, null); 15556 // Queue up an async operation since the package deletion may take a little while. 15557 final int userId = UserHandle.getCallingUserId(); 15558 mHandler.post(new Runnable() { 15559 public void run() { 15560 mHandler.removeCallbacks(this); 15561 final boolean succeded; 15562 synchronized (mInstallLock) { 15563 succeded = deleteApplicationCacheFilesLI(packageName, userId); 15564 } 15565 clearExternalStorageDataSync(packageName, userId, false); 15566 if (observer != null) { 15567 try { 15568 observer.onRemoveCompleted(packageName, succeded); 15569 } catch (RemoteException e) { 15570 Log.i(TAG, "Observer no longer exists."); 15571 } 15572 } //end if observer 15573 } //end run 15574 }); 15575 } 15576 15577 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 15578 if (packageName == null) { 15579 Slog.w(TAG, "Attempt to delete null packageName."); 15580 return false; 15581 } 15582 PackageParser.Package p; 15583 synchronized (mPackages) { 15584 p = mPackages.get(packageName); 15585 } 15586 if (p == null) { 15587 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 15588 return false; 15589 } 15590 final ApplicationInfo applicationInfo = p.applicationInfo; 15591 if (applicationInfo == null) { 15592 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 15593 return false; 15594 } 15595 // TODO: triage flags as part of 26466827 15596 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15597 try { 15598 mInstaller.clearAppData(p.volumeUuid, packageName, userId, 15599 flags | Installer.FLAG_CLEAR_CACHE_ONLY); 15600 } catch (InstallerException e) { 15601 Slog.w(TAG, "Couldn't remove cache files for package " 15602 + packageName + " u" + userId, e); 15603 return false; 15604 } 15605 return true; 15606 } 15607 15608 @Override 15609 public void getPackageSizeInfo(final String packageName, int userHandle, 15610 final IPackageStatsObserver observer) { 15611 mContext.enforceCallingOrSelfPermission( 15612 android.Manifest.permission.GET_PACKAGE_SIZE, null); 15613 if (packageName == null) { 15614 throw new IllegalArgumentException("Attempt to get size of null packageName"); 15615 } 15616 15617 PackageStats stats = new PackageStats(packageName, userHandle); 15618 15619 /* 15620 * Queue up an async operation since the package measurement may take a 15621 * little while. 15622 */ 15623 Message msg = mHandler.obtainMessage(INIT_COPY); 15624 msg.obj = new MeasureParams(stats, observer); 15625 mHandler.sendMessage(msg); 15626 } 15627 15628 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 15629 PackageStats pStats) { 15630 if (packageName == null) { 15631 Slog.w(TAG, "Attempt to get size of null packageName."); 15632 return false; 15633 } 15634 PackageParser.Package p; 15635 boolean dataOnly = false; 15636 String libDirRoot = null; 15637 String asecPath = null; 15638 PackageSetting ps = null; 15639 synchronized (mPackages) { 15640 p = mPackages.get(packageName); 15641 ps = mSettings.mPackages.get(packageName); 15642 if(p == null) { 15643 dataOnly = true; 15644 if((ps == null) || (ps.pkg == null)) { 15645 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 15646 return false; 15647 } 15648 p = ps.pkg; 15649 } 15650 if (ps != null) { 15651 libDirRoot = ps.legacyNativeLibraryPathString; 15652 } 15653 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 15654 final long token = Binder.clearCallingIdentity(); 15655 try { 15656 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 15657 if (secureContainerId != null) { 15658 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 15659 } 15660 } finally { 15661 Binder.restoreCallingIdentity(token); 15662 } 15663 } 15664 } 15665 String publicSrcDir = null; 15666 if(!dataOnly) { 15667 final ApplicationInfo applicationInfo = p.applicationInfo; 15668 if (applicationInfo == null) { 15669 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 15670 return false; 15671 } 15672 if (p.isForwardLocked()) { 15673 publicSrcDir = applicationInfo.getBaseResourcePath(); 15674 } 15675 } 15676 // TODO: extend to measure size of split APKs 15677 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 15678 // not just the first level. 15679 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 15680 // just the primary. 15681 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 15682 15683 String apkPath; 15684 File packageDir = new File(p.codePath); 15685 15686 if (packageDir.isDirectory() && p.canHaveOatDir()) { 15687 apkPath = packageDir.getAbsolutePath(); 15688 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 15689 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 15690 libDirRoot = null; 15691 } 15692 } else { 15693 apkPath = p.baseCodePath; 15694 } 15695 15696 // TODO: triage flags as part of 26466827 15697 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15698 try { 15699 mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath, 15700 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 15701 } catch (InstallerException e) { 15702 return false; 15703 } 15704 15705 // Fix-up for forward-locked applications in ASEC containers. 15706 if (!isExternal(p)) { 15707 pStats.codeSize += pStats.externalCodeSize; 15708 pStats.externalCodeSize = 0L; 15709 } 15710 15711 return true; 15712 } 15713 15714 private int getUidTargetSdkVersionLockedLPr(int uid) { 15715 Object obj = mSettings.getUserIdLPr(uid); 15716 if (obj instanceof SharedUserSetting) { 15717 final SharedUserSetting sus = (SharedUserSetting) obj; 15718 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 15719 final Iterator<PackageSetting> it = sus.packages.iterator(); 15720 while (it.hasNext()) { 15721 final PackageSetting ps = it.next(); 15722 if (ps.pkg != null) { 15723 int v = ps.pkg.applicationInfo.targetSdkVersion; 15724 if (v < vers) vers = v; 15725 } 15726 } 15727 return vers; 15728 } else if (obj instanceof PackageSetting) { 15729 final PackageSetting ps = (PackageSetting) obj; 15730 if (ps.pkg != null) { 15731 return ps.pkg.applicationInfo.targetSdkVersion; 15732 } 15733 } 15734 return Build.VERSION_CODES.CUR_DEVELOPMENT; 15735 } 15736 15737 @Override 15738 public void addPreferredActivity(IntentFilter filter, int match, 15739 ComponentName[] set, ComponentName activity, int userId) { 15740 addPreferredActivityInternal(filter, match, set, activity, true, userId, 15741 "Adding preferred"); 15742 } 15743 15744 private void addPreferredActivityInternal(IntentFilter filter, int match, 15745 ComponentName[] set, ComponentName activity, boolean always, int userId, 15746 String opname) { 15747 // writer 15748 int callingUid = Binder.getCallingUid(); 15749 enforceCrossUserPermission(callingUid, userId, 15750 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 15751 if (filter.countActions() == 0) { 15752 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 15753 return; 15754 } 15755 synchronized (mPackages) { 15756 if (mContext.checkCallingOrSelfPermission( 15757 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15758 != PackageManager.PERMISSION_GRANTED) { 15759 if (getUidTargetSdkVersionLockedLPr(callingUid) 15760 < Build.VERSION_CODES.FROYO) { 15761 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 15762 + callingUid); 15763 return; 15764 } 15765 mContext.enforceCallingOrSelfPermission( 15766 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15767 } 15768 15769 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 15770 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 15771 + userId + ":"); 15772 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15773 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 15774 scheduleWritePackageRestrictionsLocked(userId); 15775 } 15776 } 15777 15778 @Override 15779 public void replacePreferredActivity(IntentFilter filter, int match, 15780 ComponentName[] set, ComponentName activity, int userId) { 15781 if (filter.countActions() != 1) { 15782 throw new IllegalArgumentException( 15783 "replacePreferredActivity expects filter to have only 1 action."); 15784 } 15785 if (filter.countDataAuthorities() != 0 15786 || filter.countDataPaths() != 0 15787 || filter.countDataSchemes() > 1 15788 || filter.countDataTypes() != 0) { 15789 throw new IllegalArgumentException( 15790 "replacePreferredActivity expects filter to have no data authorities, " + 15791 "paths, or types; and at most one scheme."); 15792 } 15793 15794 final int callingUid = Binder.getCallingUid(); 15795 enforceCrossUserPermission(callingUid, userId, 15796 true /* requireFullPermission */, false /* checkShell */, 15797 "replace preferred activity"); 15798 synchronized (mPackages) { 15799 if (mContext.checkCallingOrSelfPermission( 15800 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15801 != PackageManager.PERMISSION_GRANTED) { 15802 if (getUidTargetSdkVersionLockedLPr(callingUid) 15803 < Build.VERSION_CODES.FROYO) { 15804 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 15805 + Binder.getCallingUid()); 15806 return; 15807 } 15808 mContext.enforceCallingOrSelfPermission( 15809 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15810 } 15811 15812 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 15813 if (pir != null) { 15814 // Get all of the existing entries that exactly match this filter. 15815 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 15816 if (existing != null && existing.size() == 1) { 15817 PreferredActivity cur = existing.get(0); 15818 if (DEBUG_PREFERRED) { 15819 Slog.i(TAG, "Checking replace of preferred:"); 15820 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15821 if (!cur.mPref.mAlways) { 15822 Slog.i(TAG, " -- CUR; not mAlways!"); 15823 } else { 15824 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 15825 Slog.i(TAG, " -- CUR: mSet=" 15826 + Arrays.toString(cur.mPref.mSetComponents)); 15827 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 15828 Slog.i(TAG, " -- NEW: mMatch=" 15829 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 15830 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 15831 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 15832 } 15833 } 15834 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 15835 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 15836 && cur.mPref.sameSet(set)) { 15837 // Setting the preferred activity to what it happens to be already 15838 if (DEBUG_PREFERRED) { 15839 Slog.i(TAG, "Replacing with same preferred activity " 15840 + cur.mPref.mShortComponent + " for user " 15841 + userId + ":"); 15842 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15843 } 15844 return; 15845 } 15846 } 15847 15848 if (existing != null) { 15849 if (DEBUG_PREFERRED) { 15850 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 15851 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15852 } 15853 for (int i = 0; i < existing.size(); i++) { 15854 PreferredActivity pa = existing.get(i); 15855 if (DEBUG_PREFERRED) { 15856 Slog.i(TAG, "Removing existing preferred activity " 15857 + pa.mPref.mComponent + ":"); 15858 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 15859 } 15860 pir.removeFilter(pa); 15861 } 15862 } 15863 } 15864 addPreferredActivityInternal(filter, match, set, activity, true, userId, 15865 "Replacing preferred"); 15866 } 15867 } 15868 15869 @Override 15870 public void clearPackagePreferredActivities(String packageName) { 15871 final int uid = Binder.getCallingUid(); 15872 // writer 15873 synchronized (mPackages) { 15874 PackageParser.Package pkg = mPackages.get(packageName); 15875 if (pkg == null || pkg.applicationInfo.uid != uid) { 15876 if (mContext.checkCallingOrSelfPermission( 15877 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15878 != PackageManager.PERMISSION_GRANTED) { 15879 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 15880 < Build.VERSION_CODES.FROYO) { 15881 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 15882 + Binder.getCallingUid()); 15883 return; 15884 } 15885 mContext.enforceCallingOrSelfPermission( 15886 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15887 } 15888 } 15889 15890 int user = UserHandle.getCallingUserId(); 15891 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 15892 scheduleWritePackageRestrictionsLocked(user); 15893 } 15894 } 15895 } 15896 15897 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15898 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 15899 ArrayList<PreferredActivity> removed = null; 15900 boolean changed = false; 15901 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15902 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 15903 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15904 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 15905 continue; 15906 } 15907 Iterator<PreferredActivity> it = pir.filterIterator(); 15908 while (it.hasNext()) { 15909 PreferredActivity pa = it.next(); 15910 // Mark entry for removal only if it matches the package name 15911 // and the entry is of type "always". 15912 if (packageName == null || 15913 (pa.mPref.mComponent.getPackageName().equals(packageName) 15914 && pa.mPref.mAlways)) { 15915 if (removed == null) { 15916 removed = new ArrayList<PreferredActivity>(); 15917 } 15918 removed.add(pa); 15919 } 15920 } 15921 if (removed != null) { 15922 for (int j=0; j<removed.size(); j++) { 15923 PreferredActivity pa = removed.get(j); 15924 pir.removeFilter(pa); 15925 } 15926 changed = true; 15927 } 15928 } 15929 return changed; 15930 } 15931 15932 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15933 private void clearIntentFilterVerificationsLPw(int userId) { 15934 final int packageCount = mPackages.size(); 15935 for (int i = 0; i < packageCount; i++) { 15936 PackageParser.Package pkg = mPackages.valueAt(i); 15937 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 15938 } 15939 } 15940 15941 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15942 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 15943 if (userId == UserHandle.USER_ALL) { 15944 if (mSettings.removeIntentFilterVerificationLPw(packageName, 15945 sUserManager.getUserIds())) { 15946 for (int oneUserId : sUserManager.getUserIds()) { 15947 scheduleWritePackageRestrictionsLocked(oneUserId); 15948 } 15949 } 15950 } else { 15951 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 15952 scheduleWritePackageRestrictionsLocked(userId); 15953 } 15954 } 15955 } 15956 15957 void clearDefaultBrowserIfNeeded(String packageName) { 15958 for (int oneUserId : sUserManager.getUserIds()) { 15959 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 15960 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 15961 if (packageName.equals(defaultBrowserPackageName)) { 15962 setDefaultBrowserPackageName(null, oneUserId); 15963 } 15964 } 15965 } 15966 15967 @Override 15968 public void resetApplicationPreferences(int userId) { 15969 mContext.enforceCallingOrSelfPermission( 15970 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15971 // writer 15972 synchronized (mPackages) { 15973 final long identity = Binder.clearCallingIdentity(); 15974 try { 15975 clearPackagePreferredActivitiesLPw(null, userId); 15976 mSettings.applyDefaultPreferredAppsLPw(this, userId); 15977 // TODO: We have to reset the default SMS and Phone. This requires 15978 // significant refactoring to keep all default apps in the package 15979 // manager (cleaner but more work) or have the services provide 15980 // callbacks to the package manager to request a default app reset. 15981 applyFactoryDefaultBrowserLPw(userId); 15982 clearIntentFilterVerificationsLPw(userId); 15983 primeDomainVerificationsLPw(userId); 15984 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 15985 scheduleWritePackageRestrictionsLocked(userId); 15986 } finally { 15987 Binder.restoreCallingIdentity(identity); 15988 } 15989 } 15990 } 15991 15992 @Override 15993 public int getPreferredActivities(List<IntentFilter> outFilters, 15994 List<ComponentName> outActivities, String packageName) { 15995 15996 int num = 0; 15997 final int userId = UserHandle.getCallingUserId(); 15998 // reader 15999 synchronized (mPackages) { 16000 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16001 if (pir != null) { 16002 final Iterator<PreferredActivity> it = pir.filterIterator(); 16003 while (it.hasNext()) { 16004 final PreferredActivity pa = it.next(); 16005 if (packageName == null 16006 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16007 && pa.mPref.mAlways)) { 16008 if (outFilters != null) { 16009 outFilters.add(new IntentFilter(pa)); 16010 } 16011 if (outActivities != null) { 16012 outActivities.add(pa.mPref.mComponent); 16013 } 16014 } 16015 } 16016 } 16017 } 16018 16019 return num; 16020 } 16021 16022 @Override 16023 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16024 int userId) { 16025 int callingUid = Binder.getCallingUid(); 16026 if (callingUid != Process.SYSTEM_UID) { 16027 throw new SecurityException( 16028 "addPersistentPreferredActivity can only be run by the system"); 16029 } 16030 if (filter.countActions() == 0) { 16031 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16032 return; 16033 } 16034 synchronized (mPackages) { 16035 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16036 ":"); 16037 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16038 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16039 new PersistentPreferredActivity(filter, activity)); 16040 scheduleWritePackageRestrictionsLocked(userId); 16041 } 16042 } 16043 16044 @Override 16045 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16046 int callingUid = Binder.getCallingUid(); 16047 if (callingUid != Process.SYSTEM_UID) { 16048 throw new SecurityException( 16049 "clearPackagePersistentPreferredActivities can only be run by the system"); 16050 } 16051 ArrayList<PersistentPreferredActivity> removed = null; 16052 boolean changed = false; 16053 synchronized (mPackages) { 16054 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16055 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16056 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16057 .valueAt(i); 16058 if (userId != thisUserId) { 16059 continue; 16060 } 16061 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16062 while (it.hasNext()) { 16063 PersistentPreferredActivity ppa = it.next(); 16064 // Mark entry for removal only if it matches the package name. 16065 if (ppa.mComponent.getPackageName().equals(packageName)) { 16066 if (removed == null) { 16067 removed = new ArrayList<PersistentPreferredActivity>(); 16068 } 16069 removed.add(ppa); 16070 } 16071 } 16072 if (removed != null) { 16073 for (int j=0; j<removed.size(); j++) { 16074 PersistentPreferredActivity ppa = removed.get(j); 16075 ppir.removeFilter(ppa); 16076 } 16077 changed = true; 16078 } 16079 } 16080 16081 if (changed) { 16082 scheduleWritePackageRestrictionsLocked(userId); 16083 } 16084 } 16085 } 16086 16087 /** 16088 * Common machinery for picking apart a restored XML blob and passing 16089 * it to a caller-supplied functor to be applied to the running system. 16090 */ 16091 private void restoreFromXml(XmlPullParser parser, int userId, 16092 String expectedStartTag, BlobXmlRestorer functor) 16093 throws IOException, XmlPullParserException { 16094 int type; 16095 while ((type = parser.next()) != XmlPullParser.START_TAG 16096 && type != XmlPullParser.END_DOCUMENT) { 16097 } 16098 if (type != XmlPullParser.START_TAG) { 16099 // oops didn't find a start tag?! 16100 if (DEBUG_BACKUP) { 16101 Slog.e(TAG, "Didn't find start tag during restore"); 16102 } 16103 return; 16104 } 16105Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16106 // this is supposed to be TAG_PREFERRED_BACKUP 16107 if (!expectedStartTag.equals(parser.getName())) { 16108 if (DEBUG_BACKUP) { 16109 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16110 } 16111 return; 16112 } 16113 16114 // skip interfering stuff, then we're aligned with the backing implementation 16115 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16116Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16117 functor.apply(parser, userId); 16118 } 16119 16120 private interface BlobXmlRestorer { 16121 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16122 } 16123 16124 /** 16125 * Non-Binder method, support for the backup/restore mechanism: write the 16126 * full set of preferred activities in its canonical XML format. Returns the 16127 * XML output as a byte array, or null if there is none. 16128 */ 16129 @Override 16130 public byte[] getPreferredActivityBackup(int userId) { 16131 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16132 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16133 } 16134 16135 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16136 try { 16137 final XmlSerializer serializer = new FastXmlSerializer(); 16138 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16139 serializer.startDocument(null, true); 16140 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16141 16142 synchronized (mPackages) { 16143 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16144 } 16145 16146 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16147 serializer.endDocument(); 16148 serializer.flush(); 16149 } catch (Exception e) { 16150 if (DEBUG_BACKUP) { 16151 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16152 } 16153 return null; 16154 } 16155 16156 return dataStream.toByteArray(); 16157 } 16158 16159 @Override 16160 public void restorePreferredActivities(byte[] backup, int userId) { 16161 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16162 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16163 } 16164 16165 try { 16166 final XmlPullParser parser = Xml.newPullParser(); 16167 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16168 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16169 new BlobXmlRestorer() { 16170 @Override 16171 public void apply(XmlPullParser parser, int userId) 16172 throws XmlPullParserException, IOException { 16173 synchronized (mPackages) { 16174 mSettings.readPreferredActivitiesLPw(parser, userId); 16175 } 16176 } 16177 } ); 16178 } catch (Exception e) { 16179 if (DEBUG_BACKUP) { 16180 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16181 } 16182 } 16183 } 16184 16185 /** 16186 * Non-Binder method, support for the backup/restore mechanism: write the 16187 * default browser (etc) settings in its canonical XML format. Returns the default 16188 * browser XML representation as a byte array, or null if there is none. 16189 */ 16190 @Override 16191 public byte[] getDefaultAppsBackup(int userId) { 16192 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16193 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 16194 } 16195 16196 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16197 try { 16198 final XmlSerializer serializer = new FastXmlSerializer(); 16199 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16200 serializer.startDocument(null, true); 16201 serializer.startTag(null, TAG_DEFAULT_APPS); 16202 16203 synchronized (mPackages) { 16204 mSettings.writeDefaultAppsLPr(serializer, userId); 16205 } 16206 16207 serializer.endTag(null, TAG_DEFAULT_APPS); 16208 serializer.endDocument(); 16209 serializer.flush(); 16210 } catch (Exception e) { 16211 if (DEBUG_BACKUP) { 16212 Slog.e(TAG, "Unable to write default apps for backup", e); 16213 } 16214 return null; 16215 } 16216 16217 return dataStream.toByteArray(); 16218 } 16219 16220 @Override 16221 public void restoreDefaultApps(byte[] backup, int userId) { 16222 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16223 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16224 } 16225 16226 try { 16227 final XmlPullParser parser = Xml.newPullParser(); 16228 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16229 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16230 new BlobXmlRestorer() { 16231 @Override 16232 public void apply(XmlPullParser parser, int userId) 16233 throws XmlPullParserException, IOException { 16234 synchronized (mPackages) { 16235 mSettings.readDefaultAppsLPw(parser, userId); 16236 } 16237 } 16238 } ); 16239 } catch (Exception e) { 16240 if (DEBUG_BACKUP) { 16241 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16242 } 16243 } 16244 } 16245 16246 @Override 16247 public byte[] getIntentFilterVerificationBackup(int userId) { 16248 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16249 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 16250 } 16251 16252 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16253 try { 16254 final XmlSerializer serializer = new FastXmlSerializer(); 16255 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16256 serializer.startDocument(null, true); 16257 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 16258 16259 synchronized (mPackages) { 16260 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 16261 } 16262 16263 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 16264 serializer.endDocument(); 16265 serializer.flush(); 16266 } catch (Exception e) { 16267 if (DEBUG_BACKUP) { 16268 Slog.e(TAG, "Unable to write default apps for backup", e); 16269 } 16270 return null; 16271 } 16272 16273 return dataStream.toByteArray(); 16274 } 16275 16276 @Override 16277 public void restoreIntentFilterVerification(byte[] backup, int userId) { 16278 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16279 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16280 } 16281 16282 try { 16283 final XmlPullParser parser = Xml.newPullParser(); 16284 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16285 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 16286 new BlobXmlRestorer() { 16287 @Override 16288 public void apply(XmlPullParser parser, int userId) 16289 throws XmlPullParserException, IOException { 16290 synchronized (mPackages) { 16291 mSettings.readAllDomainVerificationsLPr(parser, userId); 16292 mSettings.writeLPr(); 16293 } 16294 } 16295 } ); 16296 } catch (Exception e) { 16297 if (DEBUG_BACKUP) { 16298 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16299 } 16300 } 16301 } 16302 16303 @Override 16304 public byte[] getPermissionGrantBackup(int userId) { 16305 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16306 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 16307 } 16308 16309 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16310 try { 16311 final XmlSerializer serializer = new FastXmlSerializer(); 16312 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16313 serializer.startDocument(null, true); 16314 serializer.startTag(null, TAG_PERMISSION_BACKUP); 16315 16316 synchronized (mPackages) { 16317 serializeRuntimePermissionGrantsLPr(serializer, userId); 16318 } 16319 16320 serializer.endTag(null, TAG_PERMISSION_BACKUP); 16321 serializer.endDocument(); 16322 serializer.flush(); 16323 } catch (Exception e) { 16324 if (DEBUG_BACKUP) { 16325 Slog.e(TAG, "Unable to write default apps for backup", e); 16326 } 16327 return null; 16328 } 16329 16330 return dataStream.toByteArray(); 16331 } 16332 16333 @Override 16334 public void restorePermissionGrants(byte[] backup, int userId) { 16335 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16336 throw new SecurityException("Only the system may call restorePermissionGrants()"); 16337 } 16338 16339 try { 16340 final XmlPullParser parser = Xml.newPullParser(); 16341 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16342 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 16343 new BlobXmlRestorer() { 16344 @Override 16345 public void apply(XmlPullParser parser, int userId) 16346 throws XmlPullParserException, IOException { 16347 synchronized (mPackages) { 16348 processRestoredPermissionGrantsLPr(parser, userId); 16349 } 16350 } 16351 } ); 16352 } catch (Exception e) { 16353 if (DEBUG_BACKUP) { 16354 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16355 } 16356 } 16357 } 16358 16359 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 16360 throws IOException { 16361 serializer.startTag(null, TAG_ALL_GRANTS); 16362 16363 final int N = mSettings.mPackages.size(); 16364 for (int i = 0; i < N; i++) { 16365 final PackageSetting ps = mSettings.mPackages.valueAt(i); 16366 boolean pkgGrantsKnown = false; 16367 16368 PermissionsState packagePerms = ps.getPermissionsState(); 16369 16370 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 16371 final int grantFlags = state.getFlags(); 16372 // only look at grants that are not system/policy fixed 16373 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 16374 final boolean isGranted = state.isGranted(); 16375 // And only back up the user-twiddled state bits 16376 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 16377 final String packageName = mSettings.mPackages.keyAt(i); 16378 if (!pkgGrantsKnown) { 16379 serializer.startTag(null, TAG_GRANT); 16380 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 16381 pkgGrantsKnown = true; 16382 } 16383 16384 final boolean userSet = 16385 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 16386 final boolean userFixed = 16387 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 16388 final boolean revoke = 16389 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 16390 16391 serializer.startTag(null, TAG_PERMISSION); 16392 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 16393 if (isGranted) { 16394 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 16395 } 16396 if (userSet) { 16397 serializer.attribute(null, ATTR_USER_SET, "true"); 16398 } 16399 if (userFixed) { 16400 serializer.attribute(null, ATTR_USER_FIXED, "true"); 16401 } 16402 if (revoke) { 16403 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 16404 } 16405 serializer.endTag(null, TAG_PERMISSION); 16406 } 16407 } 16408 } 16409 16410 if (pkgGrantsKnown) { 16411 serializer.endTag(null, TAG_GRANT); 16412 } 16413 } 16414 16415 serializer.endTag(null, TAG_ALL_GRANTS); 16416 } 16417 16418 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 16419 throws XmlPullParserException, IOException { 16420 String pkgName = null; 16421 int outerDepth = parser.getDepth(); 16422 int type; 16423 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 16424 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 16425 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 16426 continue; 16427 } 16428 16429 final String tagName = parser.getName(); 16430 if (tagName.equals(TAG_GRANT)) { 16431 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 16432 if (DEBUG_BACKUP) { 16433 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 16434 } 16435 } else if (tagName.equals(TAG_PERMISSION)) { 16436 16437 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 16438 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 16439 16440 int newFlagSet = 0; 16441 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 16442 newFlagSet |= FLAG_PERMISSION_USER_SET; 16443 } 16444 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 16445 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 16446 } 16447 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 16448 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 16449 } 16450 if (DEBUG_BACKUP) { 16451 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 16452 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 16453 } 16454 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16455 if (ps != null) { 16456 // Already installed so we apply the grant immediately 16457 if (DEBUG_BACKUP) { 16458 Slog.v(TAG, " + already installed; applying"); 16459 } 16460 PermissionsState perms = ps.getPermissionsState(); 16461 BasePermission bp = mSettings.mPermissions.get(permName); 16462 if (bp != null) { 16463 if (isGranted) { 16464 perms.grantRuntimePermission(bp, userId); 16465 } 16466 if (newFlagSet != 0) { 16467 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 16468 } 16469 } 16470 } else { 16471 // Need to wait for post-restore install to apply the grant 16472 if (DEBUG_BACKUP) { 16473 Slog.v(TAG, " - not yet installed; saving for later"); 16474 } 16475 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 16476 isGranted, newFlagSet, userId); 16477 } 16478 } else { 16479 PackageManagerService.reportSettingsProblem(Log.WARN, 16480 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 16481 XmlUtils.skipCurrentTag(parser); 16482 } 16483 } 16484 16485 scheduleWriteSettingsLocked(); 16486 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16487 } 16488 16489 @Override 16490 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 16491 int sourceUserId, int targetUserId, int flags) { 16492 mContext.enforceCallingOrSelfPermission( 16493 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16494 int callingUid = Binder.getCallingUid(); 16495 enforceOwnerRights(ownerPackage, callingUid); 16496 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16497 if (intentFilter.countActions() == 0) { 16498 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 16499 return; 16500 } 16501 synchronized (mPackages) { 16502 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 16503 ownerPackage, targetUserId, flags); 16504 CrossProfileIntentResolver resolver = 16505 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16506 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 16507 // We have all those whose filter is equal. Now checking if the rest is equal as well. 16508 if (existing != null) { 16509 int size = existing.size(); 16510 for (int i = 0; i < size; i++) { 16511 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 16512 return; 16513 } 16514 } 16515 } 16516 resolver.addFilter(newFilter); 16517 scheduleWritePackageRestrictionsLocked(sourceUserId); 16518 } 16519 } 16520 16521 @Override 16522 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 16523 mContext.enforceCallingOrSelfPermission( 16524 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16525 int callingUid = Binder.getCallingUid(); 16526 enforceOwnerRights(ownerPackage, callingUid); 16527 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16528 synchronized (mPackages) { 16529 CrossProfileIntentResolver resolver = 16530 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16531 ArraySet<CrossProfileIntentFilter> set = 16532 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 16533 for (CrossProfileIntentFilter filter : set) { 16534 if (filter.getOwnerPackage().equals(ownerPackage)) { 16535 resolver.removeFilter(filter); 16536 } 16537 } 16538 scheduleWritePackageRestrictionsLocked(sourceUserId); 16539 } 16540 } 16541 16542 // Enforcing that callingUid is owning pkg on userId 16543 private void enforceOwnerRights(String pkg, int callingUid) { 16544 // The system owns everything. 16545 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 16546 return; 16547 } 16548 int callingUserId = UserHandle.getUserId(callingUid); 16549 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 16550 if (pi == null) { 16551 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 16552 + callingUserId); 16553 } 16554 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 16555 throw new SecurityException("Calling uid " + callingUid 16556 + " does not own package " + pkg); 16557 } 16558 } 16559 16560 @Override 16561 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 16562 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 16563 } 16564 16565 private Intent getHomeIntent() { 16566 Intent intent = new Intent(Intent.ACTION_MAIN); 16567 intent.addCategory(Intent.CATEGORY_HOME); 16568 return intent; 16569 } 16570 16571 private IntentFilter getHomeFilter() { 16572 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 16573 filter.addCategory(Intent.CATEGORY_HOME); 16574 filter.addCategory(Intent.CATEGORY_DEFAULT); 16575 return filter; 16576 } 16577 16578 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 16579 int userId) { 16580 Intent intent = getHomeIntent(); 16581 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 16582 PackageManager.GET_META_DATA, userId); 16583 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 16584 true, false, false, userId); 16585 16586 allHomeCandidates.clear(); 16587 if (list != null) { 16588 for (ResolveInfo ri : list) { 16589 allHomeCandidates.add(ri); 16590 } 16591 } 16592 return (preferred == null || preferred.activityInfo == null) 16593 ? null 16594 : new ComponentName(preferred.activityInfo.packageName, 16595 preferred.activityInfo.name); 16596 } 16597 16598 @Override 16599 public void setHomeActivity(ComponentName comp, int userId) { 16600 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 16601 getHomeActivitiesAsUser(homeActivities, userId); 16602 16603 boolean found = false; 16604 16605 final int size = homeActivities.size(); 16606 final ComponentName[] set = new ComponentName[size]; 16607 for (int i = 0; i < size; i++) { 16608 final ResolveInfo candidate = homeActivities.get(i); 16609 final ActivityInfo info = candidate.activityInfo; 16610 final ComponentName activityName = new ComponentName(info.packageName, info.name); 16611 set[i] = activityName; 16612 if (!found && activityName.equals(comp)) { 16613 found = true; 16614 } 16615 } 16616 if (!found) { 16617 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 16618 + userId); 16619 } 16620 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 16621 set, comp, userId); 16622 } 16623 16624 @Override 16625 public void setApplicationEnabledSetting(String appPackageName, 16626 int newState, int flags, int userId, String callingPackage) { 16627 if (!sUserManager.exists(userId)) return; 16628 if (callingPackage == null) { 16629 callingPackage = Integer.toString(Binder.getCallingUid()); 16630 } 16631 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 16632 } 16633 16634 @Override 16635 public void setComponentEnabledSetting(ComponentName componentName, 16636 int newState, int flags, int userId) { 16637 if (!sUserManager.exists(userId)) return; 16638 setEnabledSetting(componentName.getPackageName(), 16639 componentName.getClassName(), newState, flags, userId, null); 16640 } 16641 16642 private void setEnabledSetting(final String packageName, String className, int newState, 16643 final int flags, int userId, String callingPackage) { 16644 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 16645 || newState == COMPONENT_ENABLED_STATE_ENABLED 16646 || newState == COMPONENT_ENABLED_STATE_DISABLED 16647 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 16648 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 16649 throw new IllegalArgumentException("Invalid new component state: " 16650 + newState); 16651 } 16652 PackageSetting pkgSetting; 16653 final int uid = Binder.getCallingUid(); 16654 final int permission = mContext.checkCallingOrSelfPermission( 16655 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 16656 enforceCrossUserPermission(uid, userId, 16657 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 16658 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 16659 boolean sendNow = false; 16660 boolean isApp = (className == null); 16661 String componentName = isApp ? packageName : className; 16662 int packageUid = -1; 16663 ArrayList<String> components; 16664 16665 // writer 16666 synchronized (mPackages) { 16667 pkgSetting = mSettings.mPackages.get(packageName); 16668 if (pkgSetting == null) { 16669 if (className == null) { 16670 throw new IllegalArgumentException("Unknown package: " + packageName); 16671 } 16672 throw new IllegalArgumentException( 16673 "Unknown component: " + packageName + "/" + className); 16674 } 16675 // Allow root and verify that userId is not being specified by a different user 16676 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 16677 throw new SecurityException( 16678 "Permission Denial: attempt to change component state from pid=" 16679 + Binder.getCallingPid() 16680 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 16681 } 16682 if (className == null) { 16683 // We're dealing with an application/package level state change 16684 if (pkgSetting.getEnabled(userId) == newState) { 16685 // Nothing to do 16686 return; 16687 } 16688 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 16689 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 16690 // Don't care about who enables an app. 16691 callingPackage = null; 16692 } 16693 pkgSetting.setEnabled(newState, userId, callingPackage); 16694 // pkgSetting.pkg.mSetEnabled = newState; 16695 } else { 16696 // We're dealing with a component level state change 16697 // First, verify that this is a valid class name. 16698 PackageParser.Package pkg = pkgSetting.pkg; 16699 if (pkg == null || !pkg.hasComponentClassName(className)) { 16700 if (pkg != null && 16701 pkg.applicationInfo.targetSdkVersion >= 16702 Build.VERSION_CODES.JELLY_BEAN) { 16703 throw new IllegalArgumentException("Component class " + className 16704 + " does not exist in " + packageName); 16705 } else { 16706 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 16707 + className + " does not exist in " + packageName); 16708 } 16709 } 16710 switch (newState) { 16711 case COMPONENT_ENABLED_STATE_ENABLED: 16712 if (!pkgSetting.enableComponentLPw(className, userId)) { 16713 return; 16714 } 16715 break; 16716 case COMPONENT_ENABLED_STATE_DISABLED: 16717 if (!pkgSetting.disableComponentLPw(className, userId)) { 16718 return; 16719 } 16720 break; 16721 case COMPONENT_ENABLED_STATE_DEFAULT: 16722 if (!pkgSetting.restoreComponentLPw(className, userId)) { 16723 return; 16724 } 16725 break; 16726 default: 16727 Slog.e(TAG, "Invalid new component state: " + newState); 16728 return; 16729 } 16730 } 16731 scheduleWritePackageRestrictionsLocked(userId); 16732 components = mPendingBroadcasts.get(userId, packageName); 16733 final boolean newPackage = components == null; 16734 if (newPackage) { 16735 components = new ArrayList<String>(); 16736 } 16737 if (!components.contains(componentName)) { 16738 components.add(componentName); 16739 } 16740 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 16741 sendNow = true; 16742 // Purge entry from pending broadcast list if another one exists already 16743 // since we are sending one right away. 16744 mPendingBroadcasts.remove(userId, packageName); 16745 } else { 16746 if (newPackage) { 16747 mPendingBroadcasts.put(userId, packageName, components); 16748 } 16749 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 16750 // Schedule a message 16751 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 16752 } 16753 } 16754 } 16755 16756 long callingId = Binder.clearCallingIdentity(); 16757 try { 16758 if (sendNow) { 16759 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 16760 sendPackageChangedBroadcast(packageName, 16761 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 16762 } 16763 } finally { 16764 Binder.restoreCallingIdentity(callingId); 16765 } 16766 } 16767 16768 @Override 16769 public void flushPackageRestrictionsAsUser(int userId) { 16770 if (!sUserManager.exists(userId)) { 16771 return; 16772 } 16773 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 16774 false /* checkShell */, "flushPackageRestrictions"); 16775 synchronized (mPackages) { 16776 mSettings.writePackageRestrictionsLPr(userId); 16777 mDirtyUsers.remove(userId); 16778 if (mDirtyUsers.isEmpty()) { 16779 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 16780 } 16781 } 16782 } 16783 16784 private void sendPackageChangedBroadcast(String packageName, 16785 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 16786 if (DEBUG_INSTALL) 16787 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 16788 + componentNames); 16789 Bundle extras = new Bundle(4); 16790 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 16791 String nameList[] = new String[componentNames.size()]; 16792 componentNames.toArray(nameList); 16793 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 16794 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 16795 extras.putInt(Intent.EXTRA_UID, packageUid); 16796 // If this is not reporting a change of the overall package, then only send it 16797 // to registered receivers. We don't want to launch a swath of apps for every 16798 // little component state change. 16799 final int flags = !componentNames.contains(packageName) 16800 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 16801 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 16802 new int[] {UserHandle.getUserId(packageUid)}); 16803 } 16804 16805 @Override 16806 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 16807 if (!sUserManager.exists(userId)) return; 16808 final int uid = Binder.getCallingUid(); 16809 final int permission = mContext.checkCallingOrSelfPermission( 16810 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 16811 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 16812 enforceCrossUserPermission(uid, userId, 16813 true /* requireFullPermission */, true /* checkShell */, "stop package"); 16814 // writer 16815 synchronized (mPackages) { 16816 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 16817 allowedByPermission, uid, userId)) { 16818 scheduleWritePackageRestrictionsLocked(userId); 16819 } 16820 } 16821 } 16822 16823 @Override 16824 public String getInstallerPackageName(String packageName) { 16825 // reader 16826 synchronized (mPackages) { 16827 return mSettings.getInstallerPackageNameLPr(packageName); 16828 } 16829 } 16830 16831 @Override 16832 public int getApplicationEnabledSetting(String packageName, int userId) { 16833 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 16834 int uid = Binder.getCallingUid(); 16835 enforceCrossUserPermission(uid, userId, 16836 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 16837 // reader 16838 synchronized (mPackages) { 16839 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 16840 } 16841 } 16842 16843 @Override 16844 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 16845 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 16846 int uid = Binder.getCallingUid(); 16847 enforceCrossUserPermission(uid, userId, 16848 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 16849 // reader 16850 synchronized (mPackages) { 16851 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 16852 } 16853 } 16854 16855 @Override 16856 public void enterSafeMode() { 16857 enforceSystemOrRoot("Only the system can request entering safe mode"); 16858 16859 if (!mSystemReady) { 16860 mSafeMode = true; 16861 } 16862 } 16863 16864 @Override 16865 public void systemReady() { 16866 mSystemReady = true; 16867 16868 // Read the compatibilty setting when the system is ready. 16869 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 16870 mContext.getContentResolver(), 16871 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 16872 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 16873 if (DEBUG_SETTINGS) { 16874 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 16875 } 16876 16877 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 16878 16879 synchronized (mPackages) { 16880 // Verify that all of the preferred activity components actually 16881 // exist. It is possible for applications to be updated and at 16882 // that point remove a previously declared activity component that 16883 // had been set as a preferred activity. We try to clean this up 16884 // the next time we encounter that preferred activity, but it is 16885 // possible for the user flow to never be able to return to that 16886 // situation so here we do a sanity check to make sure we haven't 16887 // left any junk around. 16888 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 16889 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16890 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16891 removed.clear(); 16892 for (PreferredActivity pa : pir.filterSet()) { 16893 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 16894 removed.add(pa); 16895 } 16896 } 16897 if (removed.size() > 0) { 16898 for (int r=0; r<removed.size(); r++) { 16899 PreferredActivity pa = removed.get(r); 16900 Slog.w(TAG, "Removing dangling preferred activity: " 16901 + pa.mPref.mComponent); 16902 pir.removeFilter(pa); 16903 } 16904 mSettings.writePackageRestrictionsLPr( 16905 mSettings.mPreferredActivities.keyAt(i)); 16906 } 16907 } 16908 16909 for (int userId : UserManagerService.getInstance().getUserIds()) { 16910 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 16911 grantPermissionsUserIds = ArrayUtils.appendInt( 16912 grantPermissionsUserIds, userId); 16913 } 16914 } 16915 } 16916 sUserManager.systemReady(); 16917 16918 // If we upgraded grant all default permissions before kicking off. 16919 for (int userId : grantPermissionsUserIds) { 16920 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 16921 } 16922 16923 // Kick off any messages waiting for system ready 16924 if (mPostSystemReadyMessages != null) { 16925 for (Message msg : mPostSystemReadyMessages) { 16926 msg.sendToTarget(); 16927 } 16928 mPostSystemReadyMessages = null; 16929 } 16930 16931 // Watch for external volumes that come and go over time 16932 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16933 storage.registerListener(mStorageListener); 16934 16935 mInstallerService.systemReady(); 16936 mPackageDexOptimizer.systemReady(); 16937 16938 MountServiceInternal mountServiceInternal = LocalServices.getService( 16939 MountServiceInternal.class); 16940 mountServiceInternal.addExternalStoragePolicy( 16941 new MountServiceInternal.ExternalStorageMountPolicy() { 16942 @Override 16943 public int getMountMode(int uid, String packageName) { 16944 if (Process.isIsolated(uid)) { 16945 return Zygote.MOUNT_EXTERNAL_NONE; 16946 } 16947 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 16948 return Zygote.MOUNT_EXTERNAL_DEFAULT; 16949 } 16950 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 16951 return Zygote.MOUNT_EXTERNAL_DEFAULT; 16952 } 16953 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 16954 return Zygote.MOUNT_EXTERNAL_READ; 16955 } 16956 return Zygote.MOUNT_EXTERNAL_WRITE; 16957 } 16958 16959 @Override 16960 public boolean hasExternalStorage(int uid, String packageName) { 16961 return true; 16962 } 16963 }); 16964 } 16965 16966 @Override 16967 public boolean isSafeMode() { 16968 return mSafeMode; 16969 } 16970 16971 @Override 16972 public boolean hasSystemUidErrors() { 16973 return mHasSystemUidErrors; 16974 } 16975 16976 static String arrayToString(int[] array) { 16977 StringBuffer buf = new StringBuffer(128); 16978 buf.append('['); 16979 if (array != null) { 16980 for (int i=0; i<array.length; i++) { 16981 if (i > 0) buf.append(", "); 16982 buf.append(array[i]); 16983 } 16984 } 16985 buf.append(']'); 16986 return buf.toString(); 16987 } 16988 16989 static class DumpState { 16990 public static final int DUMP_LIBS = 1 << 0; 16991 public static final int DUMP_FEATURES = 1 << 1; 16992 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 16993 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 16994 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 16995 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 16996 public static final int DUMP_PERMISSIONS = 1 << 6; 16997 public static final int DUMP_PACKAGES = 1 << 7; 16998 public static final int DUMP_SHARED_USERS = 1 << 8; 16999 public static final int DUMP_MESSAGES = 1 << 9; 17000 public static final int DUMP_PROVIDERS = 1 << 10; 17001 public static final int DUMP_VERIFIERS = 1 << 11; 17002 public static final int DUMP_PREFERRED = 1 << 12; 17003 public static final int DUMP_PREFERRED_XML = 1 << 13; 17004 public static final int DUMP_KEYSETS = 1 << 14; 17005 public static final int DUMP_VERSION = 1 << 15; 17006 public static final int DUMP_INSTALLS = 1 << 16; 17007 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17008 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17009 17010 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17011 17012 private int mTypes; 17013 17014 private int mOptions; 17015 17016 private boolean mTitlePrinted; 17017 17018 private SharedUserSetting mSharedUser; 17019 17020 public boolean isDumping(int type) { 17021 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17022 return true; 17023 } 17024 17025 return (mTypes & type) != 0; 17026 } 17027 17028 public void setDump(int type) { 17029 mTypes |= type; 17030 } 17031 17032 public boolean isOptionEnabled(int option) { 17033 return (mOptions & option) != 0; 17034 } 17035 17036 public void setOptionEnabled(int option) { 17037 mOptions |= option; 17038 } 17039 17040 public boolean onTitlePrinted() { 17041 final boolean printed = mTitlePrinted; 17042 mTitlePrinted = true; 17043 return printed; 17044 } 17045 17046 public boolean getTitlePrinted() { 17047 return mTitlePrinted; 17048 } 17049 17050 public void setTitlePrinted(boolean enabled) { 17051 mTitlePrinted = enabled; 17052 } 17053 17054 public SharedUserSetting getSharedUser() { 17055 return mSharedUser; 17056 } 17057 17058 public void setSharedUser(SharedUserSetting user) { 17059 mSharedUser = user; 17060 } 17061 } 17062 17063 @Override 17064 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17065 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17066 (new PackageManagerShellCommand(this)).exec( 17067 this, in, out, err, args, resultReceiver); 17068 } 17069 17070 @Override 17071 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17072 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17073 != PackageManager.PERMISSION_GRANTED) { 17074 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17075 + Binder.getCallingPid() 17076 + ", uid=" + Binder.getCallingUid() 17077 + " without permission " 17078 + android.Manifest.permission.DUMP); 17079 return; 17080 } 17081 17082 DumpState dumpState = new DumpState(); 17083 boolean fullPreferred = false; 17084 boolean checkin = false; 17085 17086 String packageName = null; 17087 ArraySet<String> permissionNames = null; 17088 17089 int opti = 0; 17090 while (opti < args.length) { 17091 String opt = args[opti]; 17092 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 17093 break; 17094 } 17095 opti++; 17096 17097 if ("-a".equals(opt)) { 17098 // Right now we only know how to print all. 17099 } else if ("-h".equals(opt)) { 17100 pw.println("Package manager dump options:"); 17101 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 17102 pw.println(" --checkin: dump for a checkin"); 17103 pw.println(" -f: print details of intent filters"); 17104 pw.println(" -h: print this help"); 17105 pw.println(" cmd may be one of:"); 17106 pw.println(" l[ibraries]: list known shared libraries"); 17107 pw.println(" f[eatures]: list device features"); 17108 pw.println(" k[eysets]: print known keysets"); 17109 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 17110 pw.println(" perm[issions]: dump permissions"); 17111 pw.println(" permission [name ...]: dump declaration and use of given permission"); 17112 pw.println(" pref[erred]: print preferred package settings"); 17113 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 17114 pw.println(" prov[iders]: dump content providers"); 17115 pw.println(" p[ackages]: dump installed packages"); 17116 pw.println(" s[hared-users]: dump shared user IDs"); 17117 pw.println(" m[essages]: print collected runtime messages"); 17118 pw.println(" v[erifiers]: print package verifier info"); 17119 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 17120 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 17121 pw.println(" version: print database version info"); 17122 pw.println(" write: write current settings now"); 17123 pw.println(" installs: details about install sessions"); 17124 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 17125 pw.println(" <package.name>: info about given package"); 17126 return; 17127 } else if ("--checkin".equals(opt)) { 17128 checkin = true; 17129 } else if ("-f".equals(opt)) { 17130 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17131 } else { 17132 pw.println("Unknown argument: " + opt + "; use -h for help"); 17133 } 17134 } 17135 17136 // Is the caller requesting to dump a particular piece of data? 17137 if (opti < args.length) { 17138 String cmd = args[opti]; 17139 opti++; 17140 // Is this a package name? 17141 if ("android".equals(cmd) || cmd.contains(".")) { 17142 packageName = cmd; 17143 // When dumping a single package, we always dump all of its 17144 // filter information since the amount of data will be reasonable. 17145 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17146 } else if ("check-permission".equals(cmd)) { 17147 if (opti >= args.length) { 17148 pw.println("Error: check-permission missing permission argument"); 17149 return; 17150 } 17151 String perm = args[opti]; 17152 opti++; 17153 if (opti >= args.length) { 17154 pw.println("Error: check-permission missing package argument"); 17155 return; 17156 } 17157 String pkg = args[opti]; 17158 opti++; 17159 int user = UserHandle.getUserId(Binder.getCallingUid()); 17160 if (opti < args.length) { 17161 try { 17162 user = Integer.parseInt(args[opti]); 17163 } catch (NumberFormatException e) { 17164 pw.println("Error: check-permission user argument is not a number: " 17165 + args[opti]); 17166 return; 17167 } 17168 } 17169 pw.println(checkPermission(perm, pkg, user)); 17170 return; 17171 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 17172 dumpState.setDump(DumpState.DUMP_LIBS); 17173 } else if ("f".equals(cmd) || "features".equals(cmd)) { 17174 dumpState.setDump(DumpState.DUMP_FEATURES); 17175 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 17176 if (opti >= args.length) { 17177 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 17178 | DumpState.DUMP_SERVICE_RESOLVERS 17179 | DumpState.DUMP_RECEIVER_RESOLVERS 17180 | DumpState.DUMP_CONTENT_RESOLVERS); 17181 } else { 17182 while (opti < args.length) { 17183 String name = args[opti]; 17184 if ("a".equals(name) || "activity".equals(name)) { 17185 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 17186 } else if ("s".equals(name) || "service".equals(name)) { 17187 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 17188 } else if ("r".equals(name) || "receiver".equals(name)) { 17189 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 17190 } else if ("c".equals(name) || "content".equals(name)) { 17191 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 17192 } else { 17193 pw.println("Error: unknown resolver table type: " + name); 17194 return; 17195 } 17196 opti++; 17197 } 17198 } 17199 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 17200 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 17201 } else if ("permission".equals(cmd)) { 17202 if (opti >= args.length) { 17203 pw.println("Error: permission requires permission name"); 17204 return; 17205 } 17206 permissionNames = new ArraySet<>(); 17207 while (opti < args.length) { 17208 permissionNames.add(args[opti]); 17209 opti++; 17210 } 17211 dumpState.setDump(DumpState.DUMP_PERMISSIONS 17212 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 17213 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 17214 dumpState.setDump(DumpState.DUMP_PREFERRED); 17215 } else if ("preferred-xml".equals(cmd)) { 17216 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 17217 if (opti < args.length && "--full".equals(args[opti])) { 17218 fullPreferred = true; 17219 opti++; 17220 } 17221 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 17222 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 17223 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 17224 dumpState.setDump(DumpState.DUMP_PACKAGES); 17225 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 17226 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 17227 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 17228 dumpState.setDump(DumpState.DUMP_PROVIDERS); 17229 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 17230 dumpState.setDump(DumpState.DUMP_MESSAGES); 17231 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 17232 dumpState.setDump(DumpState.DUMP_VERIFIERS); 17233 } else if ("i".equals(cmd) || "ifv".equals(cmd) 17234 || "intent-filter-verifiers".equals(cmd)) { 17235 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 17236 } else if ("version".equals(cmd)) { 17237 dumpState.setDump(DumpState.DUMP_VERSION); 17238 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 17239 dumpState.setDump(DumpState.DUMP_KEYSETS); 17240 } else if ("installs".equals(cmd)) { 17241 dumpState.setDump(DumpState.DUMP_INSTALLS); 17242 } else if ("write".equals(cmd)) { 17243 synchronized (mPackages) { 17244 mSettings.writeLPr(); 17245 pw.println("Settings written."); 17246 return; 17247 } 17248 } 17249 } 17250 17251 if (checkin) { 17252 pw.println("vers,1"); 17253 } 17254 17255 // reader 17256 synchronized (mPackages) { 17257 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 17258 if (!checkin) { 17259 if (dumpState.onTitlePrinted()) 17260 pw.println(); 17261 pw.println("Database versions:"); 17262 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 17263 } 17264 } 17265 17266 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 17267 if (!checkin) { 17268 if (dumpState.onTitlePrinted()) 17269 pw.println(); 17270 pw.println("Verifiers:"); 17271 pw.print(" Required: "); 17272 pw.print(mRequiredVerifierPackage); 17273 pw.print(" (uid="); 17274 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17275 UserHandle.USER_SYSTEM)); 17276 pw.println(")"); 17277 } else if (mRequiredVerifierPackage != null) { 17278 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 17279 pw.print(","); 17280 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17281 UserHandle.USER_SYSTEM)); 17282 } 17283 } 17284 17285 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 17286 packageName == null) { 17287 if (mIntentFilterVerifierComponent != null) { 17288 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 17289 if (!checkin) { 17290 if (dumpState.onTitlePrinted()) 17291 pw.println(); 17292 pw.println("Intent Filter Verifier:"); 17293 pw.print(" Using: "); 17294 pw.print(verifierPackageName); 17295 pw.print(" (uid="); 17296 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17297 UserHandle.USER_SYSTEM)); 17298 pw.println(")"); 17299 } else if (verifierPackageName != null) { 17300 pw.print("ifv,"); pw.print(verifierPackageName); 17301 pw.print(","); 17302 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17303 UserHandle.USER_SYSTEM)); 17304 } 17305 } else { 17306 pw.println(); 17307 pw.println("No Intent Filter Verifier available!"); 17308 } 17309 } 17310 17311 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 17312 boolean printedHeader = false; 17313 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 17314 while (it.hasNext()) { 17315 String name = it.next(); 17316 SharedLibraryEntry ent = mSharedLibraries.get(name); 17317 if (!checkin) { 17318 if (!printedHeader) { 17319 if (dumpState.onTitlePrinted()) 17320 pw.println(); 17321 pw.println("Libraries:"); 17322 printedHeader = true; 17323 } 17324 pw.print(" "); 17325 } else { 17326 pw.print("lib,"); 17327 } 17328 pw.print(name); 17329 if (!checkin) { 17330 pw.print(" -> "); 17331 } 17332 if (ent.path != null) { 17333 if (!checkin) { 17334 pw.print("(jar) "); 17335 pw.print(ent.path); 17336 } else { 17337 pw.print(",jar,"); 17338 pw.print(ent.path); 17339 } 17340 } else { 17341 if (!checkin) { 17342 pw.print("(apk) "); 17343 pw.print(ent.apk); 17344 } else { 17345 pw.print(",apk,"); 17346 pw.print(ent.apk); 17347 } 17348 } 17349 pw.println(); 17350 } 17351 } 17352 17353 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 17354 if (dumpState.onTitlePrinted()) 17355 pw.println(); 17356 if (!checkin) { 17357 pw.println("Features:"); 17358 } 17359 17360 for (FeatureInfo feat : mAvailableFeatures.values()) { 17361 if (checkin) { 17362 pw.print("feat,"); 17363 pw.print(feat.name); 17364 pw.print(","); 17365 pw.println(feat.version); 17366 } else { 17367 pw.print(" "); 17368 pw.print(feat.name); 17369 if (feat.version > 0) { 17370 pw.print(" version="); 17371 pw.print(feat.version); 17372 } 17373 pw.println(); 17374 } 17375 } 17376 } 17377 17378 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 17379 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 17380 : "Activity Resolver Table:", " ", packageName, 17381 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17382 dumpState.setTitlePrinted(true); 17383 } 17384 } 17385 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 17386 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 17387 : "Receiver Resolver Table:", " ", packageName, 17388 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17389 dumpState.setTitlePrinted(true); 17390 } 17391 } 17392 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 17393 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 17394 : "Service Resolver Table:", " ", packageName, 17395 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17396 dumpState.setTitlePrinted(true); 17397 } 17398 } 17399 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 17400 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 17401 : "Provider Resolver Table:", " ", packageName, 17402 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17403 dumpState.setTitlePrinted(true); 17404 } 17405 } 17406 17407 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 17408 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17409 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17410 int user = mSettings.mPreferredActivities.keyAt(i); 17411 if (pir.dump(pw, 17412 dumpState.getTitlePrinted() 17413 ? "\nPreferred Activities User " + user + ":" 17414 : "Preferred Activities User " + user + ":", " ", 17415 packageName, true, false)) { 17416 dumpState.setTitlePrinted(true); 17417 } 17418 } 17419 } 17420 17421 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 17422 pw.flush(); 17423 FileOutputStream fout = new FileOutputStream(fd); 17424 BufferedOutputStream str = new BufferedOutputStream(fout); 17425 XmlSerializer serializer = new FastXmlSerializer(); 17426 try { 17427 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 17428 serializer.startDocument(null, true); 17429 serializer.setFeature( 17430 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 17431 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 17432 serializer.endDocument(); 17433 serializer.flush(); 17434 } catch (IllegalArgumentException e) { 17435 pw.println("Failed writing: " + e); 17436 } catch (IllegalStateException e) { 17437 pw.println("Failed writing: " + e); 17438 } catch (IOException e) { 17439 pw.println("Failed writing: " + e); 17440 } 17441 } 17442 17443 if (!checkin 17444 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 17445 && packageName == null) { 17446 pw.println(); 17447 int count = mSettings.mPackages.size(); 17448 if (count == 0) { 17449 pw.println("No applications!"); 17450 pw.println(); 17451 } else { 17452 final String prefix = " "; 17453 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 17454 if (allPackageSettings.size() == 0) { 17455 pw.println("No domain preferred apps!"); 17456 pw.println(); 17457 } else { 17458 pw.println("App verification status:"); 17459 pw.println(); 17460 count = 0; 17461 for (PackageSetting ps : allPackageSettings) { 17462 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 17463 if (ivi == null || ivi.getPackageName() == null) continue; 17464 pw.println(prefix + "Package: " + ivi.getPackageName()); 17465 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 17466 pw.println(prefix + "Status: " + ivi.getStatusString()); 17467 pw.println(); 17468 count++; 17469 } 17470 if (count == 0) { 17471 pw.println(prefix + "No app verification established."); 17472 pw.println(); 17473 } 17474 for (int userId : sUserManager.getUserIds()) { 17475 pw.println("App linkages for user " + userId + ":"); 17476 pw.println(); 17477 count = 0; 17478 for (PackageSetting ps : allPackageSettings) { 17479 final long status = ps.getDomainVerificationStatusForUser(userId); 17480 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 17481 continue; 17482 } 17483 pw.println(prefix + "Package: " + ps.name); 17484 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 17485 String statusStr = IntentFilterVerificationInfo. 17486 getStatusStringFromValue(status); 17487 pw.println(prefix + "Status: " + statusStr); 17488 pw.println(); 17489 count++; 17490 } 17491 if (count == 0) { 17492 pw.println(prefix + "No configured app linkages."); 17493 pw.println(); 17494 } 17495 } 17496 } 17497 } 17498 } 17499 17500 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 17501 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 17502 if (packageName == null && permissionNames == null) { 17503 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 17504 if (iperm == 0) { 17505 if (dumpState.onTitlePrinted()) 17506 pw.println(); 17507 pw.println("AppOp Permissions:"); 17508 } 17509 pw.print(" AppOp Permission "); 17510 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 17511 pw.println(":"); 17512 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 17513 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 17514 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 17515 } 17516 } 17517 } 17518 } 17519 17520 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 17521 boolean printedSomething = false; 17522 for (PackageParser.Provider p : mProviders.mProviders.values()) { 17523 if (packageName != null && !packageName.equals(p.info.packageName)) { 17524 continue; 17525 } 17526 if (!printedSomething) { 17527 if (dumpState.onTitlePrinted()) 17528 pw.println(); 17529 pw.println("Registered ContentProviders:"); 17530 printedSomething = true; 17531 } 17532 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 17533 pw.print(" "); pw.println(p.toString()); 17534 } 17535 printedSomething = false; 17536 for (Map.Entry<String, PackageParser.Provider> entry : 17537 mProvidersByAuthority.entrySet()) { 17538 PackageParser.Provider p = entry.getValue(); 17539 if (packageName != null && !packageName.equals(p.info.packageName)) { 17540 continue; 17541 } 17542 if (!printedSomething) { 17543 if (dumpState.onTitlePrinted()) 17544 pw.println(); 17545 pw.println("ContentProvider Authorities:"); 17546 printedSomething = true; 17547 } 17548 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 17549 pw.print(" "); pw.println(p.toString()); 17550 if (p.info != null && p.info.applicationInfo != null) { 17551 final String appInfo = p.info.applicationInfo.toString(); 17552 pw.print(" applicationInfo="); pw.println(appInfo); 17553 } 17554 } 17555 } 17556 17557 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 17558 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 17559 } 17560 17561 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 17562 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 17563 } 17564 17565 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 17566 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 17567 } 17568 17569 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 17570 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 17571 } 17572 17573 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 17574 // XXX should handle packageName != null by dumping only install data that 17575 // the given package is involved with. 17576 if (dumpState.onTitlePrinted()) pw.println(); 17577 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 17578 } 17579 17580 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 17581 if (dumpState.onTitlePrinted()) pw.println(); 17582 mSettings.dumpReadMessagesLPr(pw, dumpState); 17583 17584 pw.println(); 17585 pw.println("Package warning messages:"); 17586 BufferedReader in = null; 17587 String line = null; 17588 try { 17589 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 17590 while ((line = in.readLine()) != null) { 17591 if (line.contains("ignored: updated version")) continue; 17592 pw.println(line); 17593 } 17594 } catch (IOException ignored) { 17595 } finally { 17596 IoUtils.closeQuietly(in); 17597 } 17598 } 17599 17600 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 17601 BufferedReader in = null; 17602 String line = null; 17603 try { 17604 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 17605 while ((line = in.readLine()) != null) { 17606 if (line.contains("ignored: updated version")) continue; 17607 pw.print("msg,"); 17608 pw.println(line); 17609 } 17610 } catch (IOException ignored) { 17611 } finally { 17612 IoUtils.closeQuietly(in); 17613 } 17614 } 17615 } 17616 } 17617 17618 private String dumpDomainString(String packageName) { 17619 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 17620 .getList(); 17621 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 17622 17623 ArraySet<String> result = new ArraySet<>(); 17624 if (iviList.size() > 0) { 17625 for (IntentFilterVerificationInfo ivi : iviList) { 17626 for (String host : ivi.getDomains()) { 17627 result.add(host); 17628 } 17629 } 17630 } 17631 if (filters != null && filters.size() > 0) { 17632 for (IntentFilter filter : filters) { 17633 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 17634 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 17635 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 17636 result.addAll(filter.getHostsList()); 17637 } 17638 } 17639 } 17640 17641 StringBuilder sb = new StringBuilder(result.size() * 16); 17642 for (String domain : result) { 17643 if (sb.length() > 0) sb.append(" "); 17644 sb.append(domain); 17645 } 17646 return sb.toString(); 17647 } 17648 17649 // ------- apps on sdcard specific code ------- 17650 static final boolean DEBUG_SD_INSTALL = false; 17651 17652 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 17653 17654 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 17655 17656 private boolean mMediaMounted = false; 17657 17658 static String getEncryptKey() { 17659 try { 17660 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 17661 SD_ENCRYPTION_KEYSTORE_NAME); 17662 if (sdEncKey == null) { 17663 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 17664 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 17665 if (sdEncKey == null) { 17666 Slog.e(TAG, "Failed to create encryption keys"); 17667 return null; 17668 } 17669 } 17670 return sdEncKey; 17671 } catch (NoSuchAlgorithmException nsae) { 17672 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 17673 return null; 17674 } catch (IOException ioe) { 17675 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 17676 return null; 17677 } 17678 } 17679 17680 /* 17681 * Update media status on PackageManager. 17682 */ 17683 @Override 17684 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 17685 int callingUid = Binder.getCallingUid(); 17686 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 17687 throw new SecurityException("Media status can only be updated by the system"); 17688 } 17689 // reader; this apparently protects mMediaMounted, but should probably 17690 // be a different lock in that case. 17691 synchronized (mPackages) { 17692 Log.i(TAG, "Updating external media status from " 17693 + (mMediaMounted ? "mounted" : "unmounted") + " to " 17694 + (mediaStatus ? "mounted" : "unmounted")); 17695 if (DEBUG_SD_INSTALL) 17696 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 17697 + ", mMediaMounted=" + mMediaMounted); 17698 if (mediaStatus == mMediaMounted) { 17699 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 17700 : 0, -1); 17701 mHandler.sendMessage(msg); 17702 return; 17703 } 17704 mMediaMounted = mediaStatus; 17705 } 17706 // Queue up an async operation since the package installation may take a 17707 // little while. 17708 mHandler.post(new Runnable() { 17709 public void run() { 17710 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 17711 } 17712 }); 17713 } 17714 17715 /** 17716 * Called by MountService when the initial ASECs to scan are available. 17717 * Should block until all the ASEC containers are finished being scanned. 17718 */ 17719 public void scanAvailableAsecs() { 17720 updateExternalMediaStatusInner(true, false, false); 17721 } 17722 17723 /* 17724 * Collect information of applications on external media, map them against 17725 * existing containers and update information based on current mount status. 17726 * Please note that we always have to report status if reportStatus has been 17727 * set to true especially when unloading packages. 17728 */ 17729 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 17730 boolean externalStorage) { 17731 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 17732 int[] uidArr = EmptyArray.INT; 17733 17734 final String[] list = PackageHelper.getSecureContainerList(); 17735 if (ArrayUtils.isEmpty(list)) { 17736 Log.i(TAG, "No secure containers found"); 17737 } else { 17738 // Process list of secure containers and categorize them 17739 // as active or stale based on their package internal state. 17740 17741 // reader 17742 synchronized (mPackages) { 17743 for (String cid : list) { 17744 // Leave stages untouched for now; installer service owns them 17745 if (PackageInstallerService.isStageName(cid)) continue; 17746 17747 if (DEBUG_SD_INSTALL) 17748 Log.i(TAG, "Processing container " + cid); 17749 String pkgName = getAsecPackageName(cid); 17750 if (pkgName == null) { 17751 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 17752 continue; 17753 } 17754 if (DEBUG_SD_INSTALL) 17755 Log.i(TAG, "Looking for pkg : " + pkgName); 17756 17757 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17758 if (ps == null) { 17759 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 17760 continue; 17761 } 17762 17763 /* 17764 * Skip packages that are not external if we're unmounting 17765 * external storage. 17766 */ 17767 if (externalStorage && !isMounted && !isExternal(ps)) { 17768 continue; 17769 } 17770 17771 final AsecInstallArgs args = new AsecInstallArgs(cid, 17772 getAppDexInstructionSets(ps), ps.isForwardLocked()); 17773 // The package status is changed only if the code path 17774 // matches between settings and the container id. 17775 if (ps.codePathString != null 17776 && ps.codePathString.startsWith(args.getCodePath())) { 17777 if (DEBUG_SD_INSTALL) { 17778 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 17779 + " at code path: " + ps.codePathString); 17780 } 17781 17782 // We do have a valid package installed on sdcard 17783 processCids.put(args, ps.codePathString); 17784 final int uid = ps.appId; 17785 if (uid != -1) { 17786 uidArr = ArrayUtils.appendInt(uidArr, uid); 17787 } 17788 } else { 17789 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 17790 + ps.codePathString); 17791 } 17792 } 17793 } 17794 17795 Arrays.sort(uidArr); 17796 } 17797 17798 // Process packages with valid entries. 17799 if (isMounted) { 17800 if (DEBUG_SD_INSTALL) 17801 Log.i(TAG, "Loading packages"); 17802 loadMediaPackages(processCids, uidArr, externalStorage); 17803 startCleaningPackages(); 17804 mInstallerService.onSecureContainersAvailable(); 17805 } else { 17806 if (DEBUG_SD_INSTALL) 17807 Log.i(TAG, "Unloading packages"); 17808 unloadMediaPackages(processCids, uidArr, reportStatus); 17809 } 17810 } 17811 17812 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17813 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 17814 final int size = infos.size(); 17815 final String[] packageNames = new String[size]; 17816 final int[] packageUids = new int[size]; 17817 for (int i = 0; i < size; i++) { 17818 final ApplicationInfo info = infos.get(i); 17819 packageNames[i] = info.packageName; 17820 packageUids[i] = info.uid; 17821 } 17822 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 17823 finishedReceiver); 17824 } 17825 17826 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17827 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 17828 sendResourcesChangedBroadcast(mediaStatus, replacing, 17829 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 17830 } 17831 17832 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17833 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 17834 int size = pkgList.length; 17835 if (size > 0) { 17836 // Send broadcasts here 17837 Bundle extras = new Bundle(); 17838 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 17839 if (uidArr != null) { 17840 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 17841 } 17842 if (replacing) { 17843 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 17844 } 17845 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 17846 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 17847 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 17848 } 17849 } 17850 17851 /* 17852 * Look at potentially valid container ids from processCids If package 17853 * information doesn't match the one on record or package scanning fails, 17854 * the cid is added to list of removeCids. We currently don't delete stale 17855 * containers. 17856 */ 17857 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 17858 boolean externalStorage) { 17859 ArrayList<String> pkgList = new ArrayList<String>(); 17860 Set<AsecInstallArgs> keys = processCids.keySet(); 17861 17862 for (AsecInstallArgs args : keys) { 17863 String codePath = processCids.get(args); 17864 if (DEBUG_SD_INSTALL) 17865 Log.i(TAG, "Loading container : " + args.cid); 17866 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 17867 try { 17868 // Make sure there are no container errors first. 17869 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 17870 Slog.e(TAG, "Failed to mount cid : " + args.cid 17871 + " when installing from sdcard"); 17872 continue; 17873 } 17874 // Check code path here. 17875 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 17876 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 17877 + " does not match one in settings " + codePath); 17878 continue; 17879 } 17880 // Parse package 17881 int parseFlags = mDefParseFlags; 17882 if (args.isExternalAsec()) { 17883 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 17884 } 17885 if (args.isFwdLocked()) { 17886 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 17887 } 17888 17889 synchronized (mInstallLock) { 17890 PackageParser.Package pkg = null; 17891 try { 17892 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 17893 } catch (PackageManagerException e) { 17894 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 17895 } 17896 // Scan the package 17897 if (pkg != null) { 17898 /* 17899 * TODO why is the lock being held? doPostInstall is 17900 * called in other places without the lock. This needs 17901 * to be straightened out. 17902 */ 17903 // writer 17904 synchronized (mPackages) { 17905 retCode = PackageManager.INSTALL_SUCCEEDED; 17906 pkgList.add(pkg.packageName); 17907 // Post process args 17908 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 17909 pkg.applicationInfo.uid); 17910 } 17911 } else { 17912 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 17913 } 17914 } 17915 17916 } finally { 17917 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 17918 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 17919 } 17920 } 17921 } 17922 // writer 17923 synchronized (mPackages) { 17924 // If the platform SDK has changed since the last time we booted, 17925 // we need to re-grant app permission to catch any new ones that 17926 // appear. This is really a hack, and means that apps can in some 17927 // cases get permissions that the user didn't initially explicitly 17928 // allow... it would be nice to have some better way to handle 17929 // this situation. 17930 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 17931 : mSettings.getInternalVersion(); 17932 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 17933 : StorageManager.UUID_PRIVATE_INTERNAL; 17934 17935 int updateFlags = UPDATE_PERMISSIONS_ALL; 17936 if (ver.sdkVersion != mSdkVersion) { 17937 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 17938 + mSdkVersion + "; regranting permissions for external"); 17939 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 17940 } 17941 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 17942 17943 // Yay, everything is now upgraded 17944 ver.forceCurrent(); 17945 17946 // can downgrade to reader 17947 // Persist settings 17948 mSettings.writeLPr(); 17949 } 17950 // Send a broadcast to let everyone know we are done processing 17951 if (pkgList.size() > 0) { 17952 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 17953 } 17954 } 17955 17956 /* 17957 * Utility method to unload a list of specified containers 17958 */ 17959 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 17960 // Just unmount all valid containers. 17961 for (AsecInstallArgs arg : cidArgs) { 17962 synchronized (mInstallLock) { 17963 arg.doPostDeleteLI(false); 17964 } 17965 } 17966 } 17967 17968 /* 17969 * Unload packages mounted on external media. This involves deleting package 17970 * data from internal structures, sending broadcasts about disabled packages, 17971 * gc'ing to free up references, unmounting all secure containers 17972 * corresponding to packages on external media, and posting a 17973 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 17974 * that we always have to post this message if status has been requested no 17975 * matter what. 17976 */ 17977 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 17978 final boolean reportStatus) { 17979 if (DEBUG_SD_INSTALL) 17980 Log.i(TAG, "unloading media packages"); 17981 ArrayList<String> pkgList = new ArrayList<String>(); 17982 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 17983 final Set<AsecInstallArgs> keys = processCids.keySet(); 17984 for (AsecInstallArgs args : keys) { 17985 String pkgName = args.getPackageName(); 17986 if (DEBUG_SD_INSTALL) 17987 Log.i(TAG, "Trying to unload pkg : " + pkgName); 17988 // Delete package internally 17989 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 17990 synchronized (mInstallLock) { 17991 boolean res = deletePackageLI(pkgName, null, false, null, 17992 PackageManager.DELETE_KEEP_DATA, outInfo, false, null); 17993 if (res) { 17994 pkgList.add(pkgName); 17995 } else { 17996 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 17997 failedList.add(args); 17998 } 17999 } 18000 } 18001 18002 // reader 18003 synchronized (mPackages) { 18004 // We didn't update the settings after removing each package; 18005 // write them now for all packages. 18006 mSettings.writeLPr(); 18007 } 18008 18009 // We have to absolutely send UPDATED_MEDIA_STATUS only 18010 // after confirming that all the receivers processed the ordered 18011 // broadcast when packages get disabled, force a gc to clean things up. 18012 // and unload all the containers. 18013 if (pkgList.size() > 0) { 18014 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18015 new IIntentReceiver.Stub() { 18016 public void performReceive(Intent intent, int resultCode, String data, 18017 Bundle extras, boolean ordered, boolean sticky, 18018 int sendingUser) throws RemoteException { 18019 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18020 reportStatus ? 1 : 0, 1, keys); 18021 mHandler.sendMessage(msg); 18022 } 18023 }); 18024 } else { 18025 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 18026 keys); 18027 mHandler.sendMessage(msg); 18028 } 18029 } 18030 18031 private void loadPrivatePackages(final VolumeInfo vol) { 18032 mHandler.post(new Runnable() { 18033 @Override 18034 public void run() { 18035 loadPrivatePackagesInner(vol); 18036 } 18037 }); 18038 } 18039 18040 private void loadPrivatePackagesInner(VolumeInfo vol) { 18041 final String volumeUuid = vol.fsUuid; 18042 if (TextUtils.isEmpty(volumeUuid)) { 18043 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 18044 return; 18045 } 18046 18047 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 18048 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 18049 18050 final VersionInfo ver; 18051 final List<PackageSetting> packages; 18052 synchronized (mPackages) { 18053 ver = mSettings.findOrCreateVersion(volumeUuid); 18054 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18055 } 18056 18057 // TODO: introduce a new concept similar to "frozen" to prevent these 18058 // apps from being launched until after data has been fully reconciled 18059 for (PackageSetting ps : packages) { 18060 synchronized (mInstallLock) { 18061 final PackageParser.Package pkg; 18062 try { 18063 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 18064 loaded.add(pkg.applicationInfo); 18065 18066 } catch (PackageManagerException e) { 18067 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 18068 } 18069 18070 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 18071 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 18072 } 18073 } 18074 } 18075 18076 // Reconcile app data for all started/unlocked users 18077 final StorageManager sm = mContext.getSystemService(StorageManager.class); 18078 final UserManager um = mContext.getSystemService(UserManager.class); 18079 for (UserInfo user : um.getUsers()) { 18080 final int flags; 18081 if (um.isUserUnlocked(user.id)) { 18082 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18083 } else if (um.isUserRunning(user.id)) { 18084 flags = StorageManager.FLAG_STORAGE_DE; 18085 } else { 18086 continue; 18087 } 18088 18089 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 18090 reconcileAppsData(volumeUuid, user.id, flags); 18091 } 18092 18093 synchronized (mPackages) { 18094 int updateFlags = UPDATE_PERMISSIONS_ALL; 18095 if (ver.sdkVersion != mSdkVersion) { 18096 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18097 + mSdkVersion + "; regranting permissions for " + volumeUuid); 18098 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18099 } 18100 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18101 18102 // Yay, everything is now upgraded 18103 ver.forceCurrent(); 18104 18105 mSettings.writeLPr(); 18106 } 18107 18108 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 18109 sendResourcesChangedBroadcast(true, false, loaded, null); 18110 } 18111 18112 private void unloadPrivatePackages(final VolumeInfo vol) { 18113 mHandler.post(new Runnable() { 18114 @Override 18115 public void run() { 18116 unloadPrivatePackagesInner(vol); 18117 } 18118 }); 18119 } 18120 18121 private void unloadPrivatePackagesInner(VolumeInfo vol) { 18122 final String volumeUuid = vol.fsUuid; 18123 if (TextUtils.isEmpty(volumeUuid)) { 18124 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 18125 return; 18126 } 18127 18128 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 18129 synchronized (mInstallLock) { 18130 synchronized (mPackages) { 18131 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 18132 for (PackageSetting ps : packages) { 18133 if (ps.pkg == null) continue; 18134 18135 final ApplicationInfo info = ps.pkg.applicationInfo; 18136 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18137 if (deletePackageLI(ps.name, null, false, null, 18138 PackageManager.DELETE_KEEP_DATA, outInfo, false, null)) { 18139 unloaded.add(info); 18140 } else { 18141 Slog.w(TAG, "Failed to unload " + ps.codePath); 18142 } 18143 } 18144 18145 mSettings.writeLPr(); 18146 } 18147 } 18148 18149 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 18150 sendResourcesChangedBroadcast(false, false, unloaded, null); 18151 } 18152 18153 /** 18154 * Examine all users present on given mounted volume, and destroy data 18155 * belonging to users that are no longer valid, or whose user ID has been 18156 * recycled. 18157 */ 18158 private void reconcileUsers(String volumeUuid) { 18159 // TODO: also reconcile DE directories 18160 final File[] files = FileUtils 18161 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)); 18162 for (File file : files) { 18163 if (!file.isDirectory()) continue; 18164 18165 final int userId; 18166 final UserInfo info; 18167 try { 18168 userId = Integer.parseInt(file.getName()); 18169 info = sUserManager.getUserInfo(userId); 18170 } catch (NumberFormatException e) { 18171 Slog.w(TAG, "Invalid user directory " + file); 18172 continue; 18173 } 18174 18175 boolean destroyUser = false; 18176 if (info == null) { 18177 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18178 + " because no matching user was found"); 18179 destroyUser = true; 18180 } else { 18181 try { 18182 UserManagerService.enforceSerialNumber(file, info.serialNumber); 18183 } catch (IOException e) { 18184 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18185 + " because we failed to enforce serial number: " + e); 18186 destroyUser = true; 18187 } 18188 } 18189 18190 if (destroyUser) { 18191 synchronized (mInstallLock) { 18192 try { 18193 mInstaller.removeUserDataDirs(volumeUuid, userId); 18194 } catch (InstallerException e) { 18195 Slog.w(TAG, "Failed to clean up user dirs", e); 18196 } 18197 } 18198 } 18199 } 18200 } 18201 18202 private void assertPackageKnown(String volumeUuid, String packageName) 18203 throws PackageManagerException { 18204 synchronized (mPackages) { 18205 final PackageSetting ps = mSettings.mPackages.get(packageName); 18206 if (ps == null) { 18207 throw new PackageManagerException("Package " + packageName + " is unknown"); 18208 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18209 throw new PackageManagerException( 18210 "Package " + packageName + " found on unknown volume " + volumeUuid 18211 + "; expected volume " + ps.volumeUuid); 18212 } 18213 } 18214 } 18215 18216 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 18217 throws PackageManagerException { 18218 synchronized (mPackages) { 18219 final PackageSetting ps = mSettings.mPackages.get(packageName); 18220 if (ps == null) { 18221 throw new PackageManagerException("Package " + packageName + " is unknown"); 18222 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18223 throw new PackageManagerException( 18224 "Package " + packageName + " found on unknown volume " + volumeUuid 18225 + "; expected volume " + ps.volumeUuid); 18226 } else if (!ps.getInstalled(userId)) { 18227 throw new PackageManagerException( 18228 "Package " + packageName + " not installed for user " + userId); 18229 } 18230 } 18231 } 18232 18233 /** 18234 * Examine all apps present on given mounted volume, and destroy apps that 18235 * aren't expected, either due to uninstallation or reinstallation on 18236 * another volume. 18237 */ 18238 private void reconcileApps(String volumeUuid) { 18239 final File[] files = FileUtils 18240 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 18241 for (File file : files) { 18242 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 18243 && !PackageInstallerService.isStageName(file.getName()); 18244 if (!isPackage) { 18245 // Ignore entries which are not packages 18246 continue; 18247 } 18248 18249 try { 18250 final PackageLite pkg = PackageParser.parsePackageLite(file, 18251 PackageParser.PARSE_MUST_BE_APK); 18252 assertPackageKnown(volumeUuid, pkg.packageName); 18253 18254 } catch (PackageParserException | PackageManagerException e) { 18255 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18256 synchronized (mInstallLock) { 18257 removeCodePathLI(file); 18258 } 18259 } 18260 } 18261 } 18262 18263 /** 18264 * Reconcile all app data for the given user. 18265 * <p> 18266 * Verifies that directories exist and that ownership and labeling is 18267 * correct for all installed apps on all mounted volumes. 18268 */ 18269 void reconcileAppsData(int userId, int flags) { 18270 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18271 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18272 final String volumeUuid = vol.getFsUuid(); 18273 reconcileAppsData(volumeUuid, userId, flags); 18274 } 18275 } 18276 18277 /** 18278 * Reconcile all app data on given mounted volume. 18279 * <p> 18280 * Destroys app data that isn't expected, either due to uninstallation or 18281 * reinstallation on another volume. 18282 * <p> 18283 * Verifies that directories exist and that ownership and labeling is 18284 * correct for all installed apps. 18285 */ 18286 private void reconcileAppsData(String volumeUuid, int userId, int flags) { 18287 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 18288 + Integer.toHexString(flags)); 18289 18290 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 18291 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 18292 18293 boolean restoreconNeeded = false; 18294 18295 // First look for stale data that doesn't belong, and check if things 18296 // have changed since we did our last restorecon 18297 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18298 if (!isUserKeyUnlocked(userId)) { 18299 throw new RuntimeException( 18300 "Yikes, someone asked us to reconcile CE storage while " + userId 18301 + " was still locked; this would have caused massive data loss!"); 18302 } 18303 18304 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 18305 18306 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 18307 for (File file : files) { 18308 final String packageName = file.getName(); 18309 try { 18310 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18311 } catch (PackageManagerException e) { 18312 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18313 synchronized (mInstallLock) { 18314 destroyAppDataLI(volumeUuid, packageName, userId, 18315 StorageManager.FLAG_STORAGE_CE); 18316 } 18317 } 18318 } 18319 } 18320 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18321 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 18322 18323 final File[] files = FileUtils.listFilesOrEmpty(deDir); 18324 for (File file : files) { 18325 final String packageName = file.getName(); 18326 try { 18327 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18328 } catch (PackageManagerException e) { 18329 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18330 synchronized (mInstallLock) { 18331 destroyAppDataLI(volumeUuid, packageName, userId, 18332 StorageManager.FLAG_STORAGE_DE); 18333 } 18334 } 18335 } 18336 } 18337 18338 // Ensure that data directories are ready to roll for all packages 18339 // installed for this volume and user 18340 final List<PackageSetting> packages; 18341 synchronized (mPackages) { 18342 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18343 } 18344 int preparedCount = 0; 18345 for (PackageSetting ps : packages) { 18346 final String packageName = ps.name; 18347 if (ps.pkg == null) { 18348 Slog.w(TAG, "Odd, missing scanned package " + packageName); 18349 // TODO: might be due to legacy ASEC apps; we should circle back 18350 // and reconcile again once they're scanned 18351 continue; 18352 } 18353 18354 if (ps.getInstalled(userId)) { 18355 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 18356 18357 if (maybeMigrateAppData(volumeUuid, userId, ps.pkg)) { 18358 // We may have just shuffled around app data directories, so 18359 // prepare them one more time 18360 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 18361 } 18362 18363 preparedCount++; 18364 } 18365 } 18366 18367 if (restoreconNeeded) { 18368 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18369 SELinuxMMAC.setRestoreconDone(ceDir); 18370 } 18371 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18372 SELinuxMMAC.setRestoreconDone(deDir); 18373 } 18374 } 18375 18376 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 18377 + " packages; restoreconNeeded was " + restoreconNeeded); 18378 } 18379 18380 /** 18381 * Prepare app data for the given app just after it was installed or 18382 * upgraded. This method carefully only touches users that it's installed 18383 * for, and it forces a restorecon to handle any seinfo changes. 18384 * <p> 18385 * Verifies that directories exist and that ownership and labeling is 18386 * correct for all installed apps. If there is an ownership mismatch, it 18387 * will try recovering system apps by wiping data; third-party app data is 18388 * left intact. 18389 * <p> 18390 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 18391 */ 18392 private void prepareAppDataAfterInstall(PackageParser.Package pkg) { 18393 prepareAppDataAfterInstallInternal(pkg); 18394 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 18395 for (int i = 0; i < childCount; i++) { 18396 PackageParser.Package childPackage = pkg.childPackages.get(i); 18397 prepareAppDataAfterInstallInternal(childPackage); 18398 } 18399 } 18400 18401 private void prepareAppDataAfterInstallInternal(PackageParser.Package pkg) { 18402 final PackageSetting ps; 18403 synchronized (mPackages) { 18404 ps = mSettings.mPackages.get(pkg.packageName); 18405 mSettings.writeKernelMappingLPr(ps); 18406 } 18407 18408 final UserManager um = mContext.getSystemService(UserManager.class); 18409 for (UserInfo user : um.getUsers()) { 18410 final int flags; 18411 if (um.isUserUnlocked(user.id)) { 18412 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18413 } else if (um.isUserRunning(user.id)) { 18414 flags = StorageManager.FLAG_STORAGE_DE; 18415 } else { 18416 continue; 18417 } 18418 18419 if (ps.getInstalled(user.id)) { 18420 // Whenever an app changes, force a restorecon of its data 18421 // TODO: when user data is locked, mark that we're still dirty 18422 prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true); 18423 } 18424 } 18425 } 18426 18427 /** 18428 * Prepare app data for the given app. 18429 * <p> 18430 * Verifies that directories exist and that ownership and labeling is 18431 * correct for all installed apps. If there is an ownership mismatch, this 18432 * will try recovering system apps by wiping data; third-party app data is 18433 * left intact. 18434 */ 18435 private void prepareAppData(String volumeUuid, int userId, int flags, 18436 PackageParser.Package pkg, boolean restoreconNeeded) { 18437 if (DEBUG_APP_DATA) { 18438 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 18439 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 18440 } 18441 18442 final String packageName = pkg.packageName; 18443 final ApplicationInfo app = pkg.applicationInfo; 18444 final int appId = UserHandle.getAppId(app.uid); 18445 18446 Preconditions.checkNotNull(app.seinfo); 18447 18448 synchronized (mInstallLock) { 18449 try { 18450 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18451 appId, app.seinfo, app.targetSdkVersion); 18452 } catch (InstallerException e) { 18453 if (app.isSystemApp()) { 18454 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 18455 + ", but trying to recover: " + e); 18456 destroyAppDataLI(volumeUuid, packageName, userId, flags); 18457 try { 18458 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18459 appId, app.seinfo, app.targetSdkVersion); 18460 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 18461 } catch (InstallerException e2) { 18462 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 18463 } 18464 } else { 18465 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 18466 } 18467 } 18468 18469 if (restoreconNeeded) { 18470 restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo); 18471 } 18472 18473 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18474 // Create a native library symlink only if we have native libraries 18475 // and if the native libraries are 32 bit libraries. We do not provide 18476 // this symlink for 64 bit libraries. 18477 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 18478 final String nativeLibPath = app.nativeLibraryDir; 18479 try { 18480 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 18481 nativeLibPath, userId); 18482 } catch (InstallerException e) { 18483 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 18484 } 18485 } 18486 } 18487 } 18488 } 18489 18490 /** 18491 * For system apps on non-FBE devices, this method migrates any existing 18492 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 18493 * requested by the app. 18494 */ 18495 private boolean maybeMigrateAppData(String volumeUuid, int userId, PackageParser.Package pkg) { 18496 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 18497 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 18498 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 18499 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 18500 synchronized (mInstallLock) { 18501 try { 18502 mInstaller.migrateAppData(volumeUuid, pkg.packageName, userId, storageTarget); 18503 } catch (InstallerException e) { 18504 logCriticalInfo(Log.WARN, 18505 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 18506 } 18507 } 18508 return true; 18509 } else { 18510 return false; 18511 } 18512 } 18513 18514 private void unfreezePackage(String packageName) { 18515 synchronized (mPackages) { 18516 final PackageSetting ps = mSettings.mPackages.get(packageName); 18517 if (ps != null) { 18518 ps.frozen = false; 18519 } 18520 } 18521 } 18522 18523 @Override 18524 public int movePackage(final String packageName, final String volumeUuid) { 18525 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 18526 18527 final int moveId = mNextMoveId.getAndIncrement(); 18528 mHandler.post(new Runnable() { 18529 @Override 18530 public void run() { 18531 try { 18532 movePackageInternal(packageName, volumeUuid, moveId); 18533 } catch (PackageManagerException e) { 18534 Slog.w(TAG, "Failed to move " + packageName, e); 18535 mMoveCallbacks.notifyStatusChanged(moveId, 18536 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 18537 } 18538 } 18539 }); 18540 return moveId; 18541 } 18542 18543 private void movePackageInternal(final String packageName, final String volumeUuid, 18544 final int moveId) throws PackageManagerException { 18545 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 18546 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18547 final PackageManager pm = mContext.getPackageManager(); 18548 18549 final boolean currentAsec; 18550 final String currentVolumeUuid; 18551 final File codeFile; 18552 final String installerPackageName; 18553 final String packageAbiOverride; 18554 final int appId; 18555 final String seinfo; 18556 final String label; 18557 final int targetSdkVersion; 18558 18559 // reader 18560 synchronized (mPackages) { 18561 final PackageParser.Package pkg = mPackages.get(packageName); 18562 final PackageSetting ps = mSettings.mPackages.get(packageName); 18563 if (pkg == null || ps == null) { 18564 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 18565 } 18566 18567 if (pkg.applicationInfo.isSystemApp()) { 18568 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 18569 "Cannot move system application"); 18570 } 18571 18572 if (pkg.applicationInfo.isExternalAsec()) { 18573 currentAsec = true; 18574 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 18575 } else if (pkg.applicationInfo.isForwardLocked()) { 18576 currentAsec = true; 18577 currentVolumeUuid = "forward_locked"; 18578 } else { 18579 currentAsec = false; 18580 currentVolumeUuid = ps.volumeUuid; 18581 18582 final File probe = new File(pkg.codePath); 18583 final File probeOat = new File(probe, "oat"); 18584 if (!probe.isDirectory() || !probeOat.isDirectory()) { 18585 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18586 "Move only supported for modern cluster style installs"); 18587 } 18588 } 18589 18590 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 18591 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18592 "Package already moved to " + volumeUuid); 18593 } 18594 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 18595 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 18596 "Device admin cannot be moved"); 18597 } 18598 18599 if (ps.frozen) { 18600 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 18601 "Failed to move already frozen package"); 18602 } 18603 ps.frozen = true; 18604 18605 codeFile = new File(pkg.codePath); 18606 installerPackageName = ps.installerPackageName; 18607 packageAbiOverride = ps.cpuAbiOverrideString; 18608 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18609 seinfo = pkg.applicationInfo.seinfo; 18610 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 18611 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 18612 } 18613 18614 // Now that we're guarded by frozen state, kill app during move 18615 final long token = Binder.clearCallingIdentity(); 18616 try { 18617 killApplication(packageName, appId, "move pkg"); 18618 } finally { 18619 Binder.restoreCallingIdentity(token); 18620 } 18621 18622 final Bundle extras = new Bundle(); 18623 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 18624 extras.putString(Intent.EXTRA_TITLE, label); 18625 mMoveCallbacks.notifyCreated(moveId, extras); 18626 18627 int installFlags; 18628 final boolean moveCompleteApp; 18629 final File measurePath; 18630 18631 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 18632 installFlags = INSTALL_INTERNAL; 18633 moveCompleteApp = !currentAsec; 18634 measurePath = Environment.getDataAppDirectory(volumeUuid); 18635 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 18636 installFlags = INSTALL_EXTERNAL; 18637 moveCompleteApp = false; 18638 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 18639 } else { 18640 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 18641 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 18642 || !volume.isMountedWritable()) { 18643 unfreezePackage(packageName); 18644 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18645 "Move location not mounted private volume"); 18646 } 18647 18648 Preconditions.checkState(!currentAsec); 18649 18650 installFlags = INSTALL_INTERNAL; 18651 moveCompleteApp = true; 18652 measurePath = Environment.getDataAppDirectory(volumeUuid); 18653 } 18654 18655 final PackageStats stats = new PackageStats(null, -1); 18656 synchronized (mInstaller) { 18657 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 18658 unfreezePackage(packageName); 18659 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18660 "Failed to measure package size"); 18661 } 18662 } 18663 18664 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 18665 + stats.dataSize); 18666 18667 final long startFreeBytes = measurePath.getFreeSpace(); 18668 final long sizeBytes; 18669 if (moveCompleteApp) { 18670 sizeBytes = stats.codeSize + stats.dataSize; 18671 } else { 18672 sizeBytes = stats.codeSize; 18673 } 18674 18675 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 18676 unfreezePackage(packageName); 18677 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18678 "Not enough free space to move"); 18679 } 18680 18681 mMoveCallbacks.notifyStatusChanged(moveId, 10); 18682 18683 final CountDownLatch installedLatch = new CountDownLatch(1); 18684 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 18685 @Override 18686 public void onUserActionRequired(Intent intent) throws RemoteException { 18687 throw new IllegalStateException(); 18688 } 18689 18690 @Override 18691 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 18692 Bundle extras) throws RemoteException { 18693 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 18694 + PackageManager.installStatusToString(returnCode, msg)); 18695 18696 installedLatch.countDown(); 18697 18698 // Regardless of success or failure of the move operation, 18699 // always unfreeze the package 18700 unfreezePackage(packageName); 18701 18702 final int status = PackageManager.installStatusToPublicStatus(returnCode); 18703 switch (status) { 18704 case PackageInstaller.STATUS_SUCCESS: 18705 mMoveCallbacks.notifyStatusChanged(moveId, 18706 PackageManager.MOVE_SUCCEEDED); 18707 break; 18708 case PackageInstaller.STATUS_FAILURE_STORAGE: 18709 mMoveCallbacks.notifyStatusChanged(moveId, 18710 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 18711 break; 18712 default: 18713 mMoveCallbacks.notifyStatusChanged(moveId, 18714 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 18715 break; 18716 } 18717 } 18718 }; 18719 18720 final MoveInfo move; 18721 if (moveCompleteApp) { 18722 // Kick off a thread to report progress estimates 18723 new Thread() { 18724 @Override 18725 public void run() { 18726 while (true) { 18727 try { 18728 if (installedLatch.await(1, TimeUnit.SECONDS)) { 18729 break; 18730 } 18731 } catch (InterruptedException ignored) { 18732 } 18733 18734 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 18735 final int progress = 10 + (int) MathUtils.constrain( 18736 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 18737 mMoveCallbacks.notifyStatusChanged(moveId, progress); 18738 } 18739 } 18740 }.start(); 18741 18742 final String dataAppName = codeFile.getName(); 18743 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 18744 dataAppName, appId, seinfo, targetSdkVersion); 18745 } else { 18746 move = null; 18747 } 18748 18749 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 18750 18751 final Message msg = mHandler.obtainMessage(INIT_COPY); 18752 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 18753 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 18754 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 18755 packageAbiOverride, null); 18756 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 18757 msg.obj = params; 18758 18759 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 18760 System.identityHashCode(msg.obj)); 18761 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 18762 System.identityHashCode(msg.obj)); 18763 18764 mHandler.sendMessage(msg); 18765 } 18766 18767 @Override 18768 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 18769 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 18770 18771 final int realMoveId = mNextMoveId.getAndIncrement(); 18772 final Bundle extras = new Bundle(); 18773 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 18774 mMoveCallbacks.notifyCreated(realMoveId, extras); 18775 18776 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 18777 @Override 18778 public void onCreated(int moveId, Bundle extras) { 18779 // Ignored 18780 } 18781 18782 @Override 18783 public void onStatusChanged(int moveId, int status, long estMillis) { 18784 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 18785 } 18786 }; 18787 18788 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18789 storage.setPrimaryStorageUuid(volumeUuid, callback); 18790 return realMoveId; 18791 } 18792 18793 @Override 18794 public int getMoveStatus(int moveId) { 18795 mContext.enforceCallingOrSelfPermission( 18796 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18797 return mMoveCallbacks.mLastStatus.get(moveId); 18798 } 18799 18800 @Override 18801 public void registerMoveCallback(IPackageMoveObserver callback) { 18802 mContext.enforceCallingOrSelfPermission( 18803 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18804 mMoveCallbacks.register(callback); 18805 } 18806 18807 @Override 18808 public void unregisterMoveCallback(IPackageMoveObserver callback) { 18809 mContext.enforceCallingOrSelfPermission( 18810 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18811 mMoveCallbacks.unregister(callback); 18812 } 18813 18814 @Override 18815 public boolean setInstallLocation(int loc) { 18816 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 18817 null); 18818 if (getInstallLocation() == loc) { 18819 return true; 18820 } 18821 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 18822 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 18823 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 18824 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 18825 return true; 18826 } 18827 return false; 18828 } 18829 18830 @Override 18831 public int getInstallLocation() { 18832 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 18833 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 18834 PackageHelper.APP_INSTALL_AUTO); 18835 } 18836 18837 /** Called by UserManagerService */ 18838 void cleanUpUser(UserManagerService userManager, int userHandle) { 18839 synchronized (mPackages) { 18840 mDirtyUsers.remove(userHandle); 18841 mUserNeedsBadging.delete(userHandle); 18842 mSettings.removeUserLPw(userHandle); 18843 mPendingBroadcasts.remove(userHandle); 18844 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 18845 } 18846 synchronized (mInstallLock) { 18847 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18848 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18849 final String volumeUuid = vol.getFsUuid(); 18850 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 18851 try { 18852 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 18853 } catch (InstallerException e) { 18854 Slog.w(TAG, "Failed to remove user data", e); 18855 } 18856 } 18857 synchronized (mPackages) { 18858 removeUnusedPackagesLILPw(userManager, userHandle); 18859 } 18860 } 18861 } 18862 18863 /** 18864 * We're removing userHandle and would like to remove any downloaded packages 18865 * that are no longer in use by any other user. 18866 * @param userHandle the user being removed 18867 */ 18868 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 18869 final boolean DEBUG_CLEAN_APKS = false; 18870 int [] users = userManager.getUserIds(); 18871 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 18872 while (psit.hasNext()) { 18873 PackageSetting ps = psit.next(); 18874 if (ps.pkg == null) { 18875 continue; 18876 } 18877 final String packageName = ps.pkg.packageName; 18878 // Skip over if system app 18879 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 18880 continue; 18881 } 18882 if (DEBUG_CLEAN_APKS) { 18883 Slog.i(TAG, "Checking package " + packageName); 18884 } 18885 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 18886 if (keep) { 18887 if (DEBUG_CLEAN_APKS) { 18888 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 18889 } 18890 } else { 18891 for (int i = 0; i < users.length; i++) { 18892 if (users[i] != userHandle && ps.getInstalled(users[i])) { 18893 keep = true; 18894 if (DEBUG_CLEAN_APKS) { 18895 Slog.i(TAG, " Keeping package " + packageName + " for user " 18896 + users[i]); 18897 } 18898 break; 18899 } 18900 } 18901 } 18902 if (!keep) { 18903 if (DEBUG_CLEAN_APKS) { 18904 Slog.i(TAG, " Removing package " + packageName); 18905 } 18906 mHandler.post(new Runnable() { 18907 public void run() { 18908 deletePackageX(packageName, userHandle, 0); 18909 } //end run 18910 }); 18911 } 18912 } 18913 } 18914 18915 /** Called by UserManagerService */ 18916 void createNewUser(int userHandle) { 18917 synchronized (mInstallLock) { 18918 try { 18919 mInstaller.createUserConfig(userHandle); 18920 } catch (InstallerException e) { 18921 Slog.w(TAG, "Failed to create user config", e); 18922 } 18923 mSettings.createNewUserLI(this, mInstaller, userHandle); 18924 } 18925 synchronized (mPackages) { 18926 applyFactoryDefaultBrowserLPw(userHandle); 18927 primeDomainVerificationsLPw(userHandle); 18928 } 18929 } 18930 18931 void newUserCreated(final int userHandle) { 18932 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 18933 // If permission review for legacy apps is required, we represent 18934 // dagerous permissions for such apps as always granted runtime 18935 // permissions to keep per user flag state whether review is needed. 18936 // Hence, if a new user is added we have to propagate dangerous 18937 // permission grants for these legacy apps. 18938 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 18939 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 18940 | UPDATE_PERMISSIONS_REPLACE_ALL); 18941 } 18942 } 18943 18944 @Override 18945 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 18946 mContext.enforceCallingOrSelfPermission( 18947 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 18948 "Only package verification agents can read the verifier device identity"); 18949 18950 synchronized (mPackages) { 18951 return mSettings.getVerifierDeviceIdentityLPw(); 18952 } 18953 } 18954 18955 @Override 18956 public void setPermissionEnforced(String permission, boolean enforced) { 18957 // TODO: Now that we no longer change GID for storage, this should to away. 18958 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 18959 "setPermissionEnforced"); 18960 if (READ_EXTERNAL_STORAGE.equals(permission)) { 18961 synchronized (mPackages) { 18962 if (mSettings.mReadExternalStorageEnforced == null 18963 || mSettings.mReadExternalStorageEnforced != enforced) { 18964 mSettings.mReadExternalStorageEnforced = enforced; 18965 mSettings.writeLPr(); 18966 } 18967 } 18968 // kill any non-foreground processes so we restart them and 18969 // grant/revoke the GID. 18970 final IActivityManager am = ActivityManagerNative.getDefault(); 18971 if (am != null) { 18972 final long token = Binder.clearCallingIdentity(); 18973 try { 18974 am.killProcessesBelowForeground("setPermissionEnforcement"); 18975 } catch (RemoteException e) { 18976 } finally { 18977 Binder.restoreCallingIdentity(token); 18978 } 18979 } 18980 } else { 18981 throw new IllegalArgumentException("No selective enforcement for " + permission); 18982 } 18983 } 18984 18985 @Override 18986 @Deprecated 18987 public boolean isPermissionEnforced(String permission) { 18988 return true; 18989 } 18990 18991 @Override 18992 public boolean isStorageLow() { 18993 final long token = Binder.clearCallingIdentity(); 18994 try { 18995 final DeviceStorageMonitorInternal 18996 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 18997 if (dsm != null) { 18998 return dsm.isMemoryLow(); 18999 } else { 19000 return false; 19001 } 19002 } finally { 19003 Binder.restoreCallingIdentity(token); 19004 } 19005 } 19006 19007 @Override 19008 public IPackageInstaller getPackageInstaller() { 19009 return mInstallerService; 19010 } 19011 19012 private boolean userNeedsBadging(int userId) { 19013 int index = mUserNeedsBadging.indexOfKey(userId); 19014 if (index < 0) { 19015 final UserInfo userInfo; 19016 final long token = Binder.clearCallingIdentity(); 19017 try { 19018 userInfo = sUserManager.getUserInfo(userId); 19019 } finally { 19020 Binder.restoreCallingIdentity(token); 19021 } 19022 final boolean b; 19023 if (userInfo != null && userInfo.isManagedProfile()) { 19024 b = true; 19025 } else { 19026 b = false; 19027 } 19028 mUserNeedsBadging.put(userId, b); 19029 return b; 19030 } 19031 return mUserNeedsBadging.valueAt(index); 19032 } 19033 19034 @Override 19035 public KeySet getKeySetByAlias(String packageName, String alias) { 19036 if (packageName == null || alias == null) { 19037 return null; 19038 } 19039 synchronized(mPackages) { 19040 final PackageParser.Package pkg = mPackages.get(packageName); 19041 if (pkg == null) { 19042 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19043 throw new IllegalArgumentException("Unknown package: " + packageName); 19044 } 19045 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19046 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 19047 } 19048 } 19049 19050 @Override 19051 public KeySet getSigningKeySet(String packageName) { 19052 if (packageName == null) { 19053 return null; 19054 } 19055 synchronized(mPackages) { 19056 final PackageParser.Package pkg = mPackages.get(packageName); 19057 if (pkg == null) { 19058 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19059 throw new IllegalArgumentException("Unknown package: " + packageName); 19060 } 19061 if (pkg.applicationInfo.uid != Binder.getCallingUid() 19062 && Process.SYSTEM_UID != Binder.getCallingUid()) { 19063 throw new SecurityException("May not access signing KeySet of other apps."); 19064 } 19065 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19066 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 19067 } 19068 } 19069 19070 @Override 19071 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 19072 if (packageName == null || ks == null) { 19073 return false; 19074 } 19075 synchronized(mPackages) { 19076 final PackageParser.Package pkg = mPackages.get(packageName); 19077 if (pkg == null) { 19078 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19079 throw new IllegalArgumentException("Unknown package: " + packageName); 19080 } 19081 IBinder ksh = ks.getToken(); 19082 if (ksh instanceof KeySetHandle) { 19083 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19084 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 19085 } 19086 return false; 19087 } 19088 } 19089 19090 @Override 19091 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 19092 if (packageName == null || ks == null) { 19093 return false; 19094 } 19095 synchronized(mPackages) { 19096 final PackageParser.Package pkg = mPackages.get(packageName); 19097 if (pkg == null) { 19098 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19099 throw new IllegalArgumentException("Unknown package: " + packageName); 19100 } 19101 IBinder ksh = ks.getToken(); 19102 if (ksh instanceof KeySetHandle) { 19103 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19104 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 19105 } 19106 return false; 19107 } 19108 } 19109 19110 private void deletePackageIfUnusedLPr(final String packageName) { 19111 PackageSetting ps = mSettings.mPackages.get(packageName); 19112 if (ps == null) { 19113 return; 19114 } 19115 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 19116 // TODO Implement atomic delete if package is unused 19117 // It is currently possible that the package will be deleted even if it is installed 19118 // after this method returns. 19119 mHandler.post(new Runnable() { 19120 public void run() { 19121 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 19122 } 19123 }); 19124 } 19125 } 19126 19127 /** 19128 * Check and throw if the given before/after packages would be considered a 19129 * downgrade. 19130 */ 19131 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 19132 throws PackageManagerException { 19133 if (after.versionCode < before.mVersionCode) { 19134 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19135 "Update version code " + after.versionCode + " is older than current " 19136 + before.mVersionCode); 19137 } else if (after.versionCode == before.mVersionCode) { 19138 if (after.baseRevisionCode < before.baseRevisionCode) { 19139 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19140 "Update base revision code " + after.baseRevisionCode 19141 + " is older than current " + before.baseRevisionCode); 19142 } 19143 19144 if (!ArrayUtils.isEmpty(after.splitNames)) { 19145 for (int i = 0; i < after.splitNames.length; i++) { 19146 final String splitName = after.splitNames[i]; 19147 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 19148 if (j != -1) { 19149 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 19150 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19151 "Update split " + splitName + " revision code " 19152 + after.splitRevisionCodes[i] + " is older than current " 19153 + before.splitRevisionCodes[j]); 19154 } 19155 } 19156 } 19157 } 19158 } 19159 } 19160 19161 private static class MoveCallbacks extends Handler { 19162 private static final int MSG_CREATED = 1; 19163 private static final int MSG_STATUS_CHANGED = 2; 19164 19165 private final RemoteCallbackList<IPackageMoveObserver> 19166 mCallbacks = new RemoteCallbackList<>(); 19167 19168 private final SparseIntArray mLastStatus = new SparseIntArray(); 19169 19170 public MoveCallbacks(Looper looper) { 19171 super(looper); 19172 } 19173 19174 public void register(IPackageMoveObserver callback) { 19175 mCallbacks.register(callback); 19176 } 19177 19178 public void unregister(IPackageMoveObserver callback) { 19179 mCallbacks.unregister(callback); 19180 } 19181 19182 @Override 19183 public void handleMessage(Message msg) { 19184 final SomeArgs args = (SomeArgs) msg.obj; 19185 final int n = mCallbacks.beginBroadcast(); 19186 for (int i = 0; i < n; i++) { 19187 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 19188 try { 19189 invokeCallback(callback, msg.what, args); 19190 } catch (RemoteException ignored) { 19191 } 19192 } 19193 mCallbacks.finishBroadcast(); 19194 args.recycle(); 19195 } 19196 19197 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 19198 throws RemoteException { 19199 switch (what) { 19200 case MSG_CREATED: { 19201 callback.onCreated(args.argi1, (Bundle) args.arg2); 19202 break; 19203 } 19204 case MSG_STATUS_CHANGED: { 19205 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 19206 break; 19207 } 19208 } 19209 } 19210 19211 private void notifyCreated(int moveId, Bundle extras) { 19212 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 19213 19214 final SomeArgs args = SomeArgs.obtain(); 19215 args.argi1 = moveId; 19216 args.arg2 = extras; 19217 obtainMessage(MSG_CREATED, args).sendToTarget(); 19218 } 19219 19220 private void notifyStatusChanged(int moveId, int status) { 19221 notifyStatusChanged(moveId, status, -1); 19222 } 19223 19224 private void notifyStatusChanged(int moveId, int status, long estMillis) { 19225 Slog.v(TAG, "Move " + moveId + " status " + status); 19226 19227 final SomeArgs args = SomeArgs.obtain(); 19228 args.argi1 = moveId; 19229 args.argi2 = status; 19230 args.arg3 = estMillis; 19231 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 19232 19233 synchronized (mLastStatus) { 19234 mLastStatus.put(moveId, status); 19235 } 19236 } 19237 } 19238 19239 private final static class OnPermissionChangeListeners extends Handler { 19240 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 19241 19242 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 19243 new RemoteCallbackList<>(); 19244 19245 public OnPermissionChangeListeners(Looper looper) { 19246 super(looper); 19247 } 19248 19249 @Override 19250 public void handleMessage(Message msg) { 19251 switch (msg.what) { 19252 case MSG_ON_PERMISSIONS_CHANGED: { 19253 final int uid = msg.arg1; 19254 handleOnPermissionsChanged(uid); 19255 } break; 19256 } 19257 } 19258 19259 public void addListenerLocked(IOnPermissionsChangeListener listener) { 19260 mPermissionListeners.register(listener); 19261 19262 } 19263 19264 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 19265 mPermissionListeners.unregister(listener); 19266 } 19267 19268 public void onPermissionsChanged(int uid) { 19269 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 19270 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 19271 } 19272 } 19273 19274 private void handleOnPermissionsChanged(int uid) { 19275 final int count = mPermissionListeners.beginBroadcast(); 19276 try { 19277 for (int i = 0; i < count; i++) { 19278 IOnPermissionsChangeListener callback = mPermissionListeners 19279 .getBroadcastItem(i); 19280 try { 19281 callback.onPermissionsChanged(uid); 19282 } catch (RemoteException e) { 19283 Log.e(TAG, "Permission listener is dead", e); 19284 } 19285 } 19286 } finally { 19287 mPermissionListeners.finishBroadcast(); 19288 } 19289 } 19290 } 19291 19292 private class PackageManagerInternalImpl extends PackageManagerInternal { 19293 @Override 19294 public void setLocationPackagesProvider(PackagesProvider provider) { 19295 synchronized (mPackages) { 19296 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 19297 } 19298 } 19299 19300 @Override 19301 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 19302 synchronized (mPackages) { 19303 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 19304 } 19305 } 19306 19307 @Override 19308 public void setSmsAppPackagesProvider(PackagesProvider provider) { 19309 synchronized (mPackages) { 19310 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 19311 } 19312 } 19313 19314 @Override 19315 public void setDialerAppPackagesProvider(PackagesProvider provider) { 19316 synchronized (mPackages) { 19317 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 19318 } 19319 } 19320 19321 @Override 19322 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 19323 synchronized (mPackages) { 19324 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 19325 } 19326 } 19327 19328 @Override 19329 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 19330 synchronized (mPackages) { 19331 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 19332 } 19333 } 19334 19335 @Override 19336 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 19337 synchronized (mPackages) { 19338 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 19339 packageName, userId); 19340 } 19341 } 19342 19343 @Override 19344 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 19345 synchronized (mPackages) { 19346 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 19347 packageName, userId); 19348 } 19349 } 19350 19351 @Override 19352 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 19353 synchronized (mPackages) { 19354 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 19355 packageName, userId); 19356 } 19357 } 19358 19359 @Override 19360 public void setKeepUninstalledPackages(final List<String> packageList) { 19361 Preconditions.checkNotNull(packageList); 19362 List<String> removedFromList = null; 19363 synchronized (mPackages) { 19364 if (mKeepUninstalledPackages != null) { 19365 final int packagesCount = mKeepUninstalledPackages.size(); 19366 for (int i = 0; i < packagesCount; i++) { 19367 String oldPackage = mKeepUninstalledPackages.get(i); 19368 if (packageList != null && packageList.contains(oldPackage)) { 19369 continue; 19370 } 19371 if (removedFromList == null) { 19372 removedFromList = new ArrayList<>(); 19373 } 19374 removedFromList.add(oldPackage); 19375 } 19376 } 19377 mKeepUninstalledPackages = new ArrayList<>(packageList); 19378 if (removedFromList != null) { 19379 final int removedCount = removedFromList.size(); 19380 for (int i = 0; i < removedCount; i++) { 19381 deletePackageIfUnusedLPr(removedFromList.get(i)); 19382 } 19383 } 19384 } 19385 } 19386 19387 @Override 19388 public boolean isPermissionsReviewRequired(String packageName, int userId) { 19389 synchronized (mPackages) { 19390 // If we do not support permission review, done. 19391 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 19392 return false; 19393 } 19394 19395 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 19396 if (packageSetting == null) { 19397 return false; 19398 } 19399 19400 // Permission review applies only to apps not supporting the new permission model. 19401 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 19402 return false; 19403 } 19404 19405 // Legacy apps have the permission and get user consent on launch. 19406 PermissionsState permissionsState = packageSetting.getPermissionsState(); 19407 return permissionsState.isPermissionReviewRequired(userId); 19408 } 19409 } 19410 19411 @Override 19412 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 19413 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 19414 } 19415 19416 @Override 19417 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 19418 int userId) { 19419 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 19420 } 19421 } 19422 19423 @Override 19424 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 19425 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 19426 synchronized (mPackages) { 19427 final long identity = Binder.clearCallingIdentity(); 19428 try { 19429 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 19430 packageNames, userId); 19431 } finally { 19432 Binder.restoreCallingIdentity(identity); 19433 } 19434 } 19435 } 19436 19437 private static void enforceSystemOrPhoneCaller(String tag) { 19438 int callingUid = Binder.getCallingUid(); 19439 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 19440 throw new SecurityException( 19441 "Cannot call " + tag + " from UID " + callingUid); 19442 } 19443 } 19444 19445 boolean isHistoricalPackageUsageAvailable() { 19446 return mPackageUsage.isHistoricalPackageUsageAvailable(); 19447 } 19448 19449 /** 19450 * Return a <b>copy</b> of the collection of packages known to the package manager. 19451 * @return A copy of the values of mPackages. 19452 */ 19453 Collection<PackageParser.Package> getPackages() { 19454 synchronized (mPackages) { 19455 return new ArrayList<>(mPackages.values()); 19456 } 19457 } 19458 19459 /** 19460 * Logs process start information (including base APK hash) to the security log. 19461 * @hide 19462 */ 19463 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 19464 String apkFile, int pid) { 19465 if (!SecurityLog.isLoggingEnabled()) { 19466 return; 19467 } 19468 Bundle data = new Bundle(); 19469 data.putLong("startTimestamp", System.currentTimeMillis()); 19470 data.putString("processName", processName); 19471 data.putInt("uid", uid); 19472 data.putString("seinfo", seinfo); 19473 data.putString("apkFile", apkFile); 19474 data.putInt("pid", pid); 19475 Message msg = mProcessLoggingHandler.obtainMessage( 19476 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 19477 msg.setData(data); 19478 mProcessLoggingHandler.sendMessage(msg); 19479 } 19480} 19481