PackageManagerService.java revision efc4a344a173ae20ec72b8c05c45b794687fda87
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.backup.IBackupManager; 110import android.content.BroadcastReceiver; 111import android.content.ComponentName; 112import android.content.Context; 113import android.content.IIntentReceiver; 114import android.content.Intent; 115import android.content.IntentFilter; 116import android.content.IntentSender; 117import android.content.IntentSender.SendIntentException; 118import android.content.ServiceConnection; 119import android.content.pm.ActivityInfo; 120import android.content.pm.ApplicationInfo; 121import android.content.pm.AppsQueryHelper; 122import android.content.pm.ComponentInfo; 123import android.content.pm.EphemeralApplicationInfo; 124import android.content.pm.EphemeralResolveInfo; 125import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 126import android.content.pm.FeatureInfo; 127import android.content.pm.IOnPermissionsChangeListener; 128import android.content.pm.IPackageDataObserver; 129import android.content.pm.IPackageDeleteObserver; 130import android.content.pm.IPackageDeleteObserver2; 131import android.content.pm.IPackageInstallObserver2; 132import android.content.pm.IPackageInstaller; 133import android.content.pm.IPackageManager; 134import android.content.pm.IPackageMoveObserver; 135import android.content.pm.IPackageStatsObserver; 136import android.content.pm.InstrumentationInfo; 137import android.content.pm.IntentFilterVerificationInfo; 138import android.content.pm.KeySet; 139import android.content.pm.PackageCleanItem; 140import android.content.pm.PackageInfo; 141import android.content.pm.PackageInfoLite; 142import android.content.pm.PackageInstaller; 143import android.content.pm.PackageManager; 144import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 145import android.content.pm.PackageManagerInternal; 146import android.content.pm.PackageParser; 147import android.content.pm.PackageParser.ActivityIntentInfo; 148import android.content.pm.PackageParser.PackageLite; 149import android.content.pm.PackageParser.PackageParserException; 150import android.content.pm.PackageStats; 151import android.content.pm.PackageUserState; 152import android.content.pm.ParceledListSlice; 153import android.content.pm.PermissionGroupInfo; 154import android.content.pm.PermissionInfo; 155import android.content.pm.ProviderInfo; 156import android.content.pm.ResolveInfo; 157import android.content.pm.ServiceInfo; 158import android.content.pm.Signature; 159import android.content.pm.UserInfo; 160import android.content.pm.VerifierDeviceIdentity; 161import android.content.pm.VerifierInfo; 162import android.content.res.Resources; 163import android.graphics.Bitmap; 164import android.hardware.display.DisplayManager; 165import android.net.Uri; 166import android.os.Binder; 167import android.os.Build; 168import android.os.Bundle; 169import android.os.Debug; 170import android.os.Environment; 171import android.os.Environment.UserEnvironment; 172import android.os.FileUtils; 173import android.os.Handler; 174import android.os.IBinder; 175import android.os.Looper; 176import android.os.Message; 177import android.os.Parcel; 178import android.os.ParcelFileDescriptor; 179import android.os.Process; 180import android.os.RemoteCallbackList; 181import android.os.RemoteException; 182import android.os.ResultReceiver; 183import android.os.SELinux; 184import android.os.ServiceManager; 185import android.os.SystemClock; 186import android.os.SystemProperties; 187import android.os.Trace; 188import android.os.UserHandle; 189import android.os.UserManager; 190import android.os.storage.IMountService; 191import android.os.storage.MountServiceInternal; 192import android.os.storage.StorageEventListener; 193import android.os.storage.StorageManager; 194import android.os.storage.VolumeInfo; 195import android.os.storage.VolumeRecord; 196import android.security.KeyStore; 197import android.security.SystemKeyStore; 198import android.system.ErrnoException; 199import android.system.Os; 200import android.text.TextUtils; 201import android.text.format.DateUtils; 202import android.util.ArrayMap; 203import android.util.ArraySet; 204import android.util.AtomicFile; 205import android.util.DisplayMetrics; 206import android.util.EventLog; 207import android.util.ExceptionUtils; 208import android.util.Log; 209import android.util.LogPrinter; 210import android.util.MathUtils; 211import android.util.PrintStreamPrinter; 212import android.util.Slog; 213import android.util.SparseArray; 214import android.util.SparseBooleanArray; 215import android.util.SparseIntArray; 216import android.util.Xml; 217import android.view.Display; 218 219import com.android.internal.R; 220import com.android.internal.annotations.GuardedBy; 221import com.android.internal.app.IMediaContainerService; 222import com.android.internal.app.ResolverActivity; 223import com.android.internal.content.NativeLibraryHelper; 224import com.android.internal.content.PackageHelper; 225import com.android.internal.os.IParcelFileDescriptorFactory; 226import com.android.internal.os.InstallerConnection.InstallerException; 227import com.android.internal.os.SomeArgs; 228import com.android.internal.os.Zygote; 229import com.android.internal.util.ArrayUtils; 230import com.android.internal.util.FastPrintWriter; 231import com.android.internal.util.FastXmlSerializer; 232import com.android.internal.util.IndentingPrintWriter; 233import com.android.internal.util.Preconditions; 234import com.android.internal.util.XmlUtils; 235import com.android.server.EventLogTags; 236import com.android.server.FgThread; 237import com.android.server.IntentResolver; 238import com.android.server.LocalServices; 239import com.android.server.ServiceThread; 240import com.android.server.SystemConfig; 241import com.android.server.Watchdog; 242import com.android.server.pm.PermissionsState.PermissionState; 243import com.android.server.pm.Settings.DatabaseVersion; 244import com.android.server.pm.Settings.VersionInfo; 245import com.android.server.storage.DeviceStorageMonitorInternal; 246 247import dalvik.system.DexFile; 248import dalvik.system.VMRuntime; 249 250import libcore.io.IoUtils; 251import libcore.util.EmptyArray; 252 253import org.xmlpull.v1.XmlPullParser; 254import org.xmlpull.v1.XmlPullParserException; 255import org.xmlpull.v1.XmlSerializer; 256 257import java.io.BufferedInputStream; 258import java.io.BufferedOutputStream; 259import java.io.BufferedReader; 260import java.io.ByteArrayInputStream; 261import java.io.ByteArrayOutputStream; 262import java.io.File; 263import java.io.FileDescriptor; 264import java.io.FileNotFoundException; 265import java.io.FileOutputStream; 266import java.io.FileReader; 267import java.io.FilenameFilter; 268import java.io.IOException; 269import java.io.InputStream; 270import java.io.PrintWriter; 271import java.nio.charset.StandardCharsets; 272import java.security.MessageDigest; 273import java.security.NoSuchAlgorithmException; 274import java.security.PublicKey; 275import java.security.cert.CertificateEncodingException; 276import java.security.cert.CertificateException; 277import java.text.SimpleDateFormat; 278import java.util.ArrayList; 279import java.util.Arrays; 280import java.util.Collection; 281import java.util.Collections; 282import java.util.Comparator; 283import java.util.Date; 284import java.util.HashSet; 285import java.util.Iterator; 286import java.util.List; 287import java.util.Map; 288import java.util.Objects; 289import java.util.Set; 290import java.util.concurrent.CountDownLatch; 291import java.util.concurrent.TimeUnit; 292import java.util.concurrent.atomic.AtomicBoolean; 293import java.util.concurrent.atomic.AtomicInteger; 294import java.util.concurrent.atomic.AtomicLong; 295 296/** 297 * Keep track of all those .apks everywhere. 298 * 299 * This is very central to the platform's security; please run the unit 300 * tests whenever making modifications here: 301 * 302runtest -c android.content.pm.PackageManagerTests frameworks-core 303 * 304 * {@hide} 305 */ 306public class PackageManagerService extends IPackageManager.Stub { 307 static final String TAG = "PackageManager"; 308 static final boolean DEBUG_SETTINGS = false; 309 static final boolean DEBUG_PREFERRED = false; 310 static final boolean DEBUG_UPGRADE = false; 311 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 312 private static final boolean DEBUG_BACKUP = false; 313 private static final boolean DEBUG_INSTALL = false; 314 private static final boolean DEBUG_REMOVE = false; 315 private static final boolean DEBUG_BROADCASTS = false; 316 private static final boolean DEBUG_SHOW_INFO = false; 317 private static final boolean DEBUG_PACKAGE_INFO = false; 318 private static final boolean DEBUG_INTENT_MATCHING = false; 319 private static final boolean DEBUG_PACKAGE_SCANNING = false; 320 private static final boolean DEBUG_VERIFY = false; 321 322 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 323 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 324 // user, but by default initialize to this. 325 static final boolean DEBUG_DEXOPT = false; 326 327 private static final boolean DEBUG_ABI_SELECTION = false; 328 private static final boolean DEBUG_EPHEMERAL = false; 329 private static final boolean DEBUG_TRIAGED_MISSING = false; 330 private static final boolean DEBUG_APP_DATA = false; 331 332 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 333 334 private static final boolean DISABLE_EPHEMERAL_APPS = true; 335 336 private static final int RADIO_UID = Process.PHONE_UID; 337 private static final int LOG_UID = Process.LOG_UID; 338 private static final int NFC_UID = Process.NFC_UID; 339 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 340 private static final int SHELL_UID = Process.SHELL_UID; 341 342 // Cap the size of permission trees that 3rd party apps can define 343 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 344 345 // Suffix used during package installation when copying/moving 346 // package apks to install directory. 347 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 348 349 static final int SCAN_NO_DEX = 1<<1; 350 static final int SCAN_FORCE_DEX = 1<<2; 351 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 352 static final int SCAN_NEW_INSTALL = 1<<4; 353 static final int SCAN_NO_PATHS = 1<<5; 354 static final int SCAN_UPDATE_TIME = 1<<6; 355 static final int SCAN_DEFER_DEX = 1<<7; 356 static final int SCAN_BOOTING = 1<<8; 357 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 358 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 359 static final int SCAN_REPLACING = 1<<11; 360 static final int SCAN_REQUIRE_KNOWN = 1<<12; 361 static final int SCAN_MOVE = 1<<13; 362 static final int SCAN_INITIAL = 1<<14; 363 static final int SCAN_CHECK_ONLY = 1<<15; 364 static final int SCAN_DONT_KILL_APP = 1<<17; 365 366 static final int REMOVE_CHATTY = 1<<16; 367 368 private static final int[] EMPTY_INT_ARRAY = new int[0]; 369 370 /** 371 * Timeout (in milliseconds) after which the watchdog should declare that 372 * our handler thread is wedged. The usual default for such things is one 373 * minute but we sometimes do very lengthy I/O operations on this thread, 374 * such as installing multi-gigabyte applications, so ours needs to be longer. 375 */ 376 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 377 378 /** 379 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 380 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 381 * settings entry if available, otherwise we use the hardcoded default. If it's been 382 * more than this long since the last fstrim, we force one during the boot sequence. 383 * 384 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 385 * one gets run at the next available charging+idle time. This final mandatory 386 * no-fstrim check kicks in only of the other scheduling criteria is never met. 387 */ 388 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 389 390 /** 391 * Whether verification is enabled by default. 392 */ 393 private static final boolean DEFAULT_VERIFY_ENABLE = true; 394 395 /** 396 * The default maximum time to wait for the verification agent to return in 397 * milliseconds. 398 */ 399 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 400 401 /** 402 * The default response for package verification timeout. 403 * 404 * This can be either PackageManager.VERIFICATION_ALLOW or 405 * PackageManager.VERIFICATION_REJECT. 406 */ 407 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 408 409 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 410 411 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 412 DEFAULT_CONTAINER_PACKAGE, 413 "com.android.defcontainer.DefaultContainerService"); 414 415 private static final String KILL_APP_REASON_GIDS_CHANGED = 416 "permission grant or revoke changed gids"; 417 418 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 419 "permissions revoked"; 420 421 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 422 423 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 424 425 /** Permission grant: not grant the permission. */ 426 private static final int GRANT_DENIED = 1; 427 428 /** Permission grant: grant the permission as an install permission. */ 429 private static final int GRANT_INSTALL = 2; 430 431 /** Permission grant: grant the permission as a runtime one. */ 432 private static final int GRANT_RUNTIME = 3; 433 434 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 435 private static final int GRANT_UPGRADE = 4; 436 437 /** Canonical intent used to identify what counts as a "web browser" app */ 438 private static final Intent sBrowserIntent; 439 static { 440 sBrowserIntent = new Intent(); 441 sBrowserIntent.setAction(Intent.ACTION_VIEW); 442 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 443 sBrowserIntent.setData(Uri.parse("http:")); 444 } 445 446 // Compilation reasons. 447 public static final int REASON_FIRST_BOOT = 0; 448 public static final int REASON_BOOT = 1; 449 public static final int REASON_INSTALL = 2; 450 public static final int REASON_BACKGROUND_DEXOPT = 3; 451 public static final int REASON_AB_OTA = 4; 452 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 453 public static final int REASON_SHARED_APK = 6; 454 public static final int REASON_FORCED_DEXOPT = 7; 455 456 public static final int REASON_LAST = REASON_FORCED_DEXOPT; 457 458 final ServiceThread mHandlerThread; 459 460 final PackageHandler mHandler; 461 462 /** 463 * Messages for {@link #mHandler} that need to wait for system ready before 464 * being dispatched. 465 */ 466 private ArrayList<Message> mPostSystemReadyMessages; 467 468 final int mSdkVersion = Build.VERSION.SDK_INT; 469 470 final Context mContext; 471 final boolean mFactoryTest; 472 final boolean mOnlyCore; 473 final DisplayMetrics mMetrics; 474 final int mDefParseFlags; 475 final String[] mSeparateProcesses; 476 final boolean mIsUpgrade; 477 final boolean mIsPreNUpgrade; 478 479 /** The location for ASEC container files on internal storage. */ 480 final String mAsecInternalPath; 481 482 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 483 // LOCK HELD. Can be called with mInstallLock held. 484 @GuardedBy("mInstallLock") 485 final Installer mInstaller; 486 487 /** Directory where installed third-party apps stored */ 488 final File mAppInstallDir; 489 final File mEphemeralInstallDir; 490 491 /** 492 * Directory to which applications installed internally have their 493 * 32 bit native libraries copied. 494 */ 495 private File mAppLib32InstallDir; 496 497 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 498 // apps. 499 final File mDrmAppPrivateInstallDir; 500 501 // ---------------------------------------------------------------- 502 503 // Lock for state used when installing and doing other long running 504 // operations. Methods that must be called with this lock held have 505 // the suffix "LI". 506 final Object mInstallLock = new Object(); 507 508 // ---------------------------------------------------------------- 509 510 // Keys are String (package name), values are Package. This also serves 511 // as the lock for the global state. Methods that must be called with 512 // this lock held have the prefix "LP". 513 @GuardedBy("mPackages") 514 final ArrayMap<String, PackageParser.Package> mPackages = 515 new ArrayMap<String, PackageParser.Package>(); 516 517 final ArrayMap<String, Set<String>> mKnownCodebase = 518 new ArrayMap<String, Set<String>>(); 519 520 // Tracks available target package names -> overlay package paths. 521 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 522 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 523 524 /** 525 * Tracks new system packages [received in an OTA] that we expect to 526 * find updated user-installed versions. Keys are package name, values 527 * are package location. 528 */ 529 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 530 531 /** 532 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 533 */ 534 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 535 /** 536 * Whether or not system app permissions should be promoted from install to runtime. 537 */ 538 boolean mPromoteSystemApps; 539 540 final Settings mSettings; 541 boolean mRestoredSettings; 542 543 // System configuration read by SystemConfig. 544 final int[] mGlobalGids; 545 final SparseArray<ArraySet<String>> mSystemPermissions; 546 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 547 548 // If mac_permissions.xml was found for seinfo labeling. 549 boolean mFoundPolicyFile; 550 551 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 552 553 public static final class SharedLibraryEntry { 554 public final String path; 555 public final String apk; 556 557 SharedLibraryEntry(String _path, String _apk) { 558 path = _path; 559 apk = _apk; 560 } 561 } 562 563 // Currently known shared libraries. 564 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 565 new ArrayMap<String, SharedLibraryEntry>(); 566 567 // All available activities, for your resolving pleasure. 568 final ActivityIntentResolver mActivities = 569 new ActivityIntentResolver(); 570 571 // All available receivers, for your resolving pleasure. 572 final ActivityIntentResolver mReceivers = 573 new ActivityIntentResolver(); 574 575 // All available services, for your resolving pleasure. 576 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 577 578 // All available providers, for your resolving pleasure. 579 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 580 581 // Mapping from provider base names (first directory in content URI codePath) 582 // to the provider information. 583 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 584 new ArrayMap<String, PackageParser.Provider>(); 585 586 // Mapping from instrumentation class names to info about them. 587 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 588 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 589 590 // Mapping from permission names to info about them. 591 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 592 new ArrayMap<String, PackageParser.PermissionGroup>(); 593 594 // Packages whose data we have transfered into another package, thus 595 // should no longer exist. 596 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 597 598 // Broadcast actions that are only available to the system. 599 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 600 601 /** List of packages waiting for verification. */ 602 final SparseArray<PackageVerificationState> mPendingVerification 603 = new SparseArray<PackageVerificationState>(); 604 605 /** Set of packages associated with each app op permission. */ 606 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 607 608 final PackageInstallerService mInstallerService; 609 610 private final PackageDexOptimizer mPackageDexOptimizer; 611 612 private AtomicInteger mNextMoveId = new AtomicInteger(); 613 private final MoveCallbacks mMoveCallbacks; 614 615 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 616 617 // Cache of users who need badging. 618 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 619 620 /** Token for keys in mPendingVerification. */ 621 private int mPendingVerificationToken = 0; 622 623 volatile boolean mSystemReady; 624 volatile boolean mSafeMode; 625 volatile boolean mHasSystemUidErrors; 626 627 ApplicationInfo mAndroidApplication; 628 final ActivityInfo mResolveActivity = new ActivityInfo(); 629 final ResolveInfo mResolveInfo = new ResolveInfo(); 630 ComponentName mResolveComponentName; 631 PackageParser.Package mPlatformPackage; 632 ComponentName mCustomResolverComponentName; 633 634 boolean mResolverReplaced = false; 635 636 private final @Nullable ComponentName mIntentFilterVerifierComponent; 637 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 638 639 private int mIntentFilterVerificationToken = 0; 640 641 /** Component that knows whether or not an ephemeral application exists */ 642 final ComponentName mEphemeralResolverComponent; 643 /** The service connection to the ephemeral resolver */ 644 final EphemeralResolverConnection mEphemeralResolverConnection; 645 646 /** Component used to install ephemeral applications */ 647 final ComponentName mEphemeralInstallerComponent; 648 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 649 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 650 651 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 652 = new SparseArray<IntentFilterVerificationState>(); 653 654 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 655 new DefaultPermissionGrantPolicy(this); 656 657 // List of packages names to keep cached, even if they are uninstalled for all users 658 private List<String> mKeepUninstalledPackages; 659 660 private static class IFVerificationParams { 661 PackageParser.Package pkg; 662 boolean replacing; 663 int userId; 664 int verifierUid; 665 666 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 667 int _userId, int _verifierUid) { 668 pkg = _pkg; 669 replacing = _replacing; 670 userId = _userId; 671 replacing = _replacing; 672 verifierUid = _verifierUid; 673 } 674 } 675 676 private interface IntentFilterVerifier<T extends IntentFilter> { 677 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 678 T filter, String packageName); 679 void startVerifications(int userId); 680 void receiveVerificationResponse(int verificationId); 681 } 682 683 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 684 private Context mContext; 685 private ComponentName mIntentFilterVerifierComponent; 686 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 687 688 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 689 mContext = context; 690 mIntentFilterVerifierComponent = verifierComponent; 691 } 692 693 private String getDefaultScheme() { 694 return IntentFilter.SCHEME_HTTPS; 695 } 696 697 @Override 698 public void startVerifications(int userId) { 699 // Launch verifications requests 700 int count = mCurrentIntentFilterVerifications.size(); 701 for (int n=0; n<count; n++) { 702 int verificationId = mCurrentIntentFilterVerifications.get(n); 703 final IntentFilterVerificationState ivs = 704 mIntentFilterVerificationStates.get(verificationId); 705 706 String packageName = ivs.getPackageName(); 707 708 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 709 final int filterCount = filters.size(); 710 ArraySet<String> domainsSet = new ArraySet<>(); 711 for (int m=0; m<filterCount; m++) { 712 PackageParser.ActivityIntentInfo filter = filters.get(m); 713 domainsSet.addAll(filter.getHostsList()); 714 } 715 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 716 synchronized (mPackages) { 717 if (mSettings.createIntentFilterVerificationIfNeededLPw( 718 packageName, domainsList) != null) { 719 scheduleWriteSettingsLocked(); 720 } 721 } 722 sendVerificationRequest(userId, verificationId, ivs); 723 } 724 mCurrentIntentFilterVerifications.clear(); 725 } 726 727 private void sendVerificationRequest(int userId, int verificationId, 728 IntentFilterVerificationState ivs) { 729 730 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 731 verificationIntent.putExtra( 732 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 733 verificationId); 734 verificationIntent.putExtra( 735 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 736 getDefaultScheme()); 737 verificationIntent.putExtra( 738 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 739 ivs.getHostsString()); 740 verificationIntent.putExtra( 741 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 742 ivs.getPackageName()); 743 verificationIntent.setComponent(mIntentFilterVerifierComponent); 744 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 745 746 UserHandle user = new UserHandle(userId); 747 mContext.sendBroadcastAsUser(verificationIntent, user); 748 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 749 "Sending IntentFilter verification broadcast"); 750 } 751 752 public void receiveVerificationResponse(int verificationId) { 753 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 754 755 final boolean verified = ivs.isVerified(); 756 757 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 758 final int count = filters.size(); 759 if (DEBUG_DOMAIN_VERIFICATION) { 760 Slog.i(TAG, "Received verification response " + verificationId 761 + " for " + count + " filters, verified=" + verified); 762 } 763 for (int n=0; n<count; n++) { 764 PackageParser.ActivityIntentInfo filter = filters.get(n); 765 filter.setVerified(verified); 766 767 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 768 + " verified with result:" + verified + " and hosts:" 769 + ivs.getHostsString()); 770 } 771 772 mIntentFilterVerificationStates.remove(verificationId); 773 774 final String packageName = ivs.getPackageName(); 775 IntentFilterVerificationInfo ivi = null; 776 777 synchronized (mPackages) { 778 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 779 } 780 if (ivi == null) { 781 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 782 + verificationId + " packageName:" + packageName); 783 return; 784 } 785 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 786 "Updating IntentFilterVerificationInfo for package " + packageName 787 +" verificationId:" + verificationId); 788 789 synchronized (mPackages) { 790 if (verified) { 791 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 792 } else { 793 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 794 } 795 scheduleWriteSettingsLocked(); 796 797 final int userId = ivs.getUserId(); 798 if (userId != UserHandle.USER_ALL) { 799 final int userStatus = 800 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 801 802 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 803 boolean needUpdate = false; 804 805 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 806 // already been set by the User thru the Disambiguation dialog 807 switch (userStatus) { 808 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 809 if (verified) { 810 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 811 } else { 812 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 813 } 814 needUpdate = true; 815 break; 816 817 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 818 if (verified) { 819 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 820 needUpdate = true; 821 } 822 break; 823 824 default: 825 // Nothing to do 826 } 827 828 if (needUpdate) { 829 mSettings.updateIntentFilterVerificationStatusLPw( 830 packageName, updatedStatus, userId); 831 scheduleWritePackageRestrictionsLocked(userId); 832 } 833 } 834 } 835 } 836 837 @Override 838 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 839 ActivityIntentInfo filter, String packageName) { 840 if (!hasValidDomains(filter)) { 841 return false; 842 } 843 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 844 if (ivs == null) { 845 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 846 packageName); 847 } 848 if (DEBUG_DOMAIN_VERIFICATION) { 849 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 850 } 851 ivs.addFilter(filter); 852 return true; 853 } 854 855 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 856 int userId, int verificationId, String packageName) { 857 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 858 verifierUid, userId, packageName); 859 ivs.setPendingState(); 860 synchronized (mPackages) { 861 mIntentFilterVerificationStates.append(verificationId, ivs); 862 mCurrentIntentFilterVerifications.add(verificationId); 863 } 864 return ivs; 865 } 866 } 867 868 private static boolean hasValidDomains(ActivityIntentInfo filter) { 869 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 870 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 871 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 872 } 873 874 // Set of pending broadcasts for aggregating enable/disable of components. 875 static class PendingPackageBroadcasts { 876 // for each user id, a map of <package name -> components within that package> 877 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 878 879 public PendingPackageBroadcasts() { 880 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 881 } 882 883 public ArrayList<String> get(int userId, String packageName) { 884 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 885 return packages.get(packageName); 886 } 887 888 public void put(int userId, String packageName, ArrayList<String> components) { 889 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 890 packages.put(packageName, components); 891 } 892 893 public void remove(int userId, String packageName) { 894 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 895 if (packages != null) { 896 packages.remove(packageName); 897 } 898 } 899 900 public void remove(int userId) { 901 mUidMap.remove(userId); 902 } 903 904 public int userIdCount() { 905 return mUidMap.size(); 906 } 907 908 public int userIdAt(int n) { 909 return mUidMap.keyAt(n); 910 } 911 912 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 913 return mUidMap.get(userId); 914 } 915 916 public int size() { 917 // total number of pending broadcast entries across all userIds 918 int num = 0; 919 for (int i = 0; i< mUidMap.size(); i++) { 920 num += mUidMap.valueAt(i).size(); 921 } 922 return num; 923 } 924 925 public void clear() { 926 mUidMap.clear(); 927 } 928 929 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 930 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 931 if (map == null) { 932 map = new ArrayMap<String, ArrayList<String>>(); 933 mUidMap.put(userId, map); 934 } 935 return map; 936 } 937 } 938 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 939 940 // Service Connection to remote media container service to copy 941 // package uri's from external media onto secure containers 942 // or internal storage. 943 private IMediaContainerService mContainerService = null; 944 945 static final int SEND_PENDING_BROADCAST = 1; 946 static final int MCS_BOUND = 3; 947 static final int END_COPY = 4; 948 static final int INIT_COPY = 5; 949 static final int MCS_UNBIND = 6; 950 static final int START_CLEANING_PACKAGE = 7; 951 static final int FIND_INSTALL_LOC = 8; 952 static final int POST_INSTALL = 9; 953 static final int MCS_RECONNECT = 10; 954 static final int MCS_GIVE_UP = 11; 955 static final int UPDATED_MEDIA_STATUS = 12; 956 static final int WRITE_SETTINGS = 13; 957 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 958 static final int PACKAGE_VERIFIED = 15; 959 static final int CHECK_PENDING_VERIFICATION = 16; 960 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 961 static final int INTENT_FILTER_VERIFIED = 18; 962 963 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 964 965 // Delay time in millisecs 966 static final int BROADCAST_DELAY = 10 * 1000; 967 968 static UserManagerService sUserManager; 969 970 // Stores a list of users whose package restrictions file needs to be updated 971 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 972 973 final private DefaultContainerConnection mDefContainerConn = 974 new DefaultContainerConnection(); 975 class DefaultContainerConnection implements ServiceConnection { 976 public void onServiceConnected(ComponentName name, IBinder service) { 977 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 978 IMediaContainerService imcs = 979 IMediaContainerService.Stub.asInterface(service); 980 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 981 } 982 983 public void onServiceDisconnected(ComponentName name) { 984 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 985 } 986 } 987 988 // Recordkeeping of restore-after-install operations that are currently in flight 989 // between the Package Manager and the Backup Manager 990 static class PostInstallData { 991 public InstallArgs args; 992 public PackageInstalledInfo res; 993 994 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 995 args = _a; 996 res = _r; 997 } 998 } 999 1000 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1001 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1002 1003 // XML tags for backup/restore of various bits of state 1004 private static final String TAG_PREFERRED_BACKUP = "pa"; 1005 private static final String TAG_DEFAULT_APPS = "da"; 1006 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1007 1008 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1009 private static final String TAG_ALL_GRANTS = "rt-grants"; 1010 private static final String TAG_GRANT = "grant"; 1011 private static final String ATTR_PACKAGE_NAME = "pkg"; 1012 1013 private static final String TAG_PERMISSION = "perm"; 1014 private static final String ATTR_PERMISSION_NAME = "name"; 1015 private static final String ATTR_IS_GRANTED = "g"; 1016 private static final String ATTR_USER_SET = "set"; 1017 private static final String ATTR_USER_FIXED = "fixed"; 1018 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1019 1020 // System/policy permission grants are not backed up 1021 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1022 FLAG_PERMISSION_POLICY_FIXED 1023 | FLAG_PERMISSION_SYSTEM_FIXED 1024 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1025 1026 // And we back up these user-adjusted states 1027 private static final int USER_RUNTIME_GRANT_MASK = 1028 FLAG_PERMISSION_USER_SET 1029 | FLAG_PERMISSION_USER_FIXED 1030 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1031 1032 final @Nullable String mRequiredVerifierPackage; 1033 final @Nullable String mRequiredInstallerPackage; 1034 1035 private final PackageUsage mPackageUsage = new PackageUsage(); 1036 1037 private class PackageUsage { 1038 private static final int WRITE_INTERVAL 1039 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1040 1041 private final Object mFileLock = new Object(); 1042 private final AtomicLong mLastWritten = new AtomicLong(0); 1043 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1044 1045 private boolean mIsHistoricalPackageUsageAvailable = true; 1046 1047 boolean isHistoricalPackageUsageAvailable() { 1048 return mIsHistoricalPackageUsageAvailable; 1049 } 1050 1051 void write(boolean force) { 1052 if (force) { 1053 writeInternal(); 1054 return; 1055 } 1056 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1057 && !DEBUG_DEXOPT) { 1058 return; 1059 } 1060 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1061 new Thread("PackageUsage_DiskWriter") { 1062 @Override 1063 public void run() { 1064 try { 1065 writeInternal(); 1066 } finally { 1067 mBackgroundWriteRunning.set(false); 1068 } 1069 } 1070 }.start(); 1071 } 1072 } 1073 1074 private void writeInternal() { 1075 synchronized (mPackages) { 1076 synchronized (mFileLock) { 1077 AtomicFile file = getFile(); 1078 FileOutputStream f = null; 1079 try { 1080 f = file.startWrite(); 1081 BufferedOutputStream out = new BufferedOutputStream(f); 1082 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1083 StringBuilder sb = new StringBuilder(); 1084 for (PackageParser.Package pkg : mPackages.values()) { 1085 if (pkg.mLastPackageUsageTimeInMills == 0) { 1086 continue; 1087 } 1088 sb.setLength(0); 1089 sb.append(pkg.packageName); 1090 sb.append(' '); 1091 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1092 sb.append('\n'); 1093 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1094 } 1095 out.flush(); 1096 file.finishWrite(f); 1097 } catch (IOException e) { 1098 if (f != null) { 1099 file.failWrite(f); 1100 } 1101 Log.e(TAG, "Failed to write package usage times", e); 1102 } 1103 } 1104 } 1105 mLastWritten.set(SystemClock.elapsedRealtime()); 1106 } 1107 1108 void readLP() { 1109 synchronized (mFileLock) { 1110 AtomicFile file = getFile(); 1111 BufferedInputStream in = null; 1112 try { 1113 in = new BufferedInputStream(file.openRead()); 1114 StringBuffer sb = new StringBuffer(); 1115 while (true) { 1116 String packageName = readToken(in, sb, ' '); 1117 if (packageName == null) { 1118 break; 1119 } 1120 String timeInMillisString = readToken(in, sb, '\n'); 1121 if (timeInMillisString == null) { 1122 throw new IOException("Failed to find last usage time for package " 1123 + packageName); 1124 } 1125 PackageParser.Package pkg = mPackages.get(packageName); 1126 if (pkg == null) { 1127 continue; 1128 } 1129 long timeInMillis; 1130 try { 1131 timeInMillis = Long.parseLong(timeInMillisString); 1132 } catch (NumberFormatException e) { 1133 throw new IOException("Failed to parse " + timeInMillisString 1134 + " as a long.", e); 1135 } 1136 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1137 } 1138 } catch (FileNotFoundException expected) { 1139 mIsHistoricalPackageUsageAvailable = false; 1140 } catch (IOException e) { 1141 Log.w(TAG, "Failed to read package usage times", e); 1142 } finally { 1143 IoUtils.closeQuietly(in); 1144 } 1145 } 1146 mLastWritten.set(SystemClock.elapsedRealtime()); 1147 } 1148 1149 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1150 throws IOException { 1151 sb.setLength(0); 1152 while (true) { 1153 int ch = in.read(); 1154 if (ch == -1) { 1155 if (sb.length() == 0) { 1156 return null; 1157 } 1158 throw new IOException("Unexpected EOF"); 1159 } 1160 if (ch == endOfToken) { 1161 return sb.toString(); 1162 } 1163 sb.append((char)ch); 1164 } 1165 } 1166 1167 private AtomicFile getFile() { 1168 File dataDir = Environment.getDataDirectory(); 1169 File systemDir = new File(dataDir, "system"); 1170 File fname = new File(systemDir, "package-usage.list"); 1171 return new AtomicFile(fname); 1172 } 1173 } 1174 1175 class PackageHandler extends Handler { 1176 private boolean mBound = false; 1177 final ArrayList<HandlerParams> mPendingInstalls = 1178 new ArrayList<HandlerParams>(); 1179 1180 private boolean connectToService() { 1181 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1182 " DefaultContainerService"); 1183 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1184 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1185 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1186 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1187 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1188 mBound = true; 1189 return true; 1190 } 1191 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1192 return false; 1193 } 1194 1195 private void disconnectService() { 1196 mContainerService = null; 1197 mBound = false; 1198 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1199 mContext.unbindService(mDefContainerConn); 1200 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1201 } 1202 1203 PackageHandler(Looper looper) { 1204 super(looper); 1205 } 1206 1207 public void handleMessage(Message msg) { 1208 try { 1209 doHandleMessage(msg); 1210 } finally { 1211 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1212 } 1213 } 1214 1215 void doHandleMessage(Message msg) { 1216 switch (msg.what) { 1217 case INIT_COPY: { 1218 HandlerParams params = (HandlerParams) msg.obj; 1219 int idx = mPendingInstalls.size(); 1220 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1221 // If a bind was already initiated we dont really 1222 // need to do anything. The pending install 1223 // will be processed later on. 1224 if (!mBound) { 1225 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1226 System.identityHashCode(mHandler)); 1227 // If this is the only one pending we might 1228 // have to bind to the service again. 1229 if (!connectToService()) { 1230 Slog.e(TAG, "Failed to bind to media container service"); 1231 params.serviceError(); 1232 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1233 System.identityHashCode(mHandler)); 1234 if (params.traceMethod != null) { 1235 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1236 params.traceCookie); 1237 } 1238 return; 1239 } else { 1240 // Once we bind to the service, the first 1241 // pending request will be processed. 1242 mPendingInstalls.add(idx, params); 1243 } 1244 } else { 1245 mPendingInstalls.add(idx, params); 1246 // Already bound to the service. Just make 1247 // sure we trigger off processing the first request. 1248 if (idx == 0) { 1249 mHandler.sendEmptyMessage(MCS_BOUND); 1250 } 1251 } 1252 break; 1253 } 1254 case MCS_BOUND: { 1255 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1256 if (msg.obj != null) { 1257 mContainerService = (IMediaContainerService) msg.obj; 1258 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1259 System.identityHashCode(mHandler)); 1260 } 1261 if (mContainerService == null) { 1262 if (!mBound) { 1263 // Something seriously wrong since we are not bound and we are not 1264 // waiting for connection. Bail out. 1265 Slog.e(TAG, "Cannot bind to media container service"); 1266 for (HandlerParams params : mPendingInstalls) { 1267 // Indicate service bind error 1268 params.serviceError(); 1269 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1270 System.identityHashCode(params)); 1271 if (params.traceMethod != null) { 1272 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1273 params.traceMethod, params.traceCookie); 1274 } 1275 return; 1276 } 1277 mPendingInstalls.clear(); 1278 } else { 1279 Slog.w(TAG, "Waiting to connect to media container service"); 1280 } 1281 } else if (mPendingInstalls.size() > 0) { 1282 HandlerParams params = mPendingInstalls.get(0); 1283 if (params != null) { 1284 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1285 System.identityHashCode(params)); 1286 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1287 if (params.startCopy()) { 1288 // We are done... look for more work or to 1289 // go idle. 1290 if (DEBUG_SD_INSTALL) Log.i(TAG, 1291 "Checking for more work or unbind..."); 1292 // Delete pending install 1293 if (mPendingInstalls.size() > 0) { 1294 mPendingInstalls.remove(0); 1295 } 1296 if (mPendingInstalls.size() == 0) { 1297 if (mBound) { 1298 if (DEBUG_SD_INSTALL) Log.i(TAG, 1299 "Posting delayed MCS_UNBIND"); 1300 removeMessages(MCS_UNBIND); 1301 Message ubmsg = obtainMessage(MCS_UNBIND); 1302 // Unbind after a little delay, to avoid 1303 // continual thrashing. 1304 sendMessageDelayed(ubmsg, 10000); 1305 } 1306 } else { 1307 // There are more pending requests in queue. 1308 // Just post MCS_BOUND message to trigger processing 1309 // of next pending install. 1310 if (DEBUG_SD_INSTALL) Log.i(TAG, 1311 "Posting MCS_BOUND for next work"); 1312 mHandler.sendEmptyMessage(MCS_BOUND); 1313 } 1314 } 1315 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1316 } 1317 } else { 1318 // Should never happen ideally. 1319 Slog.w(TAG, "Empty queue"); 1320 } 1321 break; 1322 } 1323 case MCS_RECONNECT: { 1324 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1325 if (mPendingInstalls.size() > 0) { 1326 if (mBound) { 1327 disconnectService(); 1328 } 1329 if (!connectToService()) { 1330 Slog.e(TAG, "Failed to bind to media container service"); 1331 for (HandlerParams params : mPendingInstalls) { 1332 // Indicate service bind error 1333 params.serviceError(); 1334 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1335 System.identityHashCode(params)); 1336 } 1337 mPendingInstalls.clear(); 1338 } 1339 } 1340 break; 1341 } 1342 case MCS_UNBIND: { 1343 // If there is no actual work left, then time to unbind. 1344 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1345 1346 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1347 if (mBound) { 1348 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1349 1350 disconnectService(); 1351 } 1352 } else if (mPendingInstalls.size() > 0) { 1353 // There are more pending requests in queue. 1354 // Just post MCS_BOUND message to trigger processing 1355 // of next pending install. 1356 mHandler.sendEmptyMessage(MCS_BOUND); 1357 } 1358 1359 break; 1360 } 1361 case MCS_GIVE_UP: { 1362 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1363 HandlerParams params = mPendingInstalls.remove(0); 1364 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1365 System.identityHashCode(params)); 1366 break; 1367 } 1368 case SEND_PENDING_BROADCAST: { 1369 String packages[]; 1370 ArrayList<String> components[]; 1371 int size = 0; 1372 int uids[]; 1373 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1374 synchronized (mPackages) { 1375 if (mPendingBroadcasts == null) { 1376 return; 1377 } 1378 size = mPendingBroadcasts.size(); 1379 if (size <= 0) { 1380 // Nothing to be done. Just return 1381 return; 1382 } 1383 packages = new String[size]; 1384 components = new ArrayList[size]; 1385 uids = new int[size]; 1386 int i = 0; // filling out the above arrays 1387 1388 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1389 int packageUserId = mPendingBroadcasts.userIdAt(n); 1390 Iterator<Map.Entry<String, ArrayList<String>>> it 1391 = mPendingBroadcasts.packagesForUserId(packageUserId) 1392 .entrySet().iterator(); 1393 while (it.hasNext() && i < size) { 1394 Map.Entry<String, ArrayList<String>> ent = it.next(); 1395 packages[i] = ent.getKey(); 1396 components[i] = ent.getValue(); 1397 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1398 uids[i] = (ps != null) 1399 ? UserHandle.getUid(packageUserId, ps.appId) 1400 : -1; 1401 i++; 1402 } 1403 } 1404 size = i; 1405 mPendingBroadcasts.clear(); 1406 } 1407 // Send broadcasts 1408 for (int i = 0; i < size; i++) { 1409 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1410 } 1411 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1412 break; 1413 } 1414 case START_CLEANING_PACKAGE: { 1415 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1416 final String packageName = (String)msg.obj; 1417 final int userId = msg.arg1; 1418 final boolean andCode = msg.arg2 != 0; 1419 synchronized (mPackages) { 1420 if (userId == UserHandle.USER_ALL) { 1421 int[] users = sUserManager.getUserIds(); 1422 for (int user : users) { 1423 mSettings.addPackageToCleanLPw( 1424 new PackageCleanItem(user, packageName, andCode)); 1425 } 1426 } else { 1427 mSettings.addPackageToCleanLPw( 1428 new PackageCleanItem(userId, packageName, andCode)); 1429 } 1430 } 1431 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1432 startCleaningPackages(); 1433 } break; 1434 case POST_INSTALL: { 1435 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1436 1437 PostInstallData data = mRunningInstalls.get(msg.arg1); 1438 mRunningInstalls.delete(msg.arg1); 1439 1440 if (data != null) { 1441 InstallArgs args = data.args; 1442 PackageInstalledInfo parentRes = data.res; 1443 1444 final boolean grantPermissions = (args.installFlags 1445 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1446 final boolean killApp = (args.installFlags 1447 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1448 final String[] grantedPermissions = args.installGrantPermissions; 1449 1450 // Handle the parent package 1451 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1452 grantedPermissions, args.observer); 1453 1454 // Handle the child packages 1455 final int childCount = (parentRes.addedChildPackages != null) 1456 ? parentRes.addedChildPackages.size() : 0; 1457 for (int i = 0; i < childCount; i++) { 1458 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1459 handlePackagePostInstall(childRes, grantPermissions, killApp, 1460 grantedPermissions, args.observer); 1461 } 1462 1463 // Log tracing if needed 1464 if (args.traceMethod != null) { 1465 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1466 args.traceCookie); 1467 } 1468 } else { 1469 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1470 } 1471 1472 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1473 } break; 1474 case UPDATED_MEDIA_STATUS: { 1475 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1476 boolean reportStatus = msg.arg1 == 1; 1477 boolean doGc = msg.arg2 == 1; 1478 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1479 if (doGc) { 1480 // Force a gc to clear up stale containers. 1481 Runtime.getRuntime().gc(); 1482 } 1483 if (msg.obj != null) { 1484 @SuppressWarnings("unchecked") 1485 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1486 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1487 // Unload containers 1488 unloadAllContainers(args); 1489 } 1490 if (reportStatus) { 1491 try { 1492 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1493 PackageHelper.getMountService().finishMediaUpdate(); 1494 } catch (RemoteException e) { 1495 Log.e(TAG, "MountService not running?"); 1496 } 1497 } 1498 } break; 1499 case WRITE_SETTINGS: { 1500 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1501 synchronized (mPackages) { 1502 removeMessages(WRITE_SETTINGS); 1503 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1504 mSettings.writeLPr(); 1505 mDirtyUsers.clear(); 1506 } 1507 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1508 } break; 1509 case WRITE_PACKAGE_RESTRICTIONS: { 1510 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1511 synchronized (mPackages) { 1512 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1513 for (int userId : mDirtyUsers) { 1514 mSettings.writePackageRestrictionsLPr(userId); 1515 } 1516 mDirtyUsers.clear(); 1517 } 1518 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1519 } break; 1520 case CHECK_PENDING_VERIFICATION: { 1521 final int verificationId = msg.arg1; 1522 final PackageVerificationState state = mPendingVerification.get(verificationId); 1523 1524 if ((state != null) && !state.timeoutExtended()) { 1525 final InstallArgs args = state.getInstallArgs(); 1526 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1527 1528 Slog.i(TAG, "Verification timed out for " + originUri); 1529 mPendingVerification.remove(verificationId); 1530 1531 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1532 1533 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1534 Slog.i(TAG, "Continuing with installation of " + originUri); 1535 state.setVerifierResponse(Binder.getCallingUid(), 1536 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1537 broadcastPackageVerified(verificationId, originUri, 1538 PackageManager.VERIFICATION_ALLOW, 1539 state.getInstallArgs().getUser()); 1540 try { 1541 ret = args.copyApk(mContainerService, true); 1542 } catch (RemoteException e) { 1543 Slog.e(TAG, "Could not contact the ContainerService"); 1544 } 1545 } else { 1546 broadcastPackageVerified(verificationId, originUri, 1547 PackageManager.VERIFICATION_REJECT, 1548 state.getInstallArgs().getUser()); 1549 } 1550 1551 Trace.asyncTraceEnd( 1552 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1553 1554 processPendingInstall(args, ret); 1555 mHandler.sendEmptyMessage(MCS_UNBIND); 1556 } 1557 break; 1558 } 1559 case PACKAGE_VERIFIED: { 1560 final int verificationId = msg.arg1; 1561 1562 final PackageVerificationState state = mPendingVerification.get(verificationId); 1563 if (state == null) { 1564 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1565 break; 1566 } 1567 1568 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1569 1570 state.setVerifierResponse(response.callerUid, response.code); 1571 1572 if (state.isVerificationComplete()) { 1573 mPendingVerification.remove(verificationId); 1574 1575 final InstallArgs args = state.getInstallArgs(); 1576 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1577 1578 int ret; 1579 if (state.isInstallAllowed()) { 1580 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1581 broadcastPackageVerified(verificationId, originUri, 1582 response.code, state.getInstallArgs().getUser()); 1583 try { 1584 ret = args.copyApk(mContainerService, true); 1585 } catch (RemoteException e) { 1586 Slog.e(TAG, "Could not contact the ContainerService"); 1587 } 1588 } else { 1589 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1590 } 1591 1592 Trace.asyncTraceEnd( 1593 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1594 1595 processPendingInstall(args, ret); 1596 mHandler.sendEmptyMessage(MCS_UNBIND); 1597 } 1598 1599 break; 1600 } 1601 case START_INTENT_FILTER_VERIFICATIONS: { 1602 IFVerificationParams params = (IFVerificationParams) msg.obj; 1603 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1604 params.replacing, params.pkg); 1605 break; 1606 } 1607 case INTENT_FILTER_VERIFIED: { 1608 final int verificationId = msg.arg1; 1609 1610 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1611 verificationId); 1612 if (state == null) { 1613 Slog.w(TAG, "Invalid IntentFilter verification token " 1614 + verificationId + " received"); 1615 break; 1616 } 1617 1618 final int userId = state.getUserId(); 1619 1620 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1621 "Processing IntentFilter verification with token:" 1622 + verificationId + " and userId:" + userId); 1623 1624 final IntentFilterVerificationResponse response = 1625 (IntentFilterVerificationResponse) msg.obj; 1626 1627 state.setVerifierResponse(response.callerUid, response.code); 1628 1629 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1630 "IntentFilter verification with token:" + verificationId 1631 + " and userId:" + userId 1632 + " is settings verifier response with response code:" 1633 + response.code); 1634 1635 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1636 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1637 + response.getFailedDomainsString()); 1638 } 1639 1640 if (state.isVerificationComplete()) { 1641 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1642 } else { 1643 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1644 "IntentFilter verification with token:" + verificationId 1645 + " was not said to be complete"); 1646 } 1647 1648 break; 1649 } 1650 } 1651 } 1652 } 1653 1654 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1655 boolean killApp, String[] grantedPermissions, 1656 IPackageInstallObserver2 installObserver) { 1657 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1658 // Send the removed broadcasts 1659 if (res.removedInfo != null) { 1660 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1661 } 1662 1663 // Now that we successfully installed the package, grant runtime 1664 // permissions if requested before broadcasting the install. 1665 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1666 >= Build.VERSION_CODES.M) { 1667 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1668 } 1669 1670 final boolean update = res.removedInfo != null 1671 && res.removedInfo.removedPackage != null; 1672 1673 // If this is the first time we have child packages for a disabled privileged 1674 // app that had no children, we grant requested runtime permissions to the new 1675 // children if the parent on the system image had them already granted. 1676 if (res.pkg.parentPackage != null) { 1677 synchronized (mPackages) { 1678 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1679 } 1680 } 1681 1682 synchronized (mPackages) { 1683 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1684 } 1685 1686 final String packageName = res.pkg.applicationInfo.packageName; 1687 Bundle extras = new Bundle(1); 1688 extras.putInt(Intent.EXTRA_UID, res.uid); 1689 1690 // Determine the set of users who are adding this package for 1691 // the first time vs. those who are seeing an update. 1692 int[] firstUsers = EMPTY_INT_ARRAY; 1693 int[] updateUsers = EMPTY_INT_ARRAY; 1694 if (res.origUsers == null || res.origUsers.length == 0) { 1695 firstUsers = res.newUsers; 1696 } else { 1697 for (int newUser : res.newUsers) { 1698 boolean isNew = true; 1699 for (int origUser : res.origUsers) { 1700 if (origUser == newUser) { 1701 isNew = false; 1702 break; 1703 } 1704 } 1705 if (isNew) { 1706 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1707 } else { 1708 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1709 } 1710 } 1711 } 1712 1713 // Send installed broadcasts if the install/update is not ephemeral 1714 if (!isEphemeral(res.pkg)) { 1715 // Send added for users that see the package for the first time 1716 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1717 extras, 0 /*flags*/, null /*targetPackage*/, 1718 null /*finishedReceiver*/, firstUsers); 1719 1720 // Send added for users that don't see the package for the first time 1721 if (update) { 1722 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1723 } 1724 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1725 extras, 0 /*flags*/, null /*targetPackage*/, 1726 null /*finishedReceiver*/, updateUsers); 1727 1728 // Send replaced for users that don't see the package for the first time 1729 if (update) { 1730 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1731 packageName, extras, 0 /*flags*/, 1732 null /*targetPackage*/, null /*finishedReceiver*/, 1733 updateUsers); 1734 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1735 null /*package*/, null /*extras*/, 0 /*flags*/, 1736 packageName /*targetPackage*/, 1737 null /*finishedReceiver*/, updateUsers); 1738 } 1739 1740 // Send broadcast package appeared if forward locked/external for all users 1741 // treat asec-hosted packages like removable media on upgrade 1742 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1743 if (DEBUG_INSTALL) { 1744 Slog.i(TAG, "upgrading pkg " + res.pkg 1745 + " is ASEC-hosted -> AVAILABLE"); 1746 } 1747 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1748 ArrayList<String> pkgList = new ArrayList<>(1); 1749 pkgList.add(packageName); 1750 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1751 } 1752 } 1753 1754 // Work that needs to happen on first install within each user 1755 if (firstUsers != null && firstUsers.length > 0) { 1756 synchronized (mPackages) { 1757 for (int userId : firstUsers) { 1758 // If this app is a browser and it's newly-installed for some 1759 // users, clear any default-browser state in those users. The 1760 // app's nature doesn't depend on the user, so we can just check 1761 // its browser nature in any user and generalize. 1762 if (packageIsBrowser(packageName, userId)) { 1763 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1764 } 1765 1766 // We may also need to apply pending (restored) runtime 1767 // permission grants within these users. 1768 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1769 } 1770 } 1771 } 1772 1773 // Log current value of "unknown sources" setting 1774 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1775 getUnknownSourcesSettings()); 1776 1777 // Force a gc to clear up things 1778 Runtime.getRuntime().gc(); 1779 1780 // Remove the replaced package's older resources safely now 1781 // We delete after a gc for applications on sdcard. 1782 if (res.removedInfo != null && res.removedInfo.args != null) { 1783 synchronized (mInstallLock) { 1784 res.removedInfo.args.doPostDeleteLI(true); 1785 } 1786 } 1787 } 1788 1789 // If someone is watching installs - notify them 1790 if (installObserver != null) { 1791 try { 1792 Bundle extras = extrasForInstallResult(res); 1793 installObserver.onPackageInstalled(res.name, res.returnCode, 1794 res.returnMsg, extras); 1795 } catch (RemoteException e) { 1796 Slog.i(TAG, "Observer no longer exists."); 1797 } 1798 } 1799 } 1800 1801 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1802 PackageParser.Package pkg) { 1803 if (pkg.parentPackage == null) { 1804 return; 1805 } 1806 if (pkg.requestedPermissions == null) { 1807 return; 1808 } 1809 final PackageSetting disabledSysParentPs = mSettings 1810 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1811 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1812 || !disabledSysParentPs.isPrivileged() 1813 || (disabledSysParentPs.childPackageNames != null 1814 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1815 return; 1816 } 1817 final int[] allUserIds = sUserManager.getUserIds(); 1818 final int permCount = pkg.requestedPermissions.size(); 1819 for (int i = 0; i < permCount; i++) { 1820 String permission = pkg.requestedPermissions.get(i); 1821 BasePermission bp = mSettings.mPermissions.get(permission); 1822 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1823 continue; 1824 } 1825 for (int userId : allUserIds) { 1826 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1827 permission, userId)) { 1828 grantRuntimePermission(pkg.packageName, permission, userId); 1829 } 1830 } 1831 } 1832 } 1833 1834 private StorageEventListener mStorageListener = new StorageEventListener() { 1835 @Override 1836 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1837 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1838 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1839 final String volumeUuid = vol.getFsUuid(); 1840 1841 // Clean up any users or apps that were removed or recreated 1842 // while this volume was missing 1843 reconcileUsers(volumeUuid); 1844 reconcileApps(volumeUuid); 1845 1846 // Clean up any install sessions that expired or were 1847 // cancelled while this volume was missing 1848 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1849 1850 loadPrivatePackages(vol); 1851 1852 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1853 unloadPrivatePackages(vol); 1854 } 1855 } 1856 1857 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1858 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1859 updateExternalMediaStatus(true, false); 1860 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1861 updateExternalMediaStatus(false, false); 1862 } 1863 } 1864 } 1865 1866 @Override 1867 public void onVolumeForgotten(String fsUuid) { 1868 if (TextUtils.isEmpty(fsUuid)) { 1869 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1870 return; 1871 } 1872 1873 // Remove any apps installed on the forgotten volume 1874 synchronized (mPackages) { 1875 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1876 for (PackageSetting ps : packages) { 1877 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1878 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1879 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1880 } 1881 1882 mSettings.onVolumeForgotten(fsUuid); 1883 mSettings.writeLPr(); 1884 } 1885 } 1886 }; 1887 1888 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1889 String[] grantedPermissions) { 1890 for (int userId : userIds) { 1891 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1892 } 1893 1894 // We could have touched GID membership, so flush out packages.list 1895 synchronized (mPackages) { 1896 mSettings.writePackageListLPr(); 1897 } 1898 } 1899 1900 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1901 String[] grantedPermissions) { 1902 SettingBase sb = (SettingBase) pkg.mExtras; 1903 if (sb == null) { 1904 return; 1905 } 1906 1907 PermissionsState permissionsState = sb.getPermissionsState(); 1908 1909 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1910 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1911 1912 synchronized (mPackages) { 1913 for (String permission : pkg.requestedPermissions) { 1914 BasePermission bp = mSettings.mPermissions.get(permission); 1915 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1916 && (grantedPermissions == null 1917 || ArrayUtils.contains(grantedPermissions, permission))) { 1918 final int flags = permissionsState.getPermissionFlags(permission, userId); 1919 // Installer cannot change immutable permissions. 1920 if ((flags & immutableFlags) == 0) { 1921 grantRuntimePermission(pkg.packageName, permission, userId); 1922 } 1923 } 1924 } 1925 } 1926 } 1927 1928 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1929 Bundle extras = null; 1930 switch (res.returnCode) { 1931 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1932 extras = new Bundle(); 1933 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1934 res.origPermission); 1935 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1936 res.origPackage); 1937 break; 1938 } 1939 case PackageManager.INSTALL_SUCCEEDED: { 1940 extras = new Bundle(); 1941 extras.putBoolean(Intent.EXTRA_REPLACING, 1942 res.removedInfo != null && res.removedInfo.removedPackage != null); 1943 break; 1944 } 1945 } 1946 return extras; 1947 } 1948 1949 void scheduleWriteSettingsLocked() { 1950 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1951 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1952 } 1953 } 1954 1955 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 1956 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 1957 scheduleWritePackageRestrictionsLocked(userId); 1958 } 1959 1960 void scheduleWritePackageRestrictionsLocked(int userId) { 1961 final int[] userIds = (userId == UserHandle.USER_ALL) 1962 ? sUserManager.getUserIds() : new int[]{userId}; 1963 for (int nextUserId : userIds) { 1964 if (!sUserManager.exists(nextUserId)) return; 1965 mDirtyUsers.add(nextUserId); 1966 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1967 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1968 } 1969 } 1970 } 1971 1972 public static PackageManagerService main(Context context, Installer installer, 1973 boolean factoryTest, boolean onlyCore) { 1974 // Self-check for initial settings. 1975 PackageManagerServiceCompilerMapping.checkProperties(); 1976 1977 PackageManagerService m = new PackageManagerService(context, installer, 1978 factoryTest, onlyCore); 1979 m.enableSystemUserPackages(); 1980 ServiceManager.addService("package", m); 1981 return m; 1982 } 1983 1984 private void enableSystemUserPackages() { 1985 if (!UserManager.isSplitSystemUser()) { 1986 return; 1987 } 1988 // For system user, enable apps based on the following conditions: 1989 // - app is whitelisted or belong to one of these groups: 1990 // -- system app which has no launcher icons 1991 // -- system app which has INTERACT_ACROSS_USERS permission 1992 // -- system IME app 1993 // - app is not in the blacklist 1994 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 1995 Set<String> enableApps = new ArraySet<>(); 1996 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 1997 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 1998 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 1999 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2000 enableApps.addAll(wlApps); 2001 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2002 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2003 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2004 enableApps.removeAll(blApps); 2005 Log.i(TAG, "Applications installed for system user: " + enableApps); 2006 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2007 UserHandle.SYSTEM); 2008 final int allAppsSize = allAps.size(); 2009 synchronized (mPackages) { 2010 for (int i = 0; i < allAppsSize; i++) { 2011 String pName = allAps.get(i); 2012 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2013 // Should not happen, but we shouldn't be failing if it does 2014 if (pkgSetting == null) { 2015 continue; 2016 } 2017 boolean install = enableApps.contains(pName); 2018 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2019 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2020 + " for system user"); 2021 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2022 } 2023 } 2024 } 2025 } 2026 2027 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2028 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2029 Context.DISPLAY_SERVICE); 2030 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2031 } 2032 2033 public PackageManagerService(Context context, Installer installer, 2034 boolean factoryTest, boolean onlyCore) { 2035 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2036 SystemClock.uptimeMillis()); 2037 2038 if (mSdkVersion <= 0) { 2039 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2040 } 2041 2042 mContext = context; 2043 mFactoryTest = factoryTest; 2044 mOnlyCore = onlyCore; 2045 mMetrics = new DisplayMetrics(); 2046 mSettings = new Settings(mPackages); 2047 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2048 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2049 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2050 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2051 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2052 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2053 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2054 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2055 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2056 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2057 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2058 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2059 2060 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2061 if (separateProcesses != null && separateProcesses.length() > 0) { 2062 if ("*".equals(separateProcesses)) { 2063 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2064 mSeparateProcesses = null; 2065 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2066 } else { 2067 mDefParseFlags = 0; 2068 mSeparateProcesses = separateProcesses.split(","); 2069 Slog.w(TAG, "Running with debug.separate_processes: " 2070 + separateProcesses); 2071 } 2072 } else { 2073 mDefParseFlags = 0; 2074 mSeparateProcesses = null; 2075 } 2076 2077 mInstaller = installer; 2078 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2079 "*dexopt*"); 2080 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2081 2082 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2083 FgThread.get().getLooper()); 2084 2085 getDefaultDisplayMetrics(context, mMetrics); 2086 2087 SystemConfig systemConfig = SystemConfig.getInstance(); 2088 mGlobalGids = systemConfig.getGlobalGids(); 2089 mSystemPermissions = systemConfig.getSystemPermissions(); 2090 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2091 2092 synchronized (mInstallLock) { 2093 // writer 2094 synchronized (mPackages) { 2095 mHandlerThread = new ServiceThread(TAG, 2096 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2097 mHandlerThread.start(); 2098 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2099 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2100 2101 File dataDir = Environment.getDataDirectory(); 2102 mAppInstallDir = new File(dataDir, "app"); 2103 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2104 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2105 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2106 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2107 2108 sUserManager = new UserManagerService(context, this, mPackages); 2109 2110 // Propagate permission configuration in to package manager. 2111 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2112 = systemConfig.getPermissions(); 2113 for (int i=0; i<permConfig.size(); i++) { 2114 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2115 BasePermission bp = mSettings.mPermissions.get(perm.name); 2116 if (bp == null) { 2117 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2118 mSettings.mPermissions.put(perm.name, bp); 2119 } 2120 if (perm.gids != null) { 2121 bp.setGids(perm.gids, perm.perUser); 2122 } 2123 } 2124 2125 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2126 for (int i=0; i<libConfig.size(); i++) { 2127 mSharedLibraries.put(libConfig.keyAt(i), 2128 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2129 } 2130 2131 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2132 2133 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2134 2135 String customResolverActivity = Resources.getSystem().getString( 2136 R.string.config_customResolverActivity); 2137 if (TextUtils.isEmpty(customResolverActivity)) { 2138 customResolverActivity = null; 2139 } else { 2140 mCustomResolverComponentName = ComponentName.unflattenFromString( 2141 customResolverActivity); 2142 } 2143 2144 long startTime = SystemClock.uptimeMillis(); 2145 2146 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2147 startTime); 2148 2149 // Set flag to monitor and not change apk file paths when 2150 // scanning install directories. 2151 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2152 2153 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2154 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2155 2156 if (bootClassPath == null) { 2157 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2158 } 2159 2160 if (systemServerClassPath == null) { 2161 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2162 } 2163 2164 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2165 final String[] dexCodeInstructionSets = 2166 getDexCodeInstructionSets( 2167 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2168 2169 /** 2170 * Ensure all external libraries have had dexopt run on them. 2171 */ 2172 if (mSharedLibraries.size() > 0) { 2173 // NOTE: For now, we're compiling these system "shared libraries" 2174 // (and framework jars) into all available architectures. It's possible 2175 // to compile them only when we come across an app that uses them (there's 2176 // already logic for that in scanPackageLI) but that adds some complexity. 2177 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2178 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2179 final String lib = libEntry.path; 2180 if (lib == null) { 2181 continue; 2182 } 2183 2184 try { 2185 // Shared libraries do not have profiles so we perform a full 2186 // AOT compilation (if needed). 2187 int dexoptNeeded = DexFile.getDexOptNeeded( 2188 lib, dexCodeInstructionSet, 2189 getCompilerFilterForReason(REASON_SHARED_APK), 2190 false /* newProfile */); 2191 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2192 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2193 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2194 getCompilerFilterForReason(REASON_SHARED_APK), 2195 StorageManager.UUID_PRIVATE_INTERNAL); 2196 } 2197 } catch (FileNotFoundException e) { 2198 Slog.w(TAG, "Library not found: " + lib); 2199 } catch (IOException | InstallerException e) { 2200 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2201 + e.getMessage()); 2202 } 2203 } 2204 } 2205 } 2206 2207 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2208 2209 final VersionInfo ver = mSettings.getInternalVersion(); 2210 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2211 2212 // when upgrading from pre-M, promote system app permissions from install to runtime 2213 mPromoteSystemApps = 2214 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2215 2216 // save off the names of pre-existing system packages prior to scanning; we don't 2217 // want to automatically grant runtime permissions for new system apps 2218 if (mPromoteSystemApps) { 2219 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2220 while (pkgSettingIter.hasNext()) { 2221 PackageSetting ps = pkgSettingIter.next(); 2222 if (isSystemApp(ps)) { 2223 mExistingSystemPackages.add(ps.name); 2224 } 2225 } 2226 } 2227 2228 // When upgrading from pre-N, we need to handle package extraction like first boot, 2229 // as there is no profiling data available. 2230 mIsPreNUpgrade = !mSettings.isNWorkDone(); 2231 mSettings.setNWorkDone(); 2232 2233 // Collect vendor overlay packages. 2234 // (Do this before scanning any apps.) 2235 // For security and version matching reason, only consider 2236 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2237 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2238 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2239 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2240 2241 // Find base frameworks (resource packages without code). 2242 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2243 | PackageParser.PARSE_IS_SYSTEM_DIR 2244 | PackageParser.PARSE_IS_PRIVILEGED, 2245 scanFlags | SCAN_NO_DEX, 0); 2246 2247 // Collected privileged system packages. 2248 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2249 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2250 | PackageParser.PARSE_IS_SYSTEM_DIR 2251 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2252 2253 // Collect ordinary system packages. 2254 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2255 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2256 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2257 2258 // Collect all vendor packages. 2259 File vendorAppDir = new File("/vendor/app"); 2260 try { 2261 vendorAppDir = vendorAppDir.getCanonicalFile(); 2262 } catch (IOException e) { 2263 // failed to look up canonical path, continue with original one 2264 } 2265 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2266 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2267 2268 // Collect all OEM packages. 2269 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2270 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2271 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2272 2273 // Prune any system packages that no longer exist. 2274 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2275 if (!mOnlyCore) { 2276 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2277 while (psit.hasNext()) { 2278 PackageSetting ps = psit.next(); 2279 2280 /* 2281 * If this is not a system app, it can't be a 2282 * disable system app. 2283 */ 2284 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2285 continue; 2286 } 2287 2288 /* 2289 * If the package is scanned, it's not erased. 2290 */ 2291 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2292 if (scannedPkg != null) { 2293 /* 2294 * If the system app is both scanned and in the 2295 * disabled packages list, then it must have been 2296 * added via OTA. Remove it from the currently 2297 * scanned package so the previously user-installed 2298 * application can be scanned. 2299 */ 2300 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2301 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2302 + ps.name + "; removing system app. Last known codePath=" 2303 + ps.codePathString + ", installStatus=" + ps.installStatus 2304 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2305 + scannedPkg.mVersionCode); 2306 removePackageLI(scannedPkg, true); 2307 mExpectingBetter.put(ps.name, ps.codePath); 2308 } 2309 2310 continue; 2311 } 2312 2313 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2314 psit.remove(); 2315 logCriticalInfo(Log.WARN, "System package " + ps.name 2316 + " no longer exists; wiping its data"); 2317 removeDataDirsLI(null, ps.name); 2318 } else { 2319 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2320 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2321 possiblyDeletedUpdatedSystemApps.add(ps.name); 2322 } 2323 } 2324 } 2325 } 2326 2327 //look for any incomplete package installations 2328 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2329 //clean up list 2330 for(int i = 0; i < deletePkgsList.size(); i++) { 2331 //clean up here 2332 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2333 } 2334 //delete tmp files 2335 deleteTempPackageFiles(); 2336 2337 // Remove any shared userIDs that have no associated packages 2338 mSettings.pruneSharedUsersLPw(); 2339 2340 if (!mOnlyCore) { 2341 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2342 SystemClock.uptimeMillis()); 2343 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2344 2345 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2346 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2347 2348 scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL, 2349 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2350 2351 /** 2352 * Remove disable package settings for any updated system 2353 * apps that were removed via an OTA. If they're not a 2354 * previously-updated app, remove them completely. 2355 * Otherwise, just revoke their system-level permissions. 2356 */ 2357 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2358 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2359 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2360 2361 String msg; 2362 if (deletedPkg == null) { 2363 msg = "Updated system package " + deletedAppName 2364 + " no longer exists; wiping its data"; 2365 removeDataDirsLI(null, deletedAppName); 2366 } else { 2367 msg = "Updated system app + " + deletedAppName 2368 + " no longer present; removing system privileges for " 2369 + deletedAppName; 2370 2371 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2372 2373 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2374 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2375 } 2376 logCriticalInfo(Log.WARN, msg); 2377 } 2378 2379 /** 2380 * Make sure all system apps that we expected to appear on 2381 * the userdata partition actually showed up. If they never 2382 * appeared, crawl back and revive the system version. 2383 */ 2384 for (int i = 0; i < mExpectingBetter.size(); i++) { 2385 final String packageName = mExpectingBetter.keyAt(i); 2386 if (!mPackages.containsKey(packageName)) { 2387 final File scanFile = mExpectingBetter.valueAt(i); 2388 2389 logCriticalInfo(Log.WARN, "Expected better " + packageName 2390 + " but never showed up; reverting to system"); 2391 2392 final int reparseFlags; 2393 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2394 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2395 | PackageParser.PARSE_IS_SYSTEM_DIR 2396 | PackageParser.PARSE_IS_PRIVILEGED; 2397 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2398 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2399 | PackageParser.PARSE_IS_SYSTEM_DIR; 2400 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2401 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2402 | PackageParser.PARSE_IS_SYSTEM_DIR; 2403 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2404 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2405 | PackageParser.PARSE_IS_SYSTEM_DIR; 2406 } else { 2407 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2408 continue; 2409 } 2410 2411 mSettings.enableSystemPackageLPw(packageName); 2412 2413 try { 2414 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2415 } catch (PackageManagerException e) { 2416 Slog.e(TAG, "Failed to parse original system package: " 2417 + e.getMessage()); 2418 } 2419 } 2420 } 2421 } 2422 mExpectingBetter.clear(); 2423 2424 // Now that we know all of the shared libraries, update all clients to have 2425 // the correct library paths. 2426 updateAllSharedLibrariesLPw(); 2427 2428 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2429 // NOTE: We ignore potential failures here during a system scan (like 2430 // the rest of the commands above) because there's precious little we 2431 // can do about it. A settings error is reported, though. 2432 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2433 false /* boot complete */); 2434 } 2435 2436 // Now that we know all the packages we are keeping, 2437 // read and update their last usage times. 2438 mPackageUsage.readLP(); 2439 2440 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2441 SystemClock.uptimeMillis()); 2442 Slog.i(TAG, "Time to scan packages: " 2443 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2444 + " seconds"); 2445 2446 // If the platform SDK has changed since the last time we booted, 2447 // we need to re-grant app permission to catch any new ones that 2448 // appear. This is really a hack, and means that apps can in some 2449 // cases get permissions that the user didn't initially explicitly 2450 // allow... it would be nice to have some better way to handle 2451 // this situation. 2452 int updateFlags = UPDATE_PERMISSIONS_ALL; 2453 if (ver.sdkVersion != mSdkVersion) { 2454 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2455 + mSdkVersion + "; regranting permissions for internal storage"); 2456 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2457 } 2458 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2459 ver.sdkVersion = mSdkVersion; 2460 2461 // If this is the first boot or an update from pre-M, and it is a normal 2462 // boot, then we need to initialize the default preferred apps across 2463 // all defined users. 2464 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2465 for (UserInfo user : sUserManager.getUsers(true)) { 2466 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2467 applyFactoryDefaultBrowserLPw(user.id); 2468 primeDomainVerificationsLPw(user.id); 2469 } 2470 } 2471 2472 // Prepare storage for system user really early during boot, 2473 // since core system apps like SettingsProvider and SystemUI 2474 // can't wait for user to start 2475 final int storageFlags; 2476 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2477 storageFlags = StorageManager.FLAG_STORAGE_DE; 2478 } else { 2479 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2480 } 2481 reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2482 storageFlags); 2483 2484 // If this is first boot after an OTA, and a normal boot, then 2485 // we need to clear code cache directories. 2486 if (mIsUpgrade && !onlyCore) { 2487 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2488 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2489 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2490 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2491 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2492 } 2493 } 2494 ver.fingerprint = Build.FINGERPRINT; 2495 } 2496 2497 checkDefaultBrowser(); 2498 2499 // clear only after permissions and other defaults have been updated 2500 mExistingSystemPackages.clear(); 2501 mPromoteSystemApps = false; 2502 2503 // All the changes are done during package scanning. 2504 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2505 2506 // can downgrade to reader 2507 mSettings.writeLPr(); 2508 2509 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2510 SystemClock.uptimeMillis()); 2511 2512 if (!mOnlyCore) { 2513 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2514 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2515 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2516 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2517 mIntentFilterVerifierComponent); 2518 } else { 2519 mRequiredVerifierPackage = null; 2520 mRequiredInstallerPackage = null; 2521 mIntentFilterVerifierComponent = null; 2522 mIntentFilterVerifier = null; 2523 } 2524 2525 mInstallerService = new PackageInstallerService(context, this); 2526 2527 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2528 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2529 // both the installer and resolver must be present to enable ephemeral 2530 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2531 if (DEBUG_EPHEMERAL) { 2532 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2533 + " installer:" + ephemeralInstallerComponent); 2534 } 2535 mEphemeralResolverComponent = ephemeralResolverComponent; 2536 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2537 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2538 mEphemeralResolverConnection = 2539 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2540 } else { 2541 if (DEBUG_EPHEMERAL) { 2542 final String missingComponent = 2543 (ephemeralResolverComponent == null) 2544 ? (ephemeralInstallerComponent == null) 2545 ? "resolver and installer" 2546 : "resolver" 2547 : "installer"; 2548 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2549 } 2550 mEphemeralResolverComponent = null; 2551 mEphemeralInstallerComponent = null; 2552 mEphemeralResolverConnection = null; 2553 } 2554 2555 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2556 } // synchronized (mPackages) 2557 } // synchronized (mInstallLock) 2558 2559 // Now after opening every single application zip, make sure they 2560 // are all flushed. Not really needed, but keeps things nice and 2561 // tidy. 2562 Runtime.getRuntime().gc(); 2563 2564 // The initial scanning above does many calls into installd while 2565 // holding the mPackages lock, but we're mostly interested in yelling 2566 // once we have a booted system. 2567 mInstaller.setWarnIfHeld(mPackages); 2568 2569 // Expose private service for system components to use. 2570 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2571 } 2572 2573 @Override 2574 public boolean isFirstBoot() { 2575 return !mRestoredSettings; 2576 } 2577 2578 @Override 2579 public boolean isOnlyCoreApps() { 2580 return mOnlyCore; 2581 } 2582 2583 @Override 2584 public boolean isUpgrade() { 2585 return mIsUpgrade; 2586 } 2587 2588 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2589 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2590 2591 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2592 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2593 UserHandle.USER_SYSTEM); 2594 if (matches.size() == 1) { 2595 return matches.get(0).getComponentInfo().packageName; 2596 } else { 2597 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2598 return null; 2599 } 2600 } 2601 2602 private @NonNull String getRequiredInstallerLPr() { 2603 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2604 intent.addCategory(Intent.CATEGORY_DEFAULT); 2605 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2606 2607 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2608 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2609 UserHandle.USER_SYSTEM); 2610 if (matches.size() == 1) { 2611 return matches.get(0).getComponentInfo().packageName; 2612 } else { 2613 throw new RuntimeException("There must be exactly one installer; found " + matches); 2614 } 2615 } 2616 2617 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2618 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2619 2620 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2621 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2622 UserHandle.USER_SYSTEM); 2623 ResolveInfo best = null; 2624 final int N = matches.size(); 2625 for (int i = 0; i < N; i++) { 2626 final ResolveInfo cur = matches.get(i); 2627 final String packageName = cur.getComponentInfo().packageName; 2628 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2629 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2630 continue; 2631 } 2632 2633 if (best == null || cur.priority > best.priority) { 2634 best = cur; 2635 } 2636 } 2637 2638 if (best != null) { 2639 return best.getComponentInfo().getComponentName(); 2640 } else { 2641 throw new RuntimeException("There must be at least one intent filter verifier"); 2642 } 2643 } 2644 2645 private @Nullable ComponentName getEphemeralResolverLPr() { 2646 final String[] packageArray = 2647 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2648 if (packageArray.length == 0) { 2649 if (DEBUG_EPHEMERAL) { 2650 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2651 } 2652 return null; 2653 } 2654 2655 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2656 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2657 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2658 UserHandle.USER_SYSTEM); 2659 2660 final int N = resolvers.size(); 2661 if (N == 0) { 2662 if (DEBUG_EPHEMERAL) { 2663 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2664 } 2665 return null; 2666 } 2667 2668 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2669 for (int i = 0; i < N; i++) { 2670 final ResolveInfo info = resolvers.get(i); 2671 2672 if (info.serviceInfo == null) { 2673 continue; 2674 } 2675 2676 final String packageName = info.serviceInfo.packageName; 2677 if (!possiblePackages.contains(packageName)) { 2678 if (DEBUG_EPHEMERAL) { 2679 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2680 + " pkg: " + packageName + ", info:" + info); 2681 } 2682 continue; 2683 } 2684 2685 if (DEBUG_EPHEMERAL) { 2686 Slog.v(TAG, "Ephemeral resolver found;" 2687 + " pkg: " + packageName + ", info:" + info); 2688 } 2689 return new ComponentName(packageName, info.serviceInfo.name); 2690 } 2691 if (DEBUG_EPHEMERAL) { 2692 Slog.v(TAG, "Ephemeral resolver NOT found"); 2693 } 2694 return null; 2695 } 2696 2697 private @Nullable ComponentName getEphemeralInstallerLPr() { 2698 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2699 intent.addCategory(Intent.CATEGORY_DEFAULT); 2700 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2701 2702 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2703 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2704 UserHandle.USER_SYSTEM); 2705 if (matches.size() == 0) { 2706 return null; 2707 } else if (matches.size() == 1) { 2708 return matches.get(0).getComponentInfo().getComponentName(); 2709 } else { 2710 throw new RuntimeException( 2711 "There must be at most one ephemeral installer; found " + matches); 2712 } 2713 } 2714 2715 private void primeDomainVerificationsLPw(int userId) { 2716 if (DEBUG_DOMAIN_VERIFICATION) { 2717 Slog.d(TAG, "Priming domain verifications in user " + userId); 2718 } 2719 2720 SystemConfig systemConfig = SystemConfig.getInstance(); 2721 ArraySet<String> packages = systemConfig.getLinkedApps(); 2722 ArraySet<String> domains = new ArraySet<String>(); 2723 2724 for (String packageName : packages) { 2725 PackageParser.Package pkg = mPackages.get(packageName); 2726 if (pkg != null) { 2727 if (!pkg.isSystemApp()) { 2728 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2729 continue; 2730 } 2731 2732 domains.clear(); 2733 for (PackageParser.Activity a : pkg.activities) { 2734 for (ActivityIntentInfo filter : a.intents) { 2735 if (hasValidDomains(filter)) { 2736 domains.addAll(filter.getHostsList()); 2737 } 2738 } 2739 } 2740 2741 if (domains.size() > 0) { 2742 if (DEBUG_DOMAIN_VERIFICATION) { 2743 Slog.v(TAG, " + " + packageName); 2744 } 2745 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2746 // state w.r.t. the formal app-linkage "no verification attempted" state; 2747 // and then 'always' in the per-user state actually used for intent resolution. 2748 final IntentFilterVerificationInfo ivi; 2749 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2750 new ArrayList<String>(domains)); 2751 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2752 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2753 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2754 } else { 2755 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2756 + "' does not handle web links"); 2757 } 2758 } else { 2759 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2760 } 2761 } 2762 2763 scheduleWritePackageRestrictionsLocked(userId); 2764 scheduleWriteSettingsLocked(); 2765 } 2766 2767 private void applyFactoryDefaultBrowserLPw(int userId) { 2768 // The default browser app's package name is stored in a string resource, 2769 // with a product-specific overlay used for vendor customization. 2770 String browserPkg = mContext.getResources().getString( 2771 com.android.internal.R.string.default_browser); 2772 if (!TextUtils.isEmpty(browserPkg)) { 2773 // non-empty string => required to be a known package 2774 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2775 if (ps == null) { 2776 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2777 browserPkg = null; 2778 } else { 2779 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2780 } 2781 } 2782 2783 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2784 // default. If there's more than one, just leave everything alone. 2785 if (browserPkg == null) { 2786 calculateDefaultBrowserLPw(userId); 2787 } 2788 } 2789 2790 private void calculateDefaultBrowserLPw(int userId) { 2791 List<String> allBrowsers = resolveAllBrowserApps(userId); 2792 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2793 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2794 } 2795 2796 private List<String> resolveAllBrowserApps(int userId) { 2797 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2798 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2799 PackageManager.MATCH_ALL, userId); 2800 2801 final int count = list.size(); 2802 List<String> result = new ArrayList<String>(count); 2803 for (int i=0; i<count; i++) { 2804 ResolveInfo info = list.get(i); 2805 if (info.activityInfo == null 2806 || !info.handleAllWebDataURI 2807 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2808 || result.contains(info.activityInfo.packageName)) { 2809 continue; 2810 } 2811 result.add(info.activityInfo.packageName); 2812 } 2813 2814 return result; 2815 } 2816 2817 private boolean packageIsBrowser(String packageName, int userId) { 2818 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2819 PackageManager.MATCH_ALL, userId); 2820 final int N = list.size(); 2821 for (int i = 0; i < N; i++) { 2822 ResolveInfo info = list.get(i); 2823 if (packageName.equals(info.activityInfo.packageName)) { 2824 return true; 2825 } 2826 } 2827 return false; 2828 } 2829 2830 private void checkDefaultBrowser() { 2831 final int myUserId = UserHandle.myUserId(); 2832 final String packageName = getDefaultBrowserPackageName(myUserId); 2833 if (packageName != null) { 2834 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2835 if (info == null) { 2836 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2837 synchronized (mPackages) { 2838 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2839 } 2840 } 2841 } 2842 } 2843 2844 @Override 2845 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2846 throws RemoteException { 2847 try { 2848 return super.onTransact(code, data, reply, flags); 2849 } catch (RuntimeException e) { 2850 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2851 Slog.wtf(TAG, "Package Manager Crash", e); 2852 } 2853 throw e; 2854 } 2855 } 2856 2857 void cleanupInstallFailedPackage(PackageSetting ps) { 2858 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2859 2860 removeDataDirsLI(ps.volumeUuid, ps.name); 2861 if (ps.codePath != null) { 2862 removeCodePathLI(ps.codePath); 2863 } 2864 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2865 if (ps.resourcePath.isDirectory()) { 2866 FileUtils.deleteContents(ps.resourcePath); 2867 } 2868 ps.resourcePath.delete(); 2869 } 2870 mSettings.removePackageLPw(ps.name); 2871 } 2872 2873 static int[] appendInts(int[] cur, int[] add) { 2874 if (add == null) return cur; 2875 if (cur == null) return add; 2876 final int N = add.length; 2877 for (int i=0; i<N; i++) { 2878 cur = appendInt(cur, add[i]); 2879 } 2880 return cur; 2881 } 2882 2883 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2884 if (!sUserManager.exists(userId)) return null; 2885 final PackageSetting ps = (PackageSetting) p.mExtras; 2886 if (ps == null) { 2887 return null; 2888 } 2889 2890 final PermissionsState permissionsState = ps.getPermissionsState(); 2891 2892 final int[] gids = permissionsState.computeGids(userId); 2893 final Set<String> permissions = permissionsState.getPermissions(userId); 2894 final PackageUserState state = ps.readUserState(userId); 2895 2896 return PackageParser.generatePackageInfo(p, gids, flags, 2897 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2898 } 2899 2900 @Override 2901 public void checkPackageStartable(String packageName, int userId) { 2902 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 2903 2904 synchronized (mPackages) { 2905 final PackageSetting ps = mSettings.mPackages.get(packageName); 2906 if (ps == null) { 2907 throw new SecurityException("Package " + packageName + " was not found!"); 2908 } 2909 2910 if (!ps.getInstalled(userId)) { 2911 throw new SecurityException( 2912 "Package " + packageName + " was not installed for user " + userId + "!"); 2913 } 2914 2915 if (mSafeMode && !ps.isSystem()) { 2916 throw new SecurityException("Package " + packageName + " not a system app!"); 2917 } 2918 2919 if (ps.frozen) { 2920 throw new SecurityException("Package " + packageName + " is currently frozen!"); 2921 } 2922 2923 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 2924 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 2925 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 2926 } 2927 } 2928 } 2929 2930 @Override 2931 public boolean isPackageAvailable(String packageName, int userId) { 2932 if (!sUserManager.exists(userId)) return false; 2933 enforceCrossUserPermission(Binder.getCallingUid(), userId, 2934 false /* requireFullPermission */, false /* checkShell */, "is package available"); 2935 synchronized (mPackages) { 2936 PackageParser.Package p = mPackages.get(packageName); 2937 if (p != null) { 2938 final PackageSetting ps = (PackageSetting) p.mExtras; 2939 if (ps != null) { 2940 final PackageUserState state = ps.readUserState(userId); 2941 if (state != null) { 2942 return PackageParser.isAvailable(state); 2943 } 2944 } 2945 } 2946 } 2947 return false; 2948 } 2949 2950 @Override 2951 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2952 if (!sUserManager.exists(userId)) return null; 2953 flags = updateFlagsForPackage(flags, userId, packageName); 2954 enforceCrossUserPermission(Binder.getCallingUid(), userId, 2955 false /* requireFullPermission */, false /* checkShell */, "get package info"); 2956 // reader 2957 synchronized (mPackages) { 2958 PackageParser.Package p = mPackages.get(packageName); 2959 if (DEBUG_PACKAGE_INFO) 2960 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2961 if (p != null) { 2962 return generatePackageInfo(p, flags, userId); 2963 } 2964 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2965 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2966 } 2967 } 2968 return null; 2969 } 2970 2971 @Override 2972 public String[] currentToCanonicalPackageNames(String[] names) { 2973 String[] out = new String[names.length]; 2974 // reader 2975 synchronized (mPackages) { 2976 for (int i=names.length-1; i>=0; i--) { 2977 PackageSetting ps = mSettings.mPackages.get(names[i]); 2978 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2979 } 2980 } 2981 return out; 2982 } 2983 2984 @Override 2985 public String[] canonicalToCurrentPackageNames(String[] names) { 2986 String[] out = new String[names.length]; 2987 // reader 2988 synchronized (mPackages) { 2989 for (int i=names.length-1; i>=0; i--) { 2990 String cur = mSettings.mRenamedPackages.get(names[i]); 2991 out[i] = cur != null ? cur : names[i]; 2992 } 2993 } 2994 return out; 2995 } 2996 2997 @Override 2998 public int getPackageUid(String packageName, int flags, int userId) { 2999 if (!sUserManager.exists(userId)) return -1; 3000 flags = updateFlagsForPackage(flags, userId, packageName); 3001 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3002 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3003 3004 // reader 3005 synchronized (mPackages) { 3006 final PackageParser.Package p = mPackages.get(packageName); 3007 if (p != null && p.isMatch(flags)) { 3008 return UserHandle.getUid(userId, p.applicationInfo.uid); 3009 } 3010 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3011 final PackageSetting ps = mSettings.mPackages.get(packageName); 3012 if (ps != null && ps.isMatch(flags)) { 3013 return UserHandle.getUid(userId, ps.appId); 3014 } 3015 } 3016 } 3017 3018 return -1; 3019 } 3020 3021 @Override 3022 public int[] getPackageGids(String packageName, int flags, int userId) { 3023 if (!sUserManager.exists(userId)) return null; 3024 flags = updateFlagsForPackage(flags, userId, packageName); 3025 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3026 false /* requireFullPermission */, false /* checkShell */, 3027 "getPackageGids"); 3028 3029 // reader 3030 synchronized (mPackages) { 3031 final PackageParser.Package p = mPackages.get(packageName); 3032 if (p != null && p.isMatch(flags)) { 3033 PackageSetting ps = (PackageSetting) p.mExtras; 3034 return ps.getPermissionsState().computeGids(userId); 3035 } 3036 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3037 final PackageSetting ps = mSettings.mPackages.get(packageName); 3038 if (ps != null && ps.isMatch(flags)) { 3039 return ps.getPermissionsState().computeGids(userId); 3040 } 3041 } 3042 } 3043 3044 return null; 3045 } 3046 3047 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3048 if (bp.perm != null) { 3049 return PackageParser.generatePermissionInfo(bp.perm, flags); 3050 } 3051 PermissionInfo pi = new PermissionInfo(); 3052 pi.name = bp.name; 3053 pi.packageName = bp.sourcePackage; 3054 pi.nonLocalizedLabel = bp.name; 3055 pi.protectionLevel = bp.protectionLevel; 3056 return pi; 3057 } 3058 3059 @Override 3060 public PermissionInfo getPermissionInfo(String name, int flags) { 3061 // reader 3062 synchronized (mPackages) { 3063 final BasePermission p = mSettings.mPermissions.get(name); 3064 if (p != null) { 3065 return generatePermissionInfo(p, flags); 3066 } 3067 return null; 3068 } 3069 } 3070 3071 @Override 3072 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3073 int flags) { 3074 // reader 3075 synchronized (mPackages) { 3076 if (group != null && !mPermissionGroups.containsKey(group)) { 3077 // This is thrown as NameNotFoundException 3078 return null; 3079 } 3080 3081 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3082 for (BasePermission p : mSettings.mPermissions.values()) { 3083 if (group == null) { 3084 if (p.perm == null || p.perm.info.group == null) { 3085 out.add(generatePermissionInfo(p, flags)); 3086 } 3087 } else { 3088 if (p.perm != null && group.equals(p.perm.info.group)) { 3089 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3090 } 3091 } 3092 } 3093 return new ParceledListSlice<>(out); 3094 } 3095 } 3096 3097 @Override 3098 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3099 // reader 3100 synchronized (mPackages) { 3101 return PackageParser.generatePermissionGroupInfo( 3102 mPermissionGroups.get(name), flags); 3103 } 3104 } 3105 3106 @Override 3107 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3108 // reader 3109 synchronized (mPackages) { 3110 final int N = mPermissionGroups.size(); 3111 ArrayList<PermissionGroupInfo> out 3112 = new ArrayList<PermissionGroupInfo>(N); 3113 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3114 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3115 } 3116 return new ParceledListSlice<>(out); 3117 } 3118 } 3119 3120 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3121 int userId) { 3122 if (!sUserManager.exists(userId)) return null; 3123 PackageSetting ps = mSettings.mPackages.get(packageName); 3124 if (ps != null) { 3125 if (ps.pkg == null) { 3126 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 3127 flags, userId); 3128 if (pInfo != null) { 3129 return pInfo.applicationInfo; 3130 } 3131 return null; 3132 } 3133 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3134 ps.readUserState(userId), userId); 3135 } 3136 return null; 3137 } 3138 3139 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 3140 int userId) { 3141 if (!sUserManager.exists(userId)) return null; 3142 PackageSetting ps = mSettings.mPackages.get(packageName); 3143 if (ps != null) { 3144 PackageParser.Package pkg = ps.pkg; 3145 if (pkg == null) { 3146 if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) { 3147 return null; 3148 } 3149 // Only data remains, so we aren't worried about code paths 3150 pkg = new PackageParser.Package(packageName); 3151 pkg.applicationInfo.packageName = packageName; 3152 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 3153 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 3154 pkg.applicationInfo.uid = ps.appId; 3155 pkg.applicationInfo.initForUser(userId); 3156 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 3157 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 3158 } 3159 return generatePackageInfo(pkg, flags, userId); 3160 } 3161 return null; 3162 } 3163 3164 @Override 3165 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3166 if (!sUserManager.exists(userId)) return null; 3167 flags = updateFlagsForApplication(flags, userId, packageName); 3168 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3169 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3170 // writer 3171 synchronized (mPackages) { 3172 PackageParser.Package p = mPackages.get(packageName); 3173 if (DEBUG_PACKAGE_INFO) Log.v( 3174 TAG, "getApplicationInfo " + packageName 3175 + ": " + p); 3176 if (p != null) { 3177 PackageSetting ps = mSettings.mPackages.get(packageName); 3178 if (ps == null) return null; 3179 // Note: isEnabledLP() does not apply here - always return info 3180 return PackageParser.generateApplicationInfo( 3181 p, flags, ps.readUserState(userId), userId); 3182 } 3183 if ("android".equals(packageName)||"system".equals(packageName)) { 3184 return mAndroidApplication; 3185 } 3186 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3187 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3188 } 3189 } 3190 return null; 3191 } 3192 3193 @Override 3194 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3195 final IPackageDataObserver observer) { 3196 mContext.enforceCallingOrSelfPermission( 3197 android.Manifest.permission.CLEAR_APP_CACHE, null); 3198 // Queue up an async operation since clearing cache may take a little while. 3199 mHandler.post(new Runnable() { 3200 public void run() { 3201 mHandler.removeCallbacks(this); 3202 boolean success = true; 3203 synchronized (mInstallLock) { 3204 try { 3205 mInstaller.freeCache(volumeUuid, freeStorageSize); 3206 } catch (InstallerException e) { 3207 Slog.w(TAG, "Couldn't clear application caches: " + e); 3208 success = false; 3209 } 3210 } 3211 if (observer != null) { 3212 try { 3213 observer.onRemoveCompleted(null, success); 3214 } catch (RemoteException e) { 3215 Slog.w(TAG, "RemoveException when invoking call back"); 3216 } 3217 } 3218 } 3219 }); 3220 } 3221 3222 @Override 3223 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3224 final IntentSender pi) { 3225 mContext.enforceCallingOrSelfPermission( 3226 android.Manifest.permission.CLEAR_APP_CACHE, null); 3227 // Queue up an async operation since clearing cache may take a little while. 3228 mHandler.post(new Runnable() { 3229 public void run() { 3230 mHandler.removeCallbacks(this); 3231 boolean success = true; 3232 synchronized (mInstallLock) { 3233 try { 3234 mInstaller.freeCache(volumeUuid, freeStorageSize); 3235 } catch (InstallerException e) { 3236 Slog.w(TAG, "Couldn't clear application caches: " + e); 3237 success = false; 3238 } 3239 } 3240 if(pi != null) { 3241 try { 3242 // Callback via pending intent 3243 int code = success ? 1 : 0; 3244 pi.sendIntent(null, code, null, 3245 null, null); 3246 } catch (SendIntentException e1) { 3247 Slog.i(TAG, "Failed to send pending intent"); 3248 } 3249 } 3250 } 3251 }); 3252 } 3253 3254 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3255 synchronized (mInstallLock) { 3256 try { 3257 mInstaller.freeCache(volumeUuid, freeStorageSize); 3258 } catch (InstallerException e) { 3259 throw new IOException("Failed to free enough space", e); 3260 } 3261 } 3262 } 3263 3264 /** 3265 * Return if the user key is currently unlocked. 3266 */ 3267 private boolean isUserKeyUnlocked(int userId) { 3268 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 3269 final IMountService mount = IMountService.Stub 3270 .asInterface(ServiceManager.getService("mount")); 3271 if (mount == null) { 3272 Slog.w(TAG, "Early during boot, assuming locked"); 3273 return false; 3274 } 3275 final long token = Binder.clearCallingIdentity(); 3276 try { 3277 return mount.isUserKeyUnlocked(userId); 3278 } catch (RemoteException e) { 3279 throw e.rethrowAsRuntimeException(); 3280 } finally { 3281 Binder.restoreCallingIdentity(token); 3282 } 3283 } else { 3284 return true; 3285 } 3286 } 3287 3288 /** 3289 * Update given flags based on encryption status of current user. 3290 */ 3291 private int updateFlags(int flags, int userId) { 3292 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3293 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3294 // Caller expressed an explicit opinion about what encryption 3295 // aware/unaware components they want to see, so fall through and 3296 // give them what they want 3297 } else { 3298 // Caller expressed no opinion, so match based on user state 3299 if (isUserKeyUnlocked(userId)) { 3300 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3301 } else { 3302 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3303 } 3304 } 3305 return flags; 3306 } 3307 3308 /** 3309 * Update given flags when being used to request {@link PackageInfo}. 3310 */ 3311 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3312 boolean triaged = true; 3313 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3314 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3315 // Caller is asking for component details, so they'd better be 3316 // asking for specific encryption matching behavior, or be triaged 3317 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3318 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3319 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3320 triaged = false; 3321 } 3322 } 3323 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3324 | PackageManager.MATCH_SYSTEM_ONLY 3325 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3326 triaged = false; 3327 } 3328 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3329 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3330 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3331 } 3332 return updateFlags(flags, userId); 3333 } 3334 3335 /** 3336 * Update given flags when being used to request {@link ApplicationInfo}. 3337 */ 3338 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3339 return updateFlagsForPackage(flags, userId, cookie); 3340 } 3341 3342 /** 3343 * Update given flags when being used to request {@link ComponentInfo}. 3344 */ 3345 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3346 if (cookie instanceof Intent) { 3347 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3348 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3349 } 3350 } 3351 3352 boolean triaged = true; 3353 // Caller is asking for component details, so they'd better be 3354 // asking for specific encryption matching behavior, or be triaged 3355 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3356 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3357 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3358 triaged = false; 3359 } 3360 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3361 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3362 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3363 } 3364 3365 return updateFlags(flags, userId); 3366 } 3367 3368 /** 3369 * Update given flags when being used to request {@link ResolveInfo}. 3370 */ 3371 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3372 // Safe mode means we shouldn't match any third-party components 3373 if (mSafeMode) { 3374 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3375 } 3376 3377 return updateFlagsForComponent(flags, userId, cookie); 3378 } 3379 3380 @Override 3381 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3382 if (!sUserManager.exists(userId)) return null; 3383 flags = updateFlagsForComponent(flags, userId, component); 3384 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3385 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3386 synchronized (mPackages) { 3387 PackageParser.Activity a = mActivities.mActivities.get(component); 3388 3389 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3390 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3391 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3392 if (ps == null) return null; 3393 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3394 userId); 3395 } 3396 if (mResolveComponentName.equals(component)) { 3397 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3398 new PackageUserState(), userId); 3399 } 3400 } 3401 return null; 3402 } 3403 3404 @Override 3405 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3406 String resolvedType) { 3407 synchronized (mPackages) { 3408 if (component.equals(mResolveComponentName)) { 3409 // The resolver supports EVERYTHING! 3410 return true; 3411 } 3412 PackageParser.Activity a = mActivities.mActivities.get(component); 3413 if (a == null) { 3414 return false; 3415 } 3416 for (int i=0; i<a.intents.size(); i++) { 3417 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3418 intent.getData(), intent.getCategories(), TAG) >= 0) { 3419 return true; 3420 } 3421 } 3422 return false; 3423 } 3424 } 3425 3426 @Override 3427 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3428 if (!sUserManager.exists(userId)) return null; 3429 flags = updateFlagsForComponent(flags, userId, component); 3430 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3431 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3432 synchronized (mPackages) { 3433 PackageParser.Activity a = mReceivers.mActivities.get(component); 3434 if (DEBUG_PACKAGE_INFO) Log.v( 3435 TAG, "getReceiverInfo " + component + ": " + a); 3436 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3437 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3438 if (ps == null) return null; 3439 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3440 userId); 3441 } 3442 } 3443 return null; 3444 } 3445 3446 @Override 3447 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3448 if (!sUserManager.exists(userId)) return null; 3449 flags = updateFlagsForComponent(flags, userId, component); 3450 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3451 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3452 synchronized (mPackages) { 3453 PackageParser.Service s = mServices.mServices.get(component); 3454 if (DEBUG_PACKAGE_INFO) Log.v( 3455 TAG, "getServiceInfo " + component + ": " + s); 3456 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3457 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3458 if (ps == null) return null; 3459 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3460 userId); 3461 } 3462 } 3463 return null; 3464 } 3465 3466 @Override 3467 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3468 if (!sUserManager.exists(userId)) return null; 3469 flags = updateFlagsForComponent(flags, userId, component); 3470 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3471 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3472 synchronized (mPackages) { 3473 PackageParser.Provider p = mProviders.mProviders.get(component); 3474 if (DEBUG_PACKAGE_INFO) Log.v( 3475 TAG, "getProviderInfo " + component + ": " + p); 3476 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3477 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3478 if (ps == null) return null; 3479 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3480 userId); 3481 } 3482 } 3483 return null; 3484 } 3485 3486 @Override 3487 public String[] getSystemSharedLibraryNames() { 3488 Set<String> libSet; 3489 synchronized (mPackages) { 3490 libSet = mSharedLibraries.keySet(); 3491 int size = libSet.size(); 3492 if (size > 0) { 3493 String[] libs = new String[size]; 3494 libSet.toArray(libs); 3495 return libs; 3496 } 3497 } 3498 return null; 3499 } 3500 3501 @Override 3502 public @Nullable String getServicesSystemSharedLibraryPackageName() { 3503 synchronized (mPackages) { 3504 SharedLibraryEntry libraryEntry = mSharedLibraries.get( 3505 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 3506 if (libraryEntry != null) { 3507 return libraryEntry.apk; 3508 } 3509 } 3510 return null; 3511 } 3512 3513 @Override 3514 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3515 synchronized (mPackages) { 3516 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3517 3518 final FeatureInfo fi = new FeatureInfo(); 3519 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3520 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3521 res.add(fi); 3522 3523 return new ParceledListSlice<>(res); 3524 } 3525 } 3526 3527 @Override 3528 public boolean hasSystemFeature(String name, int version) { 3529 synchronized (mPackages) { 3530 final FeatureInfo feat = mAvailableFeatures.get(name); 3531 if (feat == null) { 3532 return false; 3533 } else { 3534 return feat.version >= version; 3535 } 3536 } 3537 } 3538 3539 @Override 3540 public int checkPermission(String permName, String pkgName, int userId) { 3541 if (!sUserManager.exists(userId)) { 3542 return PackageManager.PERMISSION_DENIED; 3543 } 3544 3545 synchronized (mPackages) { 3546 final PackageParser.Package p = mPackages.get(pkgName); 3547 if (p != null && p.mExtras != null) { 3548 final PackageSetting ps = (PackageSetting) p.mExtras; 3549 final PermissionsState permissionsState = ps.getPermissionsState(); 3550 if (permissionsState.hasPermission(permName, userId)) { 3551 return PackageManager.PERMISSION_GRANTED; 3552 } 3553 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3554 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3555 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3556 return PackageManager.PERMISSION_GRANTED; 3557 } 3558 } 3559 } 3560 3561 return PackageManager.PERMISSION_DENIED; 3562 } 3563 3564 @Override 3565 public int checkUidPermission(String permName, int uid) { 3566 final int userId = UserHandle.getUserId(uid); 3567 3568 if (!sUserManager.exists(userId)) { 3569 return PackageManager.PERMISSION_DENIED; 3570 } 3571 3572 synchronized (mPackages) { 3573 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3574 if (obj != null) { 3575 final SettingBase ps = (SettingBase) obj; 3576 final PermissionsState permissionsState = ps.getPermissionsState(); 3577 if (permissionsState.hasPermission(permName, userId)) { 3578 return PackageManager.PERMISSION_GRANTED; 3579 } 3580 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3581 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3582 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3583 return PackageManager.PERMISSION_GRANTED; 3584 } 3585 } else { 3586 ArraySet<String> perms = mSystemPermissions.get(uid); 3587 if (perms != null) { 3588 if (perms.contains(permName)) { 3589 return PackageManager.PERMISSION_GRANTED; 3590 } 3591 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3592 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3593 return PackageManager.PERMISSION_GRANTED; 3594 } 3595 } 3596 } 3597 } 3598 3599 return PackageManager.PERMISSION_DENIED; 3600 } 3601 3602 @Override 3603 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3604 if (UserHandle.getCallingUserId() != userId) { 3605 mContext.enforceCallingPermission( 3606 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3607 "isPermissionRevokedByPolicy for user " + userId); 3608 } 3609 3610 if (checkPermission(permission, packageName, userId) 3611 == PackageManager.PERMISSION_GRANTED) { 3612 return false; 3613 } 3614 3615 final long identity = Binder.clearCallingIdentity(); 3616 try { 3617 final int flags = getPermissionFlags(permission, packageName, userId); 3618 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3619 } finally { 3620 Binder.restoreCallingIdentity(identity); 3621 } 3622 } 3623 3624 @Override 3625 public String getPermissionControllerPackageName() { 3626 synchronized (mPackages) { 3627 return mRequiredInstallerPackage; 3628 } 3629 } 3630 3631 /** 3632 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3633 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3634 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3635 * @param message the message to log on security exception 3636 */ 3637 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3638 boolean checkShell, String message) { 3639 if (userId < 0) { 3640 throw new IllegalArgumentException("Invalid userId " + userId); 3641 } 3642 if (checkShell) { 3643 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3644 } 3645 if (userId == UserHandle.getUserId(callingUid)) return; 3646 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3647 if (requireFullPermission) { 3648 mContext.enforceCallingOrSelfPermission( 3649 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3650 } else { 3651 try { 3652 mContext.enforceCallingOrSelfPermission( 3653 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3654 } catch (SecurityException se) { 3655 mContext.enforceCallingOrSelfPermission( 3656 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3657 } 3658 } 3659 } 3660 } 3661 3662 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3663 if (callingUid == Process.SHELL_UID) { 3664 if (userHandle >= 0 3665 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3666 throw new SecurityException("Shell does not have permission to access user " 3667 + userHandle); 3668 } else if (userHandle < 0) { 3669 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3670 + Debug.getCallers(3)); 3671 } 3672 } 3673 } 3674 3675 private BasePermission findPermissionTreeLP(String permName) { 3676 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3677 if (permName.startsWith(bp.name) && 3678 permName.length() > bp.name.length() && 3679 permName.charAt(bp.name.length()) == '.') { 3680 return bp; 3681 } 3682 } 3683 return null; 3684 } 3685 3686 private BasePermission checkPermissionTreeLP(String permName) { 3687 if (permName != null) { 3688 BasePermission bp = findPermissionTreeLP(permName); 3689 if (bp != null) { 3690 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3691 return bp; 3692 } 3693 throw new SecurityException("Calling uid " 3694 + Binder.getCallingUid() 3695 + " is not allowed to add to permission tree " 3696 + bp.name + " owned by uid " + bp.uid); 3697 } 3698 } 3699 throw new SecurityException("No permission tree found for " + permName); 3700 } 3701 3702 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3703 if (s1 == null) { 3704 return s2 == null; 3705 } 3706 if (s2 == null) { 3707 return false; 3708 } 3709 if (s1.getClass() != s2.getClass()) { 3710 return false; 3711 } 3712 return s1.equals(s2); 3713 } 3714 3715 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3716 if (pi1.icon != pi2.icon) return false; 3717 if (pi1.logo != pi2.logo) return false; 3718 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3719 if (!compareStrings(pi1.name, pi2.name)) return false; 3720 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3721 // We'll take care of setting this one. 3722 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3723 // These are not currently stored in settings. 3724 //if (!compareStrings(pi1.group, pi2.group)) return false; 3725 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3726 //if (pi1.labelRes != pi2.labelRes) return false; 3727 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3728 return true; 3729 } 3730 3731 int permissionInfoFootprint(PermissionInfo info) { 3732 int size = info.name.length(); 3733 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3734 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3735 return size; 3736 } 3737 3738 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3739 int size = 0; 3740 for (BasePermission perm : mSettings.mPermissions.values()) { 3741 if (perm.uid == tree.uid) { 3742 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3743 } 3744 } 3745 return size; 3746 } 3747 3748 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3749 // We calculate the max size of permissions defined by this uid and throw 3750 // if that plus the size of 'info' would exceed our stated maximum. 3751 if (tree.uid != Process.SYSTEM_UID) { 3752 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3753 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3754 throw new SecurityException("Permission tree size cap exceeded"); 3755 } 3756 } 3757 } 3758 3759 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3760 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3761 throw new SecurityException("Label must be specified in permission"); 3762 } 3763 BasePermission tree = checkPermissionTreeLP(info.name); 3764 BasePermission bp = mSettings.mPermissions.get(info.name); 3765 boolean added = bp == null; 3766 boolean changed = true; 3767 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3768 if (added) { 3769 enforcePermissionCapLocked(info, tree); 3770 bp = new BasePermission(info.name, tree.sourcePackage, 3771 BasePermission.TYPE_DYNAMIC); 3772 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3773 throw new SecurityException( 3774 "Not allowed to modify non-dynamic permission " 3775 + info.name); 3776 } else { 3777 if (bp.protectionLevel == fixedLevel 3778 && bp.perm.owner.equals(tree.perm.owner) 3779 && bp.uid == tree.uid 3780 && comparePermissionInfos(bp.perm.info, info)) { 3781 changed = false; 3782 } 3783 } 3784 bp.protectionLevel = fixedLevel; 3785 info = new PermissionInfo(info); 3786 info.protectionLevel = fixedLevel; 3787 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3788 bp.perm.info.packageName = tree.perm.info.packageName; 3789 bp.uid = tree.uid; 3790 if (added) { 3791 mSettings.mPermissions.put(info.name, bp); 3792 } 3793 if (changed) { 3794 if (!async) { 3795 mSettings.writeLPr(); 3796 } else { 3797 scheduleWriteSettingsLocked(); 3798 } 3799 } 3800 return added; 3801 } 3802 3803 @Override 3804 public boolean addPermission(PermissionInfo info) { 3805 synchronized (mPackages) { 3806 return addPermissionLocked(info, false); 3807 } 3808 } 3809 3810 @Override 3811 public boolean addPermissionAsync(PermissionInfo info) { 3812 synchronized (mPackages) { 3813 return addPermissionLocked(info, true); 3814 } 3815 } 3816 3817 @Override 3818 public void removePermission(String name) { 3819 synchronized (mPackages) { 3820 checkPermissionTreeLP(name); 3821 BasePermission bp = mSettings.mPermissions.get(name); 3822 if (bp != null) { 3823 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3824 throw new SecurityException( 3825 "Not allowed to modify non-dynamic permission " 3826 + name); 3827 } 3828 mSettings.mPermissions.remove(name); 3829 mSettings.writeLPr(); 3830 } 3831 } 3832 } 3833 3834 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3835 BasePermission bp) { 3836 int index = pkg.requestedPermissions.indexOf(bp.name); 3837 if (index == -1) { 3838 throw new SecurityException("Package " + pkg.packageName 3839 + " has not requested permission " + bp.name); 3840 } 3841 if (!bp.isRuntime() && !bp.isDevelopment()) { 3842 throw new SecurityException("Permission " + bp.name 3843 + " is not a changeable permission type"); 3844 } 3845 } 3846 3847 @Override 3848 public void grantRuntimePermission(String packageName, String name, final int userId) { 3849 if (!sUserManager.exists(userId)) { 3850 Log.e(TAG, "No such user:" + userId); 3851 return; 3852 } 3853 3854 mContext.enforceCallingOrSelfPermission( 3855 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3856 "grantRuntimePermission"); 3857 3858 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3859 true /* requireFullPermission */, true /* checkShell */, 3860 "grantRuntimePermission"); 3861 3862 final int uid; 3863 final SettingBase sb; 3864 3865 synchronized (mPackages) { 3866 final PackageParser.Package pkg = mPackages.get(packageName); 3867 if (pkg == null) { 3868 throw new IllegalArgumentException("Unknown package: " + packageName); 3869 } 3870 3871 final BasePermission bp = mSettings.mPermissions.get(name); 3872 if (bp == null) { 3873 throw new IllegalArgumentException("Unknown permission: " + name); 3874 } 3875 3876 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3877 3878 // If a permission review is required for legacy apps we represent 3879 // their permissions as always granted runtime ones since we need 3880 // to keep the review required permission flag per user while an 3881 // install permission's state is shared across all users. 3882 if (Build.PERMISSIONS_REVIEW_REQUIRED 3883 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3884 && bp.isRuntime()) { 3885 return; 3886 } 3887 3888 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3889 sb = (SettingBase) pkg.mExtras; 3890 if (sb == null) { 3891 throw new IllegalArgumentException("Unknown package: " + packageName); 3892 } 3893 3894 final PermissionsState permissionsState = sb.getPermissionsState(); 3895 3896 final int flags = permissionsState.getPermissionFlags(name, userId); 3897 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3898 throw new SecurityException("Cannot grant system fixed permission " 3899 + name + " for package " + packageName); 3900 } 3901 3902 if (bp.isDevelopment()) { 3903 // Development permissions must be handled specially, since they are not 3904 // normal runtime permissions. For now they apply to all users. 3905 if (permissionsState.grantInstallPermission(bp) != 3906 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3907 scheduleWriteSettingsLocked(); 3908 } 3909 return; 3910 } 3911 3912 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 3913 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 3914 return; 3915 } 3916 3917 final int result = permissionsState.grantRuntimePermission(bp, userId); 3918 switch (result) { 3919 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3920 return; 3921 } 3922 3923 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3924 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3925 mHandler.post(new Runnable() { 3926 @Override 3927 public void run() { 3928 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3929 } 3930 }); 3931 } 3932 break; 3933 } 3934 3935 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3936 3937 // Not critical if that is lost - app has to request again. 3938 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3939 } 3940 3941 // Only need to do this if user is initialized. Otherwise it's a new user 3942 // and there are no processes running as the user yet and there's no need 3943 // to make an expensive call to remount processes for the changed permissions. 3944 if (READ_EXTERNAL_STORAGE.equals(name) 3945 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3946 final long token = Binder.clearCallingIdentity(); 3947 try { 3948 if (sUserManager.isInitialized(userId)) { 3949 MountServiceInternal mountServiceInternal = LocalServices.getService( 3950 MountServiceInternal.class); 3951 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3952 } 3953 } finally { 3954 Binder.restoreCallingIdentity(token); 3955 } 3956 } 3957 } 3958 3959 @Override 3960 public void revokeRuntimePermission(String packageName, String name, int userId) { 3961 if (!sUserManager.exists(userId)) { 3962 Log.e(TAG, "No such user:" + userId); 3963 return; 3964 } 3965 3966 mContext.enforceCallingOrSelfPermission( 3967 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3968 "revokeRuntimePermission"); 3969 3970 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3971 true /* requireFullPermission */, true /* checkShell */, 3972 "revokeRuntimePermission"); 3973 3974 final int appId; 3975 3976 synchronized (mPackages) { 3977 final PackageParser.Package pkg = mPackages.get(packageName); 3978 if (pkg == null) { 3979 throw new IllegalArgumentException("Unknown package: " + packageName); 3980 } 3981 3982 final BasePermission bp = mSettings.mPermissions.get(name); 3983 if (bp == null) { 3984 throw new IllegalArgumentException("Unknown permission: " + name); 3985 } 3986 3987 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3988 3989 // If a permission review is required for legacy apps we represent 3990 // their permissions as always granted runtime ones since we need 3991 // to keep the review required permission flag per user while an 3992 // install permission's state is shared across all users. 3993 if (Build.PERMISSIONS_REVIEW_REQUIRED 3994 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3995 && bp.isRuntime()) { 3996 return; 3997 } 3998 3999 SettingBase sb = (SettingBase) pkg.mExtras; 4000 if (sb == null) { 4001 throw new IllegalArgumentException("Unknown package: " + packageName); 4002 } 4003 4004 final PermissionsState permissionsState = sb.getPermissionsState(); 4005 4006 final int flags = permissionsState.getPermissionFlags(name, userId); 4007 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4008 throw new SecurityException("Cannot revoke system fixed permission " 4009 + name + " for package " + packageName); 4010 } 4011 4012 if (bp.isDevelopment()) { 4013 // Development permissions must be handled specially, since they are not 4014 // normal runtime permissions. For now they apply to all users. 4015 if (permissionsState.revokeInstallPermission(bp) != 4016 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4017 scheduleWriteSettingsLocked(); 4018 } 4019 return; 4020 } 4021 4022 if (permissionsState.revokeRuntimePermission(bp, userId) == 4023 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4024 return; 4025 } 4026 4027 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4028 4029 // Critical, after this call app should never have the permission. 4030 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4031 4032 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4033 } 4034 4035 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4036 } 4037 4038 @Override 4039 public void resetRuntimePermissions() { 4040 mContext.enforceCallingOrSelfPermission( 4041 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4042 "revokeRuntimePermission"); 4043 4044 int callingUid = Binder.getCallingUid(); 4045 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4046 mContext.enforceCallingOrSelfPermission( 4047 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4048 "resetRuntimePermissions"); 4049 } 4050 4051 synchronized (mPackages) { 4052 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4053 for (int userId : UserManagerService.getInstance().getUserIds()) { 4054 final int packageCount = mPackages.size(); 4055 for (int i = 0; i < packageCount; i++) { 4056 PackageParser.Package pkg = mPackages.valueAt(i); 4057 if (!(pkg.mExtras instanceof PackageSetting)) { 4058 continue; 4059 } 4060 PackageSetting ps = (PackageSetting) pkg.mExtras; 4061 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4062 } 4063 } 4064 } 4065 } 4066 4067 @Override 4068 public int getPermissionFlags(String name, String packageName, int userId) { 4069 if (!sUserManager.exists(userId)) { 4070 return 0; 4071 } 4072 4073 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4074 4075 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4076 true /* requireFullPermission */, false /* checkShell */, 4077 "getPermissionFlags"); 4078 4079 synchronized (mPackages) { 4080 final PackageParser.Package pkg = mPackages.get(packageName); 4081 if (pkg == null) { 4082 throw new IllegalArgumentException("Unknown package: " + packageName); 4083 } 4084 4085 final BasePermission bp = mSettings.mPermissions.get(name); 4086 if (bp == null) { 4087 throw new IllegalArgumentException("Unknown permission: " + name); 4088 } 4089 4090 SettingBase sb = (SettingBase) pkg.mExtras; 4091 if (sb == null) { 4092 throw new IllegalArgumentException("Unknown package: " + packageName); 4093 } 4094 4095 PermissionsState permissionsState = sb.getPermissionsState(); 4096 return permissionsState.getPermissionFlags(name, userId); 4097 } 4098 } 4099 4100 @Override 4101 public void updatePermissionFlags(String name, String packageName, int flagMask, 4102 int flagValues, int userId) { 4103 if (!sUserManager.exists(userId)) { 4104 return; 4105 } 4106 4107 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4108 4109 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4110 true /* requireFullPermission */, true /* checkShell */, 4111 "updatePermissionFlags"); 4112 4113 // Only the system can change these flags and nothing else. 4114 if (getCallingUid() != Process.SYSTEM_UID) { 4115 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4116 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4117 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4118 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4119 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4120 } 4121 4122 synchronized (mPackages) { 4123 final PackageParser.Package pkg = mPackages.get(packageName); 4124 if (pkg == null) { 4125 throw new IllegalArgumentException("Unknown package: " + packageName); 4126 } 4127 4128 final BasePermission bp = mSettings.mPermissions.get(name); 4129 if (bp == null) { 4130 throw new IllegalArgumentException("Unknown permission: " + name); 4131 } 4132 4133 SettingBase sb = (SettingBase) pkg.mExtras; 4134 if (sb == null) { 4135 throw new IllegalArgumentException("Unknown package: " + packageName); 4136 } 4137 4138 PermissionsState permissionsState = sb.getPermissionsState(); 4139 4140 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4141 4142 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4143 // Install and runtime permissions are stored in different places, 4144 // so figure out what permission changed and persist the change. 4145 if (permissionsState.getInstallPermissionState(name) != null) { 4146 scheduleWriteSettingsLocked(); 4147 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4148 || hadState) { 4149 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4150 } 4151 } 4152 } 4153 } 4154 4155 /** 4156 * Update the permission flags for all packages and runtime permissions of a user in order 4157 * to allow device or profile owner to remove POLICY_FIXED. 4158 */ 4159 @Override 4160 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4161 if (!sUserManager.exists(userId)) { 4162 return; 4163 } 4164 4165 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4166 4167 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4168 true /* requireFullPermission */, true /* checkShell */, 4169 "updatePermissionFlagsForAllApps"); 4170 4171 // Only the system can change system fixed flags. 4172 if (getCallingUid() != Process.SYSTEM_UID) { 4173 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4174 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4175 } 4176 4177 synchronized (mPackages) { 4178 boolean changed = false; 4179 final int packageCount = mPackages.size(); 4180 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4181 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4182 SettingBase sb = (SettingBase) pkg.mExtras; 4183 if (sb == null) { 4184 continue; 4185 } 4186 PermissionsState permissionsState = sb.getPermissionsState(); 4187 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4188 userId, flagMask, flagValues); 4189 } 4190 if (changed) { 4191 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4192 } 4193 } 4194 } 4195 4196 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4197 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4198 != PackageManager.PERMISSION_GRANTED 4199 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4200 != PackageManager.PERMISSION_GRANTED) { 4201 throw new SecurityException(message + " requires " 4202 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4203 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4204 } 4205 } 4206 4207 @Override 4208 public boolean shouldShowRequestPermissionRationale(String permissionName, 4209 String packageName, int userId) { 4210 if (UserHandle.getCallingUserId() != userId) { 4211 mContext.enforceCallingPermission( 4212 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4213 "canShowRequestPermissionRationale for user " + userId); 4214 } 4215 4216 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4217 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4218 return false; 4219 } 4220 4221 if (checkPermission(permissionName, packageName, userId) 4222 == PackageManager.PERMISSION_GRANTED) { 4223 return false; 4224 } 4225 4226 final int flags; 4227 4228 final long identity = Binder.clearCallingIdentity(); 4229 try { 4230 flags = getPermissionFlags(permissionName, 4231 packageName, userId); 4232 } finally { 4233 Binder.restoreCallingIdentity(identity); 4234 } 4235 4236 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4237 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4238 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4239 4240 if ((flags & fixedFlags) != 0) { 4241 return false; 4242 } 4243 4244 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4245 } 4246 4247 @Override 4248 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4249 mContext.enforceCallingOrSelfPermission( 4250 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4251 "addOnPermissionsChangeListener"); 4252 4253 synchronized (mPackages) { 4254 mOnPermissionChangeListeners.addListenerLocked(listener); 4255 } 4256 } 4257 4258 @Override 4259 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4260 synchronized (mPackages) { 4261 mOnPermissionChangeListeners.removeListenerLocked(listener); 4262 } 4263 } 4264 4265 @Override 4266 public boolean isProtectedBroadcast(String actionName) { 4267 synchronized (mPackages) { 4268 if (mProtectedBroadcasts.contains(actionName)) { 4269 return true; 4270 } else if (actionName != null) { 4271 // TODO: remove these terrible hacks 4272 if (actionName.startsWith("android.net.netmon.lingerExpired") 4273 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4274 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4275 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4276 return true; 4277 } 4278 } 4279 } 4280 return false; 4281 } 4282 4283 @Override 4284 public int checkSignatures(String pkg1, String pkg2) { 4285 synchronized (mPackages) { 4286 final PackageParser.Package p1 = mPackages.get(pkg1); 4287 final PackageParser.Package p2 = mPackages.get(pkg2); 4288 if (p1 == null || p1.mExtras == null 4289 || p2 == null || p2.mExtras == null) { 4290 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4291 } 4292 return compareSignatures(p1.mSignatures, p2.mSignatures); 4293 } 4294 } 4295 4296 @Override 4297 public int checkUidSignatures(int uid1, int uid2) { 4298 // Map to base uids. 4299 uid1 = UserHandle.getAppId(uid1); 4300 uid2 = UserHandle.getAppId(uid2); 4301 // reader 4302 synchronized (mPackages) { 4303 Signature[] s1; 4304 Signature[] s2; 4305 Object obj = mSettings.getUserIdLPr(uid1); 4306 if (obj != null) { 4307 if (obj instanceof SharedUserSetting) { 4308 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4309 } else if (obj instanceof PackageSetting) { 4310 s1 = ((PackageSetting)obj).signatures.mSignatures; 4311 } else { 4312 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4313 } 4314 } else { 4315 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4316 } 4317 obj = mSettings.getUserIdLPr(uid2); 4318 if (obj != null) { 4319 if (obj instanceof SharedUserSetting) { 4320 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4321 } else if (obj instanceof PackageSetting) { 4322 s2 = ((PackageSetting)obj).signatures.mSignatures; 4323 } else { 4324 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4325 } 4326 } else { 4327 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4328 } 4329 return compareSignatures(s1, s2); 4330 } 4331 } 4332 4333 private void killUid(int appId, int userId, String reason) { 4334 final long identity = Binder.clearCallingIdentity(); 4335 try { 4336 IActivityManager am = ActivityManagerNative.getDefault(); 4337 if (am != null) { 4338 try { 4339 am.killUid(appId, userId, reason); 4340 } catch (RemoteException e) { 4341 /* ignore - same process */ 4342 } 4343 } 4344 } finally { 4345 Binder.restoreCallingIdentity(identity); 4346 } 4347 } 4348 4349 /** 4350 * Compares two sets of signatures. Returns: 4351 * <br /> 4352 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4353 * <br /> 4354 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4355 * <br /> 4356 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4357 * <br /> 4358 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4359 * <br /> 4360 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4361 */ 4362 static int compareSignatures(Signature[] s1, Signature[] s2) { 4363 if (s1 == null) { 4364 return s2 == null 4365 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4366 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4367 } 4368 4369 if (s2 == null) { 4370 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4371 } 4372 4373 if (s1.length != s2.length) { 4374 return PackageManager.SIGNATURE_NO_MATCH; 4375 } 4376 4377 // Since both signature sets are of size 1, we can compare without HashSets. 4378 if (s1.length == 1) { 4379 return s1[0].equals(s2[0]) ? 4380 PackageManager.SIGNATURE_MATCH : 4381 PackageManager.SIGNATURE_NO_MATCH; 4382 } 4383 4384 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4385 for (Signature sig : s1) { 4386 set1.add(sig); 4387 } 4388 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4389 for (Signature sig : s2) { 4390 set2.add(sig); 4391 } 4392 // Make sure s2 contains all signatures in s1. 4393 if (set1.equals(set2)) { 4394 return PackageManager.SIGNATURE_MATCH; 4395 } 4396 return PackageManager.SIGNATURE_NO_MATCH; 4397 } 4398 4399 /** 4400 * If the database version for this type of package (internal storage or 4401 * external storage) is less than the version where package signatures 4402 * were updated, return true. 4403 */ 4404 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4405 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4406 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4407 } 4408 4409 /** 4410 * Used for backward compatibility to make sure any packages with 4411 * certificate chains get upgraded to the new style. {@code existingSigs} 4412 * will be in the old format (since they were stored on disk from before the 4413 * system upgrade) and {@code scannedSigs} will be in the newer format. 4414 */ 4415 private int compareSignaturesCompat(PackageSignatures existingSigs, 4416 PackageParser.Package scannedPkg) { 4417 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4418 return PackageManager.SIGNATURE_NO_MATCH; 4419 } 4420 4421 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4422 for (Signature sig : existingSigs.mSignatures) { 4423 existingSet.add(sig); 4424 } 4425 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4426 for (Signature sig : scannedPkg.mSignatures) { 4427 try { 4428 Signature[] chainSignatures = sig.getChainSignatures(); 4429 for (Signature chainSig : chainSignatures) { 4430 scannedCompatSet.add(chainSig); 4431 } 4432 } catch (CertificateEncodingException e) { 4433 scannedCompatSet.add(sig); 4434 } 4435 } 4436 /* 4437 * Make sure the expanded scanned set contains all signatures in the 4438 * existing one. 4439 */ 4440 if (scannedCompatSet.equals(existingSet)) { 4441 // Migrate the old signatures to the new scheme. 4442 existingSigs.assignSignatures(scannedPkg.mSignatures); 4443 // The new KeySets will be re-added later in the scanning process. 4444 synchronized (mPackages) { 4445 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4446 } 4447 return PackageManager.SIGNATURE_MATCH; 4448 } 4449 return PackageManager.SIGNATURE_NO_MATCH; 4450 } 4451 4452 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4453 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4454 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4455 } 4456 4457 private int compareSignaturesRecover(PackageSignatures existingSigs, 4458 PackageParser.Package scannedPkg) { 4459 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4460 return PackageManager.SIGNATURE_NO_MATCH; 4461 } 4462 4463 String msg = null; 4464 try { 4465 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4466 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4467 + scannedPkg.packageName); 4468 return PackageManager.SIGNATURE_MATCH; 4469 } 4470 } catch (CertificateException e) { 4471 msg = e.getMessage(); 4472 } 4473 4474 logCriticalInfo(Log.INFO, 4475 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4476 return PackageManager.SIGNATURE_NO_MATCH; 4477 } 4478 4479 @Override 4480 public List<String> getAllPackages() { 4481 synchronized (mPackages) { 4482 return new ArrayList<String>(mPackages.keySet()); 4483 } 4484 } 4485 4486 @Override 4487 public String[] getPackagesForUid(int uid) { 4488 uid = UserHandle.getAppId(uid); 4489 // reader 4490 synchronized (mPackages) { 4491 Object obj = mSettings.getUserIdLPr(uid); 4492 if (obj instanceof SharedUserSetting) { 4493 final SharedUserSetting sus = (SharedUserSetting) obj; 4494 final int N = sus.packages.size(); 4495 final String[] res = new String[N]; 4496 final Iterator<PackageSetting> it = sus.packages.iterator(); 4497 int i = 0; 4498 while (it.hasNext()) { 4499 res[i++] = it.next().name; 4500 } 4501 return res; 4502 } else if (obj instanceof PackageSetting) { 4503 final PackageSetting ps = (PackageSetting) obj; 4504 return new String[] { ps.name }; 4505 } 4506 } 4507 return null; 4508 } 4509 4510 @Override 4511 public String getNameForUid(int uid) { 4512 // reader 4513 synchronized (mPackages) { 4514 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4515 if (obj instanceof SharedUserSetting) { 4516 final SharedUserSetting sus = (SharedUserSetting) obj; 4517 return sus.name + ":" + sus.userId; 4518 } else if (obj instanceof PackageSetting) { 4519 final PackageSetting ps = (PackageSetting) obj; 4520 return ps.name; 4521 } 4522 } 4523 return null; 4524 } 4525 4526 @Override 4527 public int getUidForSharedUser(String sharedUserName) { 4528 if(sharedUserName == null) { 4529 return -1; 4530 } 4531 // reader 4532 synchronized (mPackages) { 4533 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4534 if (suid == null) { 4535 return -1; 4536 } 4537 return suid.userId; 4538 } 4539 } 4540 4541 @Override 4542 public int getFlagsForUid(int uid) { 4543 synchronized (mPackages) { 4544 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4545 if (obj instanceof SharedUserSetting) { 4546 final SharedUserSetting sus = (SharedUserSetting) obj; 4547 return sus.pkgFlags; 4548 } else if (obj instanceof PackageSetting) { 4549 final PackageSetting ps = (PackageSetting) obj; 4550 return ps.pkgFlags; 4551 } 4552 } 4553 return 0; 4554 } 4555 4556 @Override 4557 public int getPrivateFlagsForUid(int uid) { 4558 synchronized (mPackages) { 4559 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4560 if (obj instanceof SharedUserSetting) { 4561 final SharedUserSetting sus = (SharedUserSetting) obj; 4562 return sus.pkgPrivateFlags; 4563 } else if (obj instanceof PackageSetting) { 4564 final PackageSetting ps = (PackageSetting) obj; 4565 return ps.pkgPrivateFlags; 4566 } 4567 } 4568 return 0; 4569 } 4570 4571 @Override 4572 public boolean isUidPrivileged(int uid) { 4573 uid = UserHandle.getAppId(uid); 4574 // reader 4575 synchronized (mPackages) { 4576 Object obj = mSettings.getUserIdLPr(uid); 4577 if (obj instanceof SharedUserSetting) { 4578 final SharedUserSetting sus = (SharedUserSetting) obj; 4579 final Iterator<PackageSetting> it = sus.packages.iterator(); 4580 while (it.hasNext()) { 4581 if (it.next().isPrivileged()) { 4582 return true; 4583 } 4584 } 4585 } else if (obj instanceof PackageSetting) { 4586 final PackageSetting ps = (PackageSetting) obj; 4587 return ps.isPrivileged(); 4588 } 4589 } 4590 return false; 4591 } 4592 4593 @Override 4594 public String[] getAppOpPermissionPackages(String permissionName) { 4595 synchronized (mPackages) { 4596 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4597 if (pkgs == null) { 4598 return null; 4599 } 4600 return pkgs.toArray(new String[pkgs.size()]); 4601 } 4602 } 4603 4604 @Override 4605 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4606 int flags, int userId) { 4607 if (!sUserManager.exists(userId)) return null; 4608 flags = updateFlagsForResolve(flags, userId, intent); 4609 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4610 false /* requireFullPermission */, false /* checkShell */, "resolve intent"); 4611 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4612 userId); 4613 final ResolveInfo bestChoice = 4614 chooseBestActivity(intent, resolvedType, flags, query, userId); 4615 4616 if (isEphemeralAllowed(intent, query, userId)) { 4617 final EphemeralResolveInfo ai = 4618 getEphemeralResolveInfo(intent, resolvedType, userId); 4619 if (ai != null) { 4620 if (DEBUG_EPHEMERAL) { 4621 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4622 } 4623 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4624 bestChoice.ephemeralResolveInfo = ai; 4625 } 4626 } 4627 return bestChoice; 4628 } 4629 4630 @Override 4631 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4632 IntentFilter filter, int match, ComponentName activity) { 4633 final int userId = UserHandle.getCallingUserId(); 4634 if (DEBUG_PREFERRED) { 4635 Log.v(TAG, "setLastChosenActivity intent=" + intent 4636 + " resolvedType=" + resolvedType 4637 + " flags=" + flags 4638 + " filter=" + filter 4639 + " match=" + match 4640 + " activity=" + activity); 4641 filter.dump(new PrintStreamPrinter(System.out), " "); 4642 } 4643 intent.setComponent(null); 4644 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4645 userId); 4646 // Find any earlier preferred or last chosen entries and nuke them 4647 findPreferredActivity(intent, resolvedType, 4648 flags, query, 0, false, true, false, userId); 4649 // Add the new activity as the last chosen for this filter 4650 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4651 "Setting last chosen"); 4652 } 4653 4654 @Override 4655 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4656 final int userId = UserHandle.getCallingUserId(); 4657 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4658 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4659 userId); 4660 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4661 false, false, false, userId); 4662 } 4663 4664 4665 private boolean isEphemeralAllowed( 4666 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4667 // Short circuit and return early if possible. 4668 if (DISABLE_EPHEMERAL_APPS) { 4669 return false; 4670 } 4671 final int callingUser = UserHandle.getCallingUserId(); 4672 if (callingUser != UserHandle.USER_SYSTEM) { 4673 return false; 4674 } 4675 if (mEphemeralResolverConnection == null) { 4676 return false; 4677 } 4678 if (intent.getComponent() != null) { 4679 return false; 4680 } 4681 if (intent.getPackage() != null) { 4682 return false; 4683 } 4684 final boolean isWebUri = hasWebURI(intent); 4685 if (!isWebUri) { 4686 return false; 4687 } 4688 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4689 synchronized (mPackages) { 4690 final int count = resolvedActivites.size(); 4691 for (int n = 0; n < count; n++) { 4692 ResolveInfo info = resolvedActivites.get(n); 4693 String packageName = info.activityInfo.packageName; 4694 PackageSetting ps = mSettings.mPackages.get(packageName); 4695 if (ps != null) { 4696 // Try to get the status from User settings first 4697 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4698 int status = (int) (packedStatus >> 32); 4699 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4700 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4701 if (DEBUG_EPHEMERAL) { 4702 Slog.v(TAG, "DENY ephemeral apps;" 4703 + " pkg: " + packageName + ", status: " + status); 4704 } 4705 return false; 4706 } 4707 } 4708 } 4709 } 4710 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4711 return true; 4712 } 4713 4714 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4715 int userId) { 4716 MessageDigest digest = null; 4717 try { 4718 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4719 } catch (NoSuchAlgorithmException e) { 4720 // If we can't create a digest, ignore ephemeral apps. 4721 return null; 4722 } 4723 4724 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4725 final byte[] digestBytes = digest.digest(hostBytes); 4726 int shaPrefix = 4727 digestBytes[0] << 24 4728 | digestBytes[1] << 16 4729 | digestBytes[2] << 8 4730 | digestBytes[3] << 0; 4731 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4732 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4733 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4734 // No hash prefix match; there are no ephemeral apps for this domain. 4735 return null; 4736 } 4737 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4738 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4739 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4740 continue; 4741 } 4742 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4743 // No filters; this should never happen. 4744 if (filters.isEmpty()) { 4745 continue; 4746 } 4747 // We have a domain match; resolve the filters to see if anything matches. 4748 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4749 for (int j = filters.size() - 1; j >= 0; --j) { 4750 final EphemeralResolveIntentInfo intentInfo = 4751 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4752 ephemeralResolver.addFilter(intentInfo); 4753 } 4754 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4755 intent, resolvedType, false /*defaultOnly*/, userId); 4756 if (!matchedResolveInfoList.isEmpty()) { 4757 return matchedResolveInfoList.get(0); 4758 } 4759 } 4760 // Hash or filter mis-match; no ephemeral apps for this domain. 4761 return null; 4762 } 4763 4764 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4765 int flags, List<ResolveInfo> query, int userId) { 4766 if (query != null) { 4767 final int N = query.size(); 4768 if (N == 1) { 4769 return query.get(0); 4770 } else if (N > 1) { 4771 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4772 // If there is more than one activity with the same priority, 4773 // then let the user decide between them. 4774 ResolveInfo r0 = query.get(0); 4775 ResolveInfo r1 = query.get(1); 4776 if (DEBUG_INTENT_MATCHING || debug) { 4777 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4778 + r1.activityInfo.name + "=" + r1.priority); 4779 } 4780 // If the first activity has a higher priority, or a different 4781 // default, then it is always desirable to pick it. 4782 if (r0.priority != r1.priority 4783 || r0.preferredOrder != r1.preferredOrder 4784 || r0.isDefault != r1.isDefault) { 4785 return query.get(0); 4786 } 4787 // If we have saved a preference for a preferred activity for 4788 // this Intent, use that. 4789 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4790 flags, query, r0.priority, true, false, debug, userId); 4791 if (ri != null) { 4792 return ri; 4793 } 4794 ri = new ResolveInfo(mResolveInfo); 4795 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4796 ri.activityInfo.applicationInfo = new ApplicationInfo( 4797 ri.activityInfo.applicationInfo); 4798 if (userId != 0) { 4799 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4800 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4801 } 4802 // Make sure that the resolver is displayable in car mode 4803 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4804 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4805 return ri; 4806 } 4807 } 4808 return null; 4809 } 4810 4811 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4812 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4813 final int N = query.size(); 4814 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4815 .get(userId); 4816 // Get the list of persistent preferred activities that handle the intent 4817 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4818 List<PersistentPreferredActivity> pprefs = ppir != null 4819 ? ppir.queryIntent(intent, resolvedType, 4820 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4821 : null; 4822 if (pprefs != null && pprefs.size() > 0) { 4823 final int M = pprefs.size(); 4824 for (int i=0; i<M; i++) { 4825 final PersistentPreferredActivity ppa = pprefs.get(i); 4826 if (DEBUG_PREFERRED || debug) { 4827 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4828 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4829 + "\n component=" + ppa.mComponent); 4830 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4831 } 4832 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4833 flags | MATCH_DISABLED_COMPONENTS, userId); 4834 if (DEBUG_PREFERRED || debug) { 4835 Slog.v(TAG, "Found persistent preferred activity:"); 4836 if (ai != null) { 4837 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4838 } else { 4839 Slog.v(TAG, " null"); 4840 } 4841 } 4842 if (ai == null) { 4843 // This previously registered persistent preferred activity 4844 // component is no longer known. Ignore it and do NOT remove it. 4845 continue; 4846 } 4847 for (int j=0; j<N; j++) { 4848 final ResolveInfo ri = query.get(j); 4849 if (!ri.activityInfo.applicationInfo.packageName 4850 .equals(ai.applicationInfo.packageName)) { 4851 continue; 4852 } 4853 if (!ri.activityInfo.name.equals(ai.name)) { 4854 continue; 4855 } 4856 // Found a persistent preference that can handle the intent. 4857 if (DEBUG_PREFERRED || debug) { 4858 Slog.v(TAG, "Returning persistent preferred activity: " + 4859 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4860 } 4861 return ri; 4862 } 4863 } 4864 } 4865 return null; 4866 } 4867 4868 // TODO: handle preferred activities missing while user has amnesia 4869 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4870 List<ResolveInfo> query, int priority, boolean always, 4871 boolean removeMatches, boolean debug, int userId) { 4872 if (!sUserManager.exists(userId)) return null; 4873 flags = updateFlagsForResolve(flags, userId, intent); 4874 // writer 4875 synchronized (mPackages) { 4876 if (intent.getSelector() != null) { 4877 intent = intent.getSelector(); 4878 } 4879 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4880 4881 // Try to find a matching persistent preferred activity. 4882 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4883 debug, userId); 4884 4885 // If a persistent preferred activity matched, use it. 4886 if (pri != null) { 4887 return pri; 4888 } 4889 4890 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4891 // Get the list of preferred activities that handle the intent 4892 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4893 List<PreferredActivity> prefs = pir != null 4894 ? pir.queryIntent(intent, resolvedType, 4895 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4896 : null; 4897 if (prefs != null && prefs.size() > 0) { 4898 boolean changed = false; 4899 try { 4900 // First figure out how good the original match set is. 4901 // We will only allow preferred activities that came 4902 // from the same match quality. 4903 int match = 0; 4904 4905 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4906 4907 final int N = query.size(); 4908 for (int j=0; j<N; j++) { 4909 final ResolveInfo ri = query.get(j); 4910 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4911 + ": 0x" + Integer.toHexString(match)); 4912 if (ri.match > match) { 4913 match = ri.match; 4914 } 4915 } 4916 4917 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4918 + Integer.toHexString(match)); 4919 4920 match &= IntentFilter.MATCH_CATEGORY_MASK; 4921 final int M = prefs.size(); 4922 for (int i=0; i<M; i++) { 4923 final PreferredActivity pa = prefs.get(i); 4924 if (DEBUG_PREFERRED || debug) { 4925 Slog.v(TAG, "Checking PreferredActivity ds=" 4926 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4927 + "\n component=" + pa.mPref.mComponent); 4928 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4929 } 4930 if (pa.mPref.mMatch != match) { 4931 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4932 + Integer.toHexString(pa.mPref.mMatch)); 4933 continue; 4934 } 4935 // If it's not an "always" type preferred activity and that's what we're 4936 // looking for, skip it. 4937 if (always && !pa.mPref.mAlways) { 4938 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4939 continue; 4940 } 4941 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4942 flags | MATCH_DISABLED_COMPONENTS, userId); 4943 if (DEBUG_PREFERRED || debug) { 4944 Slog.v(TAG, "Found preferred activity:"); 4945 if (ai != null) { 4946 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4947 } else { 4948 Slog.v(TAG, " null"); 4949 } 4950 } 4951 if (ai == null) { 4952 // This previously registered preferred activity 4953 // component is no longer known. Most likely an update 4954 // to the app was installed and in the new version this 4955 // component no longer exists. Clean it up by removing 4956 // it from the preferred activities list, and skip it. 4957 Slog.w(TAG, "Removing dangling preferred activity: " 4958 + pa.mPref.mComponent); 4959 pir.removeFilter(pa); 4960 changed = true; 4961 continue; 4962 } 4963 for (int j=0; j<N; j++) { 4964 final ResolveInfo ri = query.get(j); 4965 if (!ri.activityInfo.applicationInfo.packageName 4966 .equals(ai.applicationInfo.packageName)) { 4967 continue; 4968 } 4969 if (!ri.activityInfo.name.equals(ai.name)) { 4970 continue; 4971 } 4972 4973 if (removeMatches) { 4974 pir.removeFilter(pa); 4975 changed = true; 4976 if (DEBUG_PREFERRED) { 4977 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4978 } 4979 break; 4980 } 4981 4982 // Okay we found a previously set preferred or last chosen app. 4983 // If the result set is different from when this 4984 // was created, we need to clear it and re-ask the 4985 // user their preference, if we're looking for an "always" type entry. 4986 if (always && !pa.mPref.sameSet(query)) { 4987 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4988 + intent + " type " + resolvedType); 4989 if (DEBUG_PREFERRED) { 4990 Slog.v(TAG, "Removing preferred activity since set changed " 4991 + pa.mPref.mComponent); 4992 } 4993 pir.removeFilter(pa); 4994 // Re-add the filter as a "last chosen" entry (!always) 4995 PreferredActivity lastChosen = new PreferredActivity( 4996 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4997 pir.addFilter(lastChosen); 4998 changed = true; 4999 return null; 5000 } 5001 5002 // Yay! Either the set matched or we're looking for the last chosen 5003 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5004 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5005 return ri; 5006 } 5007 } 5008 } finally { 5009 if (changed) { 5010 if (DEBUG_PREFERRED) { 5011 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5012 } 5013 scheduleWritePackageRestrictionsLocked(userId); 5014 } 5015 } 5016 } 5017 } 5018 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5019 return null; 5020 } 5021 5022 /* 5023 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5024 */ 5025 @Override 5026 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5027 int targetUserId) { 5028 mContext.enforceCallingOrSelfPermission( 5029 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5030 List<CrossProfileIntentFilter> matches = 5031 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5032 if (matches != null) { 5033 int size = matches.size(); 5034 for (int i = 0; i < size; i++) { 5035 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5036 } 5037 } 5038 if (hasWebURI(intent)) { 5039 // cross-profile app linking works only towards the parent. 5040 final UserInfo parent = getProfileParent(sourceUserId); 5041 synchronized(mPackages) { 5042 int flags = updateFlagsForResolve(0, parent.id, intent); 5043 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5044 intent, resolvedType, flags, sourceUserId, parent.id); 5045 return xpDomainInfo != null; 5046 } 5047 } 5048 return false; 5049 } 5050 5051 private UserInfo getProfileParent(int userId) { 5052 final long identity = Binder.clearCallingIdentity(); 5053 try { 5054 return sUserManager.getProfileParent(userId); 5055 } finally { 5056 Binder.restoreCallingIdentity(identity); 5057 } 5058 } 5059 5060 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5061 String resolvedType, int userId) { 5062 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5063 if (resolver != null) { 5064 return resolver.queryIntent(intent, resolvedType, false, userId); 5065 } 5066 return null; 5067 } 5068 5069 @Override 5070 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5071 String resolvedType, int flags, int userId) { 5072 return new ParceledListSlice<>( 5073 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5074 } 5075 5076 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5077 String resolvedType, int flags, int userId) { 5078 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5079 flags = updateFlagsForResolve(flags, userId, intent); 5080 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5081 false /* requireFullPermission */, false /* checkShell */, 5082 "query intent activities"); 5083 ComponentName comp = intent.getComponent(); 5084 if (comp == null) { 5085 if (intent.getSelector() != null) { 5086 intent = intent.getSelector(); 5087 comp = intent.getComponent(); 5088 } 5089 } 5090 5091 if (comp != null) { 5092 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5093 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5094 if (ai != null) { 5095 final ResolveInfo ri = new ResolveInfo(); 5096 ri.activityInfo = ai; 5097 list.add(ri); 5098 } 5099 return list; 5100 } 5101 5102 // reader 5103 synchronized (mPackages) { 5104 final String pkgName = intent.getPackage(); 5105 if (pkgName == null) { 5106 List<CrossProfileIntentFilter> matchingFilters = 5107 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5108 // Check for results that need to skip the current profile. 5109 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5110 resolvedType, flags, userId); 5111 if (xpResolveInfo != null) { 5112 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5113 result.add(xpResolveInfo); 5114 return filterIfNotSystemUser(result, userId); 5115 } 5116 5117 // Check for results in the current profile. 5118 List<ResolveInfo> result = mActivities.queryIntent( 5119 intent, resolvedType, flags, userId); 5120 result = filterIfNotSystemUser(result, userId); 5121 5122 // Check for cross profile results. 5123 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5124 xpResolveInfo = queryCrossProfileIntents( 5125 matchingFilters, intent, resolvedType, flags, userId, 5126 hasNonNegativePriorityResult); 5127 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5128 boolean isVisibleToUser = filterIfNotSystemUser( 5129 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5130 if (isVisibleToUser) { 5131 result.add(xpResolveInfo); 5132 Collections.sort(result, mResolvePrioritySorter); 5133 } 5134 } 5135 if (hasWebURI(intent)) { 5136 CrossProfileDomainInfo xpDomainInfo = null; 5137 final UserInfo parent = getProfileParent(userId); 5138 if (parent != null) { 5139 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5140 flags, userId, parent.id); 5141 } 5142 if (xpDomainInfo != null) { 5143 if (xpResolveInfo != null) { 5144 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5145 // in the result. 5146 result.remove(xpResolveInfo); 5147 } 5148 if (result.size() == 0) { 5149 result.add(xpDomainInfo.resolveInfo); 5150 return result; 5151 } 5152 } else if (result.size() <= 1) { 5153 return result; 5154 } 5155 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5156 xpDomainInfo, userId); 5157 Collections.sort(result, mResolvePrioritySorter); 5158 } 5159 return result; 5160 } 5161 final PackageParser.Package pkg = mPackages.get(pkgName); 5162 if (pkg != null) { 5163 return filterIfNotSystemUser( 5164 mActivities.queryIntentForPackage( 5165 intent, resolvedType, flags, pkg.activities, userId), 5166 userId); 5167 } 5168 return new ArrayList<ResolveInfo>(); 5169 } 5170 } 5171 5172 private static class CrossProfileDomainInfo { 5173 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5174 ResolveInfo resolveInfo; 5175 /* Best domain verification status of the activities found in the other profile */ 5176 int bestDomainVerificationStatus; 5177 } 5178 5179 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5180 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5181 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5182 sourceUserId)) { 5183 return null; 5184 } 5185 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5186 resolvedType, flags, parentUserId); 5187 5188 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5189 return null; 5190 } 5191 CrossProfileDomainInfo result = null; 5192 int size = resultTargetUser.size(); 5193 for (int i = 0; i < size; i++) { 5194 ResolveInfo riTargetUser = resultTargetUser.get(i); 5195 // Intent filter verification is only for filters that specify a host. So don't return 5196 // those that handle all web uris. 5197 if (riTargetUser.handleAllWebDataURI) { 5198 continue; 5199 } 5200 String packageName = riTargetUser.activityInfo.packageName; 5201 PackageSetting ps = mSettings.mPackages.get(packageName); 5202 if (ps == null) { 5203 continue; 5204 } 5205 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5206 int status = (int)(verificationState >> 32); 5207 if (result == null) { 5208 result = new CrossProfileDomainInfo(); 5209 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5210 sourceUserId, parentUserId); 5211 result.bestDomainVerificationStatus = status; 5212 } else { 5213 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5214 result.bestDomainVerificationStatus); 5215 } 5216 } 5217 // Don't consider matches with status NEVER across profiles. 5218 if (result != null && result.bestDomainVerificationStatus 5219 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5220 return null; 5221 } 5222 return result; 5223 } 5224 5225 /** 5226 * Verification statuses are ordered from the worse to the best, except for 5227 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5228 */ 5229 private int bestDomainVerificationStatus(int status1, int status2) { 5230 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5231 return status2; 5232 } 5233 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5234 return status1; 5235 } 5236 return (int) MathUtils.max(status1, status2); 5237 } 5238 5239 private boolean isUserEnabled(int userId) { 5240 long callingId = Binder.clearCallingIdentity(); 5241 try { 5242 UserInfo userInfo = sUserManager.getUserInfo(userId); 5243 return userInfo != null && userInfo.isEnabled(); 5244 } finally { 5245 Binder.restoreCallingIdentity(callingId); 5246 } 5247 } 5248 5249 /** 5250 * Filter out activities with systemUserOnly flag set, when current user is not System. 5251 * 5252 * @return filtered list 5253 */ 5254 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5255 if (userId == UserHandle.USER_SYSTEM) { 5256 return resolveInfos; 5257 } 5258 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5259 ResolveInfo info = resolveInfos.get(i); 5260 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5261 resolveInfos.remove(i); 5262 } 5263 } 5264 return resolveInfos; 5265 } 5266 5267 /** 5268 * @param resolveInfos list of resolve infos in descending priority order 5269 * @return if the list contains a resolve info with non-negative priority 5270 */ 5271 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5272 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5273 } 5274 5275 private static boolean hasWebURI(Intent intent) { 5276 if (intent.getData() == null) { 5277 return false; 5278 } 5279 final String scheme = intent.getScheme(); 5280 if (TextUtils.isEmpty(scheme)) { 5281 return false; 5282 } 5283 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5284 } 5285 5286 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5287 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5288 int userId) { 5289 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5290 5291 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5292 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5293 candidates.size()); 5294 } 5295 5296 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5297 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5298 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5299 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5300 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5301 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5302 5303 synchronized (mPackages) { 5304 final int count = candidates.size(); 5305 // First, try to use linked apps. Partition the candidates into four lists: 5306 // one for the final results, one for the "do not use ever", one for "undefined status" 5307 // and finally one for "browser app type". 5308 for (int n=0; n<count; n++) { 5309 ResolveInfo info = candidates.get(n); 5310 String packageName = info.activityInfo.packageName; 5311 PackageSetting ps = mSettings.mPackages.get(packageName); 5312 if (ps != null) { 5313 // Add to the special match all list (Browser use case) 5314 if (info.handleAllWebDataURI) { 5315 matchAllList.add(info); 5316 continue; 5317 } 5318 // Try to get the status from User settings first 5319 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5320 int status = (int)(packedStatus >> 32); 5321 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5322 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5323 if (DEBUG_DOMAIN_VERIFICATION) { 5324 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5325 + " : linkgen=" + linkGeneration); 5326 } 5327 // Use link-enabled generation as preferredOrder, i.e. 5328 // prefer newly-enabled over earlier-enabled. 5329 info.preferredOrder = linkGeneration; 5330 alwaysList.add(info); 5331 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5332 if (DEBUG_DOMAIN_VERIFICATION) { 5333 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5334 } 5335 neverList.add(info); 5336 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5337 if (DEBUG_DOMAIN_VERIFICATION) { 5338 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5339 } 5340 alwaysAskList.add(info); 5341 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5342 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5343 if (DEBUG_DOMAIN_VERIFICATION) { 5344 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5345 } 5346 undefinedList.add(info); 5347 } 5348 } 5349 } 5350 5351 // We'll want to include browser possibilities in a few cases 5352 boolean includeBrowser = false; 5353 5354 // First try to add the "always" resolution(s) for the current user, if any 5355 if (alwaysList.size() > 0) { 5356 result.addAll(alwaysList); 5357 } else { 5358 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5359 result.addAll(undefinedList); 5360 // Maybe add one for the other profile. 5361 if (xpDomainInfo != null && ( 5362 xpDomainInfo.bestDomainVerificationStatus 5363 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5364 result.add(xpDomainInfo.resolveInfo); 5365 } 5366 includeBrowser = true; 5367 } 5368 5369 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5370 // If there were 'always' entries their preferred order has been set, so we also 5371 // back that off to make the alternatives equivalent 5372 if (alwaysAskList.size() > 0) { 5373 for (ResolveInfo i : result) { 5374 i.preferredOrder = 0; 5375 } 5376 result.addAll(alwaysAskList); 5377 includeBrowser = true; 5378 } 5379 5380 if (includeBrowser) { 5381 // Also add browsers (all of them or only the default one) 5382 if (DEBUG_DOMAIN_VERIFICATION) { 5383 Slog.v(TAG, " ...including browsers in candidate set"); 5384 } 5385 if ((matchFlags & MATCH_ALL) != 0) { 5386 result.addAll(matchAllList); 5387 } else { 5388 // Browser/generic handling case. If there's a default browser, go straight 5389 // to that (but only if there is no other higher-priority match). 5390 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5391 int maxMatchPrio = 0; 5392 ResolveInfo defaultBrowserMatch = null; 5393 final int numCandidates = matchAllList.size(); 5394 for (int n = 0; n < numCandidates; n++) { 5395 ResolveInfo info = matchAllList.get(n); 5396 // track the highest overall match priority... 5397 if (info.priority > maxMatchPrio) { 5398 maxMatchPrio = info.priority; 5399 } 5400 // ...and the highest-priority default browser match 5401 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5402 if (defaultBrowserMatch == null 5403 || (defaultBrowserMatch.priority < info.priority)) { 5404 if (debug) { 5405 Slog.v(TAG, "Considering default browser match " + info); 5406 } 5407 defaultBrowserMatch = info; 5408 } 5409 } 5410 } 5411 if (defaultBrowserMatch != null 5412 && defaultBrowserMatch.priority >= maxMatchPrio 5413 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5414 { 5415 if (debug) { 5416 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5417 } 5418 result.add(defaultBrowserMatch); 5419 } else { 5420 result.addAll(matchAllList); 5421 } 5422 } 5423 5424 // If there is nothing selected, add all candidates and remove the ones that the user 5425 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5426 if (result.size() == 0) { 5427 result.addAll(candidates); 5428 result.removeAll(neverList); 5429 } 5430 } 5431 } 5432 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5433 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5434 result.size()); 5435 for (ResolveInfo info : result) { 5436 Slog.v(TAG, " + " + info.activityInfo); 5437 } 5438 } 5439 return result; 5440 } 5441 5442 // Returns a packed value as a long: 5443 // 5444 // high 'int'-sized word: link status: undefined/ask/never/always. 5445 // low 'int'-sized word: relative priority among 'always' results. 5446 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5447 long result = ps.getDomainVerificationStatusForUser(userId); 5448 // if none available, get the master status 5449 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5450 if (ps.getIntentFilterVerificationInfo() != null) { 5451 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5452 } 5453 } 5454 return result; 5455 } 5456 5457 private ResolveInfo querySkipCurrentProfileIntents( 5458 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5459 int flags, int sourceUserId) { 5460 if (matchingFilters != null) { 5461 int size = matchingFilters.size(); 5462 for (int i = 0; i < size; i ++) { 5463 CrossProfileIntentFilter filter = matchingFilters.get(i); 5464 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5465 // Checking if there are activities in the target user that can handle the 5466 // intent. 5467 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5468 resolvedType, flags, sourceUserId); 5469 if (resolveInfo != null) { 5470 return resolveInfo; 5471 } 5472 } 5473 } 5474 } 5475 return null; 5476 } 5477 5478 // Return matching ResolveInfo in target user if any. 5479 private ResolveInfo queryCrossProfileIntents( 5480 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5481 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5482 if (matchingFilters != null) { 5483 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5484 // match the same intent. For performance reasons, it is better not to 5485 // run queryIntent twice for the same userId 5486 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5487 int size = matchingFilters.size(); 5488 for (int i = 0; i < size; i++) { 5489 CrossProfileIntentFilter filter = matchingFilters.get(i); 5490 int targetUserId = filter.getTargetUserId(); 5491 boolean skipCurrentProfile = 5492 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5493 boolean skipCurrentProfileIfNoMatchFound = 5494 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5495 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5496 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5497 // Checking if there are activities in the target user that can handle the 5498 // intent. 5499 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5500 resolvedType, flags, sourceUserId); 5501 if (resolveInfo != null) return resolveInfo; 5502 alreadyTriedUserIds.put(targetUserId, true); 5503 } 5504 } 5505 } 5506 return null; 5507 } 5508 5509 /** 5510 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5511 * will forward the intent to the filter's target user. 5512 * Otherwise, returns null. 5513 */ 5514 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5515 String resolvedType, int flags, int sourceUserId) { 5516 int targetUserId = filter.getTargetUserId(); 5517 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5518 resolvedType, flags, targetUserId); 5519 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5520 // If all the matches in the target profile are suspended, return null. 5521 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5522 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5523 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5524 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5525 targetUserId); 5526 } 5527 } 5528 } 5529 return null; 5530 } 5531 5532 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5533 int sourceUserId, int targetUserId) { 5534 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5535 long ident = Binder.clearCallingIdentity(); 5536 boolean targetIsProfile; 5537 try { 5538 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5539 } finally { 5540 Binder.restoreCallingIdentity(ident); 5541 } 5542 String className; 5543 if (targetIsProfile) { 5544 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5545 } else { 5546 className = FORWARD_INTENT_TO_PARENT; 5547 } 5548 ComponentName forwardingActivityComponentName = new ComponentName( 5549 mAndroidApplication.packageName, className); 5550 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5551 sourceUserId); 5552 if (!targetIsProfile) { 5553 forwardingActivityInfo.showUserIcon = targetUserId; 5554 forwardingResolveInfo.noResourceId = true; 5555 } 5556 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5557 forwardingResolveInfo.priority = 0; 5558 forwardingResolveInfo.preferredOrder = 0; 5559 forwardingResolveInfo.match = 0; 5560 forwardingResolveInfo.isDefault = true; 5561 forwardingResolveInfo.filter = filter; 5562 forwardingResolveInfo.targetUserId = targetUserId; 5563 return forwardingResolveInfo; 5564 } 5565 5566 @Override 5567 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5568 Intent[] specifics, String[] specificTypes, Intent intent, 5569 String resolvedType, int flags, int userId) { 5570 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5571 specificTypes, intent, resolvedType, flags, userId)); 5572 } 5573 5574 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5575 Intent[] specifics, String[] specificTypes, Intent intent, 5576 String resolvedType, int flags, int userId) { 5577 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5578 flags = updateFlagsForResolve(flags, userId, intent); 5579 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5580 false /* requireFullPermission */, false /* checkShell */, 5581 "query intent activity options"); 5582 final String resultsAction = intent.getAction(); 5583 5584 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5585 | PackageManager.GET_RESOLVED_FILTER, userId); 5586 5587 if (DEBUG_INTENT_MATCHING) { 5588 Log.v(TAG, "Query " + intent + ": " + results); 5589 } 5590 5591 int specificsPos = 0; 5592 int N; 5593 5594 // todo: note that the algorithm used here is O(N^2). This 5595 // isn't a problem in our current environment, but if we start running 5596 // into situations where we have more than 5 or 10 matches then this 5597 // should probably be changed to something smarter... 5598 5599 // First we go through and resolve each of the specific items 5600 // that were supplied, taking care of removing any corresponding 5601 // duplicate items in the generic resolve list. 5602 if (specifics != null) { 5603 for (int i=0; i<specifics.length; i++) { 5604 final Intent sintent = specifics[i]; 5605 if (sintent == null) { 5606 continue; 5607 } 5608 5609 if (DEBUG_INTENT_MATCHING) { 5610 Log.v(TAG, "Specific #" + i + ": " + sintent); 5611 } 5612 5613 String action = sintent.getAction(); 5614 if (resultsAction != null && resultsAction.equals(action)) { 5615 // If this action was explicitly requested, then don't 5616 // remove things that have it. 5617 action = null; 5618 } 5619 5620 ResolveInfo ri = null; 5621 ActivityInfo ai = null; 5622 5623 ComponentName comp = sintent.getComponent(); 5624 if (comp == null) { 5625 ri = resolveIntent( 5626 sintent, 5627 specificTypes != null ? specificTypes[i] : null, 5628 flags, userId); 5629 if (ri == null) { 5630 continue; 5631 } 5632 if (ri == mResolveInfo) { 5633 // ACK! Must do something better with this. 5634 } 5635 ai = ri.activityInfo; 5636 comp = new ComponentName(ai.applicationInfo.packageName, 5637 ai.name); 5638 } else { 5639 ai = getActivityInfo(comp, flags, userId); 5640 if (ai == null) { 5641 continue; 5642 } 5643 } 5644 5645 // Look for any generic query activities that are duplicates 5646 // of this specific one, and remove them from the results. 5647 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5648 N = results.size(); 5649 int j; 5650 for (j=specificsPos; j<N; j++) { 5651 ResolveInfo sri = results.get(j); 5652 if ((sri.activityInfo.name.equals(comp.getClassName()) 5653 && sri.activityInfo.applicationInfo.packageName.equals( 5654 comp.getPackageName())) 5655 || (action != null && sri.filter.matchAction(action))) { 5656 results.remove(j); 5657 if (DEBUG_INTENT_MATCHING) Log.v( 5658 TAG, "Removing duplicate item from " + j 5659 + " due to specific " + specificsPos); 5660 if (ri == null) { 5661 ri = sri; 5662 } 5663 j--; 5664 N--; 5665 } 5666 } 5667 5668 // Add this specific item to its proper place. 5669 if (ri == null) { 5670 ri = new ResolveInfo(); 5671 ri.activityInfo = ai; 5672 } 5673 results.add(specificsPos, ri); 5674 ri.specificIndex = i; 5675 specificsPos++; 5676 } 5677 } 5678 5679 // Now we go through the remaining generic results and remove any 5680 // duplicate actions that are found here. 5681 N = results.size(); 5682 for (int i=specificsPos; i<N-1; i++) { 5683 final ResolveInfo rii = results.get(i); 5684 if (rii.filter == null) { 5685 continue; 5686 } 5687 5688 // Iterate over all of the actions of this result's intent 5689 // filter... typically this should be just one. 5690 final Iterator<String> it = rii.filter.actionsIterator(); 5691 if (it == null) { 5692 continue; 5693 } 5694 while (it.hasNext()) { 5695 final String action = it.next(); 5696 if (resultsAction != null && resultsAction.equals(action)) { 5697 // If this action was explicitly requested, then don't 5698 // remove things that have it. 5699 continue; 5700 } 5701 for (int j=i+1; j<N; j++) { 5702 final ResolveInfo rij = results.get(j); 5703 if (rij.filter != null && rij.filter.hasAction(action)) { 5704 results.remove(j); 5705 if (DEBUG_INTENT_MATCHING) Log.v( 5706 TAG, "Removing duplicate item from " + j 5707 + " due to action " + action + " at " + i); 5708 j--; 5709 N--; 5710 } 5711 } 5712 } 5713 5714 // If the caller didn't request filter information, drop it now 5715 // so we don't have to marshall/unmarshall it. 5716 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5717 rii.filter = null; 5718 } 5719 } 5720 5721 // Filter out the caller activity if so requested. 5722 if (caller != null) { 5723 N = results.size(); 5724 for (int i=0; i<N; i++) { 5725 ActivityInfo ainfo = results.get(i).activityInfo; 5726 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5727 && caller.getClassName().equals(ainfo.name)) { 5728 results.remove(i); 5729 break; 5730 } 5731 } 5732 } 5733 5734 // If the caller didn't request filter information, 5735 // drop them now so we don't have to 5736 // marshall/unmarshall it. 5737 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5738 N = results.size(); 5739 for (int i=0; i<N; i++) { 5740 results.get(i).filter = null; 5741 } 5742 } 5743 5744 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5745 return results; 5746 } 5747 5748 @Override 5749 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 5750 String resolvedType, int flags, int userId) { 5751 return new ParceledListSlice<>( 5752 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 5753 } 5754 5755 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 5756 String resolvedType, int flags, int userId) { 5757 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5758 flags = updateFlagsForResolve(flags, userId, intent); 5759 ComponentName comp = intent.getComponent(); 5760 if (comp == null) { 5761 if (intent.getSelector() != null) { 5762 intent = intent.getSelector(); 5763 comp = intent.getComponent(); 5764 } 5765 } 5766 if (comp != null) { 5767 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5768 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5769 if (ai != null) { 5770 ResolveInfo ri = new ResolveInfo(); 5771 ri.activityInfo = ai; 5772 list.add(ri); 5773 } 5774 return list; 5775 } 5776 5777 // reader 5778 synchronized (mPackages) { 5779 String pkgName = intent.getPackage(); 5780 if (pkgName == null) { 5781 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5782 } 5783 final PackageParser.Package pkg = mPackages.get(pkgName); 5784 if (pkg != null) { 5785 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5786 userId); 5787 } 5788 return Collections.emptyList(); 5789 } 5790 } 5791 5792 @Override 5793 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5794 if (!sUserManager.exists(userId)) return null; 5795 flags = updateFlagsForResolve(flags, userId, intent); 5796 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 5797 if (query != null) { 5798 if (query.size() >= 1) { 5799 // If there is more than one service with the same priority, 5800 // just arbitrarily pick the first one. 5801 return query.get(0); 5802 } 5803 } 5804 return null; 5805 } 5806 5807 @Override 5808 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 5809 String resolvedType, int flags, int userId) { 5810 return new ParceledListSlice<>( 5811 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 5812 } 5813 5814 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 5815 String resolvedType, int flags, int userId) { 5816 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5817 flags = updateFlagsForResolve(flags, userId, intent); 5818 ComponentName comp = intent.getComponent(); 5819 if (comp == null) { 5820 if (intent.getSelector() != null) { 5821 intent = intent.getSelector(); 5822 comp = intent.getComponent(); 5823 } 5824 } 5825 if (comp != null) { 5826 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5827 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5828 if (si != null) { 5829 final ResolveInfo ri = new ResolveInfo(); 5830 ri.serviceInfo = si; 5831 list.add(ri); 5832 } 5833 return list; 5834 } 5835 5836 // reader 5837 synchronized (mPackages) { 5838 String pkgName = intent.getPackage(); 5839 if (pkgName == null) { 5840 return mServices.queryIntent(intent, resolvedType, flags, userId); 5841 } 5842 final PackageParser.Package pkg = mPackages.get(pkgName); 5843 if (pkg != null) { 5844 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5845 userId); 5846 } 5847 return Collections.emptyList(); 5848 } 5849 } 5850 5851 @Override 5852 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 5853 String resolvedType, int flags, int userId) { 5854 return new ParceledListSlice<>( 5855 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 5856 } 5857 5858 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 5859 Intent intent, String resolvedType, int flags, int userId) { 5860 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5861 flags = updateFlagsForResolve(flags, userId, intent); 5862 ComponentName comp = intent.getComponent(); 5863 if (comp == null) { 5864 if (intent.getSelector() != null) { 5865 intent = intent.getSelector(); 5866 comp = intent.getComponent(); 5867 } 5868 } 5869 if (comp != null) { 5870 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5871 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5872 if (pi != null) { 5873 final ResolveInfo ri = new ResolveInfo(); 5874 ri.providerInfo = pi; 5875 list.add(ri); 5876 } 5877 return list; 5878 } 5879 5880 // reader 5881 synchronized (mPackages) { 5882 String pkgName = intent.getPackage(); 5883 if (pkgName == null) { 5884 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5885 } 5886 final PackageParser.Package pkg = mPackages.get(pkgName); 5887 if (pkg != null) { 5888 return mProviders.queryIntentForPackage( 5889 intent, resolvedType, flags, pkg.providers, userId); 5890 } 5891 return Collections.emptyList(); 5892 } 5893 } 5894 5895 @Override 5896 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5897 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5898 flags = updateFlagsForPackage(flags, userId, null); 5899 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5900 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5901 true /* requireFullPermission */, false /* checkShell */, 5902 "get installed packages"); 5903 5904 // writer 5905 synchronized (mPackages) { 5906 ArrayList<PackageInfo> list; 5907 if (listUninstalled) { 5908 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5909 for (PackageSetting ps : mSettings.mPackages.values()) { 5910 PackageInfo pi; 5911 if (ps.pkg != null) { 5912 pi = generatePackageInfo(ps.pkg, flags, userId); 5913 } else { 5914 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5915 } 5916 if (pi != null) { 5917 list.add(pi); 5918 } 5919 } 5920 } else { 5921 list = new ArrayList<PackageInfo>(mPackages.size()); 5922 for (PackageParser.Package p : mPackages.values()) { 5923 PackageInfo pi = generatePackageInfo(p, flags, userId); 5924 if (pi != null) { 5925 list.add(pi); 5926 } 5927 } 5928 } 5929 5930 return new ParceledListSlice<PackageInfo>(list); 5931 } 5932 } 5933 5934 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5935 String[] permissions, boolean[] tmp, int flags, int userId) { 5936 int numMatch = 0; 5937 final PermissionsState permissionsState = ps.getPermissionsState(); 5938 for (int i=0; i<permissions.length; i++) { 5939 final String permission = permissions[i]; 5940 if (permissionsState.hasPermission(permission, userId)) { 5941 tmp[i] = true; 5942 numMatch++; 5943 } else { 5944 tmp[i] = false; 5945 } 5946 } 5947 if (numMatch == 0) { 5948 return; 5949 } 5950 PackageInfo pi; 5951 if (ps.pkg != null) { 5952 pi = generatePackageInfo(ps.pkg, flags, userId); 5953 } else { 5954 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5955 } 5956 // The above might return null in cases of uninstalled apps or install-state 5957 // skew across users/profiles. 5958 if (pi != null) { 5959 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5960 if (numMatch == permissions.length) { 5961 pi.requestedPermissions = permissions; 5962 } else { 5963 pi.requestedPermissions = new String[numMatch]; 5964 numMatch = 0; 5965 for (int i=0; i<permissions.length; i++) { 5966 if (tmp[i]) { 5967 pi.requestedPermissions[numMatch] = permissions[i]; 5968 numMatch++; 5969 } 5970 } 5971 } 5972 } 5973 list.add(pi); 5974 } 5975 } 5976 5977 @Override 5978 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5979 String[] permissions, int flags, int userId) { 5980 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5981 flags = updateFlagsForPackage(flags, userId, permissions); 5982 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5983 5984 // writer 5985 synchronized (mPackages) { 5986 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5987 boolean[] tmpBools = new boolean[permissions.length]; 5988 if (listUninstalled) { 5989 for (PackageSetting ps : mSettings.mPackages.values()) { 5990 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5991 } 5992 } else { 5993 for (PackageParser.Package pkg : mPackages.values()) { 5994 PackageSetting ps = (PackageSetting)pkg.mExtras; 5995 if (ps != null) { 5996 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5997 userId); 5998 } 5999 } 6000 } 6001 6002 return new ParceledListSlice<PackageInfo>(list); 6003 } 6004 } 6005 6006 @Override 6007 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6008 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6009 flags = updateFlagsForApplication(flags, userId, null); 6010 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6011 6012 // writer 6013 synchronized (mPackages) { 6014 ArrayList<ApplicationInfo> list; 6015 if (listUninstalled) { 6016 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6017 for (PackageSetting ps : mSettings.mPackages.values()) { 6018 ApplicationInfo ai; 6019 if (ps.pkg != null) { 6020 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6021 ps.readUserState(userId), userId); 6022 } else { 6023 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6024 } 6025 if (ai != null) { 6026 list.add(ai); 6027 } 6028 } 6029 } else { 6030 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6031 for (PackageParser.Package p : mPackages.values()) { 6032 if (p.mExtras != null) { 6033 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6034 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6035 if (ai != null) { 6036 list.add(ai); 6037 } 6038 } 6039 } 6040 } 6041 6042 return new ParceledListSlice<ApplicationInfo>(list); 6043 } 6044 } 6045 6046 @Override 6047 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6048 if (DISABLE_EPHEMERAL_APPS) { 6049 return null; 6050 } 6051 6052 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6053 "getEphemeralApplications"); 6054 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6055 true /* requireFullPermission */, false /* checkShell */, 6056 "getEphemeralApplications"); 6057 synchronized (mPackages) { 6058 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6059 .getEphemeralApplicationsLPw(userId); 6060 if (ephemeralApps != null) { 6061 return new ParceledListSlice<>(ephemeralApps); 6062 } 6063 } 6064 return null; 6065 } 6066 6067 @Override 6068 public boolean isEphemeralApplication(String packageName, int userId) { 6069 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6070 true /* requireFullPermission */, false /* checkShell */, 6071 "isEphemeral"); 6072 if (DISABLE_EPHEMERAL_APPS) { 6073 return false; 6074 } 6075 6076 if (!isCallerSameApp(packageName)) { 6077 return false; 6078 } 6079 synchronized (mPackages) { 6080 PackageParser.Package pkg = mPackages.get(packageName); 6081 if (pkg != null) { 6082 return pkg.applicationInfo.isEphemeralApp(); 6083 } 6084 } 6085 return false; 6086 } 6087 6088 @Override 6089 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6090 if (DISABLE_EPHEMERAL_APPS) { 6091 return null; 6092 } 6093 6094 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6095 true /* requireFullPermission */, false /* checkShell */, 6096 "getCookie"); 6097 if (!isCallerSameApp(packageName)) { 6098 return null; 6099 } 6100 synchronized (mPackages) { 6101 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6102 packageName, userId); 6103 } 6104 } 6105 6106 @Override 6107 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6108 if (DISABLE_EPHEMERAL_APPS) { 6109 return true; 6110 } 6111 6112 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6113 true /* requireFullPermission */, true /* checkShell */, 6114 "setCookie"); 6115 if (!isCallerSameApp(packageName)) { 6116 return false; 6117 } 6118 synchronized (mPackages) { 6119 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6120 packageName, cookie, userId); 6121 } 6122 } 6123 6124 @Override 6125 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6126 if (DISABLE_EPHEMERAL_APPS) { 6127 return null; 6128 } 6129 6130 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6131 "getEphemeralApplicationIcon"); 6132 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6133 true /* requireFullPermission */, false /* checkShell */, 6134 "getEphemeralApplicationIcon"); 6135 synchronized (mPackages) { 6136 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6137 packageName, userId); 6138 } 6139 } 6140 6141 private boolean isCallerSameApp(String packageName) { 6142 PackageParser.Package pkg = mPackages.get(packageName); 6143 return pkg != null 6144 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6145 } 6146 6147 @Override 6148 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6149 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6150 } 6151 6152 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6153 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6154 6155 // reader 6156 synchronized (mPackages) { 6157 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6158 final int userId = UserHandle.getCallingUserId(); 6159 while (i.hasNext()) { 6160 final PackageParser.Package p = i.next(); 6161 if (p.applicationInfo == null) continue; 6162 6163 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6164 && !p.applicationInfo.isDirectBootAware(); 6165 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6166 && p.applicationInfo.isDirectBootAware(); 6167 6168 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6169 && (!mSafeMode || isSystemApp(p)) 6170 && (matchesUnaware || matchesAware)) { 6171 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6172 if (ps != null) { 6173 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6174 ps.readUserState(userId), userId); 6175 if (ai != null) { 6176 finalList.add(ai); 6177 } 6178 } 6179 } 6180 } 6181 } 6182 6183 return finalList; 6184 } 6185 6186 @Override 6187 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6188 if (!sUserManager.exists(userId)) return null; 6189 flags = updateFlagsForComponent(flags, userId, name); 6190 // reader 6191 synchronized (mPackages) { 6192 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6193 PackageSetting ps = provider != null 6194 ? mSettings.mPackages.get(provider.owner.packageName) 6195 : null; 6196 return ps != null 6197 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6198 ? PackageParser.generateProviderInfo(provider, flags, 6199 ps.readUserState(userId), userId) 6200 : null; 6201 } 6202 } 6203 6204 /** 6205 * @deprecated 6206 */ 6207 @Deprecated 6208 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6209 // reader 6210 synchronized (mPackages) { 6211 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6212 .entrySet().iterator(); 6213 final int userId = UserHandle.getCallingUserId(); 6214 while (i.hasNext()) { 6215 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6216 PackageParser.Provider p = entry.getValue(); 6217 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6218 6219 if (ps != null && p.syncable 6220 && (!mSafeMode || (p.info.applicationInfo.flags 6221 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6222 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6223 ps.readUserState(userId), userId); 6224 if (info != null) { 6225 outNames.add(entry.getKey()); 6226 outInfo.add(info); 6227 } 6228 } 6229 } 6230 } 6231 } 6232 6233 @Override 6234 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6235 int uid, int flags) { 6236 final int userId = processName != null ? UserHandle.getUserId(uid) 6237 : UserHandle.getCallingUserId(); 6238 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6239 flags = updateFlagsForComponent(flags, userId, processName); 6240 6241 ArrayList<ProviderInfo> finalList = null; 6242 // reader 6243 synchronized (mPackages) { 6244 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6245 while (i.hasNext()) { 6246 final PackageParser.Provider p = i.next(); 6247 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6248 if (ps != null && p.info.authority != null 6249 && (processName == null 6250 || (p.info.processName.equals(processName) 6251 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6252 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6253 if (finalList == null) { 6254 finalList = new ArrayList<ProviderInfo>(3); 6255 } 6256 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6257 ps.readUserState(userId), userId); 6258 if (info != null) { 6259 finalList.add(info); 6260 } 6261 } 6262 } 6263 } 6264 6265 if (finalList != null) { 6266 Collections.sort(finalList, mProviderInitOrderSorter); 6267 return new ParceledListSlice<ProviderInfo>(finalList); 6268 } 6269 6270 return ParceledListSlice.emptyList(); 6271 } 6272 6273 @Override 6274 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6275 // reader 6276 synchronized (mPackages) { 6277 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6278 return PackageParser.generateInstrumentationInfo(i, flags); 6279 } 6280 } 6281 6282 @Override 6283 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6284 String targetPackage, int flags) { 6285 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6286 } 6287 6288 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6289 int flags) { 6290 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6291 6292 // reader 6293 synchronized (mPackages) { 6294 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6295 while (i.hasNext()) { 6296 final PackageParser.Instrumentation p = i.next(); 6297 if (targetPackage == null 6298 || targetPackage.equals(p.info.targetPackage)) { 6299 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6300 flags); 6301 if (ii != null) { 6302 finalList.add(ii); 6303 } 6304 } 6305 } 6306 } 6307 6308 return finalList; 6309 } 6310 6311 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6312 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6313 if (overlays == null) { 6314 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6315 return; 6316 } 6317 for (PackageParser.Package opkg : overlays.values()) { 6318 // Not much to do if idmap fails: we already logged the error 6319 // and we certainly don't want to abort installation of pkg simply 6320 // because an overlay didn't fit properly. For these reasons, 6321 // ignore the return value of createIdmapForPackagePairLI. 6322 createIdmapForPackagePairLI(pkg, opkg); 6323 } 6324 } 6325 6326 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6327 PackageParser.Package opkg) { 6328 if (!opkg.mTrustedOverlay) { 6329 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6330 opkg.baseCodePath + ": overlay not trusted"); 6331 return false; 6332 } 6333 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6334 if (overlaySet == null) { 6335 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6336 opkg.baseCodePath + " but target package has no known overlays"); 6337 return false; 6338 } 6339 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6340 // TODO: generate idmap for split APKs 6341 try { 6342 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6343 } catch (InstallerException e) { 6344 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6345 + opkg.baseCodePath); 6346 return false; 6347 } 6348 PackageParser.Package[] overlayArray = 6349 overlaySet.values().toArray(new PackageParser.Package[0]); 6350 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6351 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6352 return p1.mOverlayPriority - p2.mOverlayPriority; 6353 } 6354 }; 6355 Arrays.sort(overlayArray, cmp); 6356 6357 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6358 int i = 0; 6359 for (PackageParser.Package p : overlayArray) { 6360 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6361 } 6362 return true; 6363 } 6364 6365 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6366 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6367 try { 6368 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6369 } finally { 6370 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6371 } 6372 } 6373 6374 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6375 final File[] files = dir.listFiles(); 6376 if (ArrayUtils.isEmpty(files)) { 6377 Log.d(TAG, "No files in app dir " + dir); 6378 return; 6379 } 6380 6381 if (DEBUG_PACKAGE_SCANNING) { 6382 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6383 + " flags=0x" + Integer.toHexString(parseFlags)); 6384 } 6385 6386 for (File file : files) { 6387 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6388 && !PackageInstallerService.isStageName(file.getName()); 6389 if (!isPackage) { 6390 // Ignore entries which are not packages 6391 continue; 6392 } 6393 try { 6394 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6395 scanFlags, currentTime, null); 6396 } catch (PackageManagerException e) { 6397 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6398 6399 // Delete invalid userdata apps 6400 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6401 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6402 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6403 removeCodePathLI(file); 6404 } 6405 } 6406 } 6407 } 6408 6409 private static File getSettingsProblemFile() { 6410 File dataDir = Environment.getDataDirectory(); 6411 File systemDir = new File(dataDir, "system"); 6412 File fname = new File(systemDir, "uiderrors.txt"); 6413 return fname; 6414 } 6415 6416 static void reportSettingsProblem(int priority, String msg) { 6417 logCriticalInfo(priority, msg); 6418 } 6419 6420 static void logCriticalInfo(int priority, String msg) { 6421 Slog.println(priority, TAG, msg); 6422 EventLogTags.writePmCriticalInfo(msg); 6423 try { 6424 File fname = getSettingsProblemFile(); 6425 FileOutputStream out = new FileOutputStream(fname, true); 6426 PrintWriter pw = new FastPrintWriter(out); 6427 SimpleDateFormat formatter = new SimpleDateFormat(); 6428 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6429 pw.println(dateString + ": " + msg); 6430 pw.close(); 6431 FileUtils.setPermissions( 6432 fname.toString(), 6433 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6434 -1, -1); 6435 } catch (java.io.IOException e) { 6436 } 6437 } 6438 6439 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6440 int parseFlags) throws PackageManagerException { 6441 if (ps != null 6442 && ps.codePath.equals(srcFile) 6443 && ps.timeStamp == srcFile.lastModified() 6444 && !isCompatSignatureUpdateNeeded(pkg) 6445 && !isRecoverSignatureUpdateNeeded(pkg)) { 6446 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6447 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6448 ArraySet<PublicKey> signingKs; 6449 synchronized (mPackages) { 6450 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6451 } 6452 if (ps.signatures.mSignatures != null 6453 && ps.signatures.mSignatures.length != 0 6454 && signingKs != null) { 6455 // Optimization: reuse the existing cached certificates 6456 // if the package appears to be unchanged. 6457 pkg.mSignatures = ps.signatures.mSignatures; 6458 pkg.mSigningKeys = signingKs; 6459 return; 6460 } 6461 6462 Slog.w(TAG, "PackageSetting for " + ps.name 6463 + " is missing signatures. Collecting certs again to recover them."); 6464 } else { 6465 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6466 } 6467 6468 try { 6469 PackageParser.collectCertificates(pkg, parseFlags); 6470 } catch (PackageParserException e) { 6471 throw PackageManagerException.from(e); 6472 } 6473 } 6474 6475 /** 6476 * Traces a package scan. 6477 * @see #scanPackageLI(File, int, int, long, UserHandle) 6478 */ 6479 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6480 long currentTime, UserHandle user) throws PackageManagerException { 6481 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6482 try { 6483 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6484 } finally { 6485 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6486 } 6487 } 6488 6489 /** 6490 * Scans a package and returns the newly parsed package. 6491 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6492 */ 6493 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6494 long currentTime, UserHandle user) throws PackageManagerException { 6495 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6496 parseFlags |= mDefParseFlags; 6497 PackageParser pp = new PackageParser(); 6498 pp.setSeparateProcesses(mSeparateProcesses); 6499 pp.setOnlyCoreApps(mOnlyCore); 6500 pp.setDisplayMetrics(mMetrics); 6501 6502 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6503 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6504 } 6505 6506 final PackageParser.Package pkg; 6507 try { 6508 pkg = pp.parsePackage(scanFile, parseFlags); 6509 } catch (PackageParserException e) { 6510 throw PackageManagerException.from(e); 6511 } 6512 6513 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6514 } 6515 6516 /** 6517 * Scans a package and returns the newly parsed package. 6518 * @throws PackageManagerException on a parse error. 6519 */ 6520 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6521 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6522 throws PackageManagerException { 6523 // If the package has children and this is the first dive in the function 6524 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6525 // packages (parent and children) would be successfully scanned before the 6526 // actual scan since scanning mutates internal state and we want to atomically 6527 // install the package and its children. 6528 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6529 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6530 scanFlags |= SCAN_CHECK_ONLY; 6531 } 6532 } else { 6533 scanFlags &= ~SCAN_CHECK_ONLY; 6534 } 6535 6536 // Scan the parent 6537 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags, 6538 scanFlags, currentTime, user); 6539 6540 // Scan the children 6541 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6542 for (int i = 0; i < childCount; i++) { 6543 PackageParser.Package childPackage = pkg.childPackages.get(i); 6544 scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags, 6545 currentTime, user); 6546 } 6547 6548 6549 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6550 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6551 } 6552 6553 return scannedPkg; 6554 } 6555 6556 /** 6557 * Scans a package and returns the newly parsed package. 6558 * @throws PackageManagerException on a parse error. 6559 */ 6560 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6561 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6562 throws PackageManagerException { 6563 PackageSetting ps = null; 6564 PackageSetting updatedPkg; 6565 // reader 6566 synchronized (mPackages) { 6567 // Look to see if we already know about this package. 6568 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6569 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6570 // This package has been renamed to its original name. Let's 6571 // use that. 6572 ps = mSettings.peekPackageLPr(oldName); 6573 } 6574 // If there was no original package, see one for the real package name. 6575 if (ps == null) { 6576 ps = mSettings.peekPackageLPr(pkg.packageName); 6577 } 6578 // Check to see if this package could be hiding/updating a system 6579 // package. Must look for it either under the original or real 6580 // package name depending on our state. 6581 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6582 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6583 6584 // If this is a package we don't know about on the system partition, we 6585 // may need to remove disabled child packages on the system partition 6586 // or may need to not add child packages if the parent apk is updated 6587 // on the data partition and no longer defines this child package. 6588 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6589 // If this is a parent package for an updated system app and this system 6590 // app got an OTA update which no longer defines some of the child packages 6591 // we have to prune them from the disabled system packages. 6592 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6593 if (disabledPs != null) { 6594 final int scannedChildCount = (pkg.childPackages != null) 6595 ? pkg.childPackages.size() : 0; 6596 final int disabledChildCount = disabledPs.childPackageNames != null 6597 ? disabledPs.childPackageNames.size() : 0; 6598 for (int i = 0; i < disabledChildCount; i++) { 6599 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6600 boolean disabledPackageAvailable = false; 6601 for (int j = 0; j < scannedChildCount; j++) { 6602 PackageParser.Package childPkg = pkg.childPackages.get(j); 6603 if (childPkg.packageName.equals(disabledChildPackageName)) { 6604 disabledPackageAvailable = true; 6605 break; 6606 } 6607 } 6608 if (!disabledPackageAvailable) { 6609 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6610 } 6611 } 6612 } 6613 } 6614 } 6615 6616 boolean updatedPkgBetter = false; 6617 // First check if this is a system package that may involve an update 6618 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6619 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6620 // it needs to drop FLAG_PRIVILEGED. 6621 if (locationIsPrivileged(scanFile)) { 6622 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6623 } else { 6624 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6625 } 6626 6627 if (ps != null && !ps.codePath.equals(scanFile)) { 6628 // The path has changed from what was last scanned... check the 6629 // version of the new path against what we have stored to determine 6630 // what to do. 6631 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6632 if (pkg.mVersionCode <= ps.versionCode) { 6633 // The system package has been updated and the code path does not match 6634 // Ignore entry. Skip it. 6635 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6636 + " ignored: updated version " + ps.versionCode 6637 + " better than this " + pkg.mVersionCode); 6638 if (!updatedPkg.codePath.equals(scanFile)) { 6639 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6640 + ps.name + " changing from " + updatedPkg.codePathString 6641 + " to " + scanFile); 6642 updatedPkg.codePath = scanFile; 6643 updatedPkg.codePathString = scanFile.toString(); 6644 updatedPkg.resourcePath = scanFile; 6645 updatedPkg.resourcePathString = scanFile.toString(); 6646 } 6647 updatedPkg.pkg = pkg; 6648 updatedPkg.versionCode = pkg.mVersionCode; 6649 6650 // Update the disabled system child packages to point to the package too. 6651 final int childCount = updatedPkg.childPackageNames != null 6652 ? updatedPkg.childPackageNames.size() : 0; 6653 for (int i = 0; i < childCount; i++) { 6654 String childPackageName = updatedPkg.childPackageNames.get(i); 6655 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6656 childPackageName); 6657 if (updatedChildPkg != null) { 6658 updatedChildPkg.pkg = pkg; 6659 updatedChildPkg.versionCode = pkg.mVersionCode; 6660 } 6661 } 6662 6663 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6664 + scanFile + " ignored: updated version " + ps.versionCode 6665 + " better than this " + pkg.mVersionCode); 6666 } else { 6667 // The current app on the system partition is better than 6668 // what we have updated to on the data partition; switch 6669 // back to the system partition version. 6670 // At this point, its safely assumed that package installation for 6671 // apps in system partition will go through. If not there won't be a working 6672 // version of the app 6673 // writer 6674 synchronized (mPackages) { 6675 // Just remove the loaded entries from package lists. 6676 mPackages.remove(ps.name); 6677 } 6678 6679 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6680 + " reverting from " + ps.codePathString 6681 + ": new version " + pkg.mVersionCode 6682 + " better than installed " + ps.versionCode); 6683 6684 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6685 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6686 synchronized (mInstallLock) { 6687 args.cleanUpResourcesLI(); 6688 } 6689 synchronized (mPackages) { 6690 mSettings.enableSystemPackageLPw(ps.name); 6691 } 6692 updatedPkgBetter = true; 6693 } 6694 } 6695 } 6696 6697 if (updatedPkg != null) { 6698 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6699 // initially 6700 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6701 6702 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6703 // flag set initially 6704 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6705 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6706 } 6707 } 6708 6709 // Verify certificates against what was last scanned 6710 collectCertificatesLI(ps, pkg, scanFile, parseFlags); 6711 6712 /* 6713 * A new system app appeared, but we already had a non-system one of the 6714 * same name installed earlier. 6715 */ 6716 boolean shouldHideSystemApp = false; 6717 if (updatedPkg == null && ps != null 6718 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6719 /* 6720 * Check to make sure the signatures match first. If they don't, 6721 * wipe the installed application and its data. 6722 */ 6723 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6724 != PackageManager.SIGNATURE_MATCH) { 6725 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6726 + " signatures don't match existing userdata copy; removing"); 6727 deletePackageLI(pkg.packageName, null, true, null, 0, null, false, null); 6728 ps = null; 6729 } else { 6730 /* 6731 * If the newly-added system app is an older version than the 6732 * already installed version, hide it. It will be scanned later 6733 * and re-added like an update. 6734 */ 6735 if (pkg.mVersionCode <= ps.versionCode) { 6736 shouldHideSystemApp = true; 6737 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6738 + " but new version " + pkg.mVersionCode + " better than installed " 6739 + ps.versionCode + "; hiding system"); 6740 } else { 6741 /* 6742 * The newly found system app is a newer version that the 6743 * one previously installed. Simply remove the 6744 * already-installed application and replace it with our own 6745 * while keeping the application data. 6746 */ 6747 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6748 + " reverting from " + ps.codePathString + ": new version " 6749 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6750 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6751 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6752 synchronized (mInstallLock) { 6753 args.cleanUpResourcesLI(); 6754 } 6755 } 6756 } 6757 } 6758 6759 // The apk is forward locked (not public) if its code and resources 6760 // are kept in different files. (except for app in either system or 6761 // vendor path). 6762 // TODO grab this value from PackageSettings 6763 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6764 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6765 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6766 } 6767 } 6768 6769 // TODO: extend to support forward-locked splits 6770 String resourcePath = null; 6771 String baseResourcePath = null; 6772 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6773 if (ps != null && ps.resourcePathString != null) { 6774 resourcePath = ps.resourcePathString; 6775 baseResourcePath = ps.resourcePathString; 6776 } else { 6777 // Should not happen at all. Just log an error. 6778 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6779 } 6780 } else { 6781 resourcePath = pkg.codePath; 6782 baseResourcePath = pkg.baseCodePath; 6783 } 6784 6785 // Set application objects path explicitly. 6786 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 6787 pkg.setApplicationInfoCodePath(pkg.codePath); 6788 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 6789 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 6790 pkg.setApplicationInfoResourcePath(resourcePath); 6791 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 6792 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 6793 6794 // Note that we invoke the following method only if we are about to unpack an application 6795 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6796 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6797 6798 /* 6799 * If the system app should be overridden by a previously installed 6800 * data, hide the system app now and let the /data/app scan pick it up 6801 * again. 6802 */ 6803 if (shouldHideSystemApp) { 6804 synchronized (mPackages) { 6805 mSettings.disableSystemPackageLPw(pkg.packageName, true); 6806 } 6807 } 6808 6809 return scannedPkg; 6810 } 6811 6812 private static String fixProcessName(String defProcessName, 6813 String processName, int uid) { 6814 if (processName == null) { 6815 return defProcessName; 6816 } 6817 return processName; 6818 } 6819 6820 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6821 throws PackageManagerException { 6822 if (pkgSetting.signatures.mSignatures != null) { 6823 // Already existing package. Make sure signatures match 6824 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6825 == PackageManager.SIGNATURE_MATCH; 6826 if (!match) { 6827 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6828 == PackageManager.SIGNATURE_MATCH; 6829 } 6830 if (!match) { 6831 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6832 == PackageManager.SIGNATURE_MATCH; 6833 } 6834 if (!match) { 6835 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6836 + pkg.packageName + " signatures do not match the " 6837 + "previously installed version; ignoring!"); 6838 } 6839 } 6840 6841 // Check for shared user signatures 6842 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6843 // Already existing package. Make sure signatures match 6844 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6845 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6846 if (!match) { 6847 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6848 == PackageManager.SIGNATURE_MATCH; 6849 } 6850 if (!match) { 6851 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6852 == PackageManager.SIGNATURE_MATCH; 6853 } 6854 if (!match) { 6855 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6856 "Package " + pkg.packageName 6857 + " has no signatures that match those in shared user " 6858 + pkgSetting.sharedUser.name + "; ignoring!"); 6859 } 6860 } 6861 } 6862 6863 /** 6864 * Enforces that only the system UID or root's UID can call a method exposed 6865 * via Binder. 6866 * 6867 * @param message used as message if SecurityException is thrown 6868 * @throws SecurityException if the caller is not system or root 6869 */ 6870 private static final void enforceSystemOrRoot(String message) { 6871 final int uid = Binder.getCallingUid(); 6872 if (uid != Process.SYSTEM_UID && uid != 0) { 6873 throw new SecurityException(message); 6874 } 6875 } 6876 6877 @Override 6878 public void performFstrimIfNeeded() { 6879 enforceSystemOrRoot("Only the system can request fstrim"); 6880 6881 // Before everything else, see whether we need to fstrim. 6882 try { 6883 IMountService ms = PackageHelper.getMountService(); 6884 if (ms != null) { 6885 final boolean isUpgrade = isUpgrade(); 6886 boolean doTrim = isUpgrade; 6887 if (doTrim) { 6888 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6889 } else { 6890 final long interval = android.provider.Settings.Global.getLong( 6891 mContext.getContentResolver(), 6892 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6893 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6894 if (interval > 0) { 6895 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6896 if (timeSinceLast > interval) { 6897 doTrim = true; 6898 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6899 + "; running immediately"); 6900 } 6901 } 6902 } 6903 if (doTrim) { 6904 if (!isFirstBoot()) { 6905 try { 6906 ActivityManagerNative.getDefault().showBootMessage( 6907 mContext.getResources().getString( 6908 R.string.android_upgrading_fstrim), true); 6909 } catch (RemoteException e) { 6910 } 6911 } 6912 ms.runMaintenance(); 6913 } 6914 } else { 6915 Slog.e(TAG, "Mount service unavailable!"); 6916 } 6917 } catch (RemoteException e) { 6918 // Can't happen; MountService is local 6919 } 6920 } 6921 6922 @Override 6923 public void extractPackagesIfNeeded() { 6924 enforceSystemOrRoot("Only the system can request package extraction"); 6925 6926 // We need to re-extract after an OTA. 6927 boolean causeUpgrade = isUpgrade(); 6928 6929 // First boot or factory reset. 6930 // Note: we also handle devices that are upgrading to N right now as if it is their 6931 // first boot, as they do not have profile data. 6932 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 6933 6934 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 6935 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 6936 6937 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 6938 return; 6939 } 6940 6941 List<PackageParser.Package> pkgs; 6942 synchronized (mPackages) { 6943 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 6944 } 6945 6946 int curr = 0; 6947 int total = pkgs.size(); 6948 for (PackageParser.Package pkg : pkgs) { 6949 curr++; 6950 6951 if (DEBUG_DEXOPT) { 6952 Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName); 6953 } 6954 6955 if (!isFirstBoot()) { 6956 try { 6957 ActivityManagerNative.getDefault().showBootMessage( 6958 mContext.getResources().getString(R.string.android_upgrading_apk, 6959 curr, total), true); 6960 } catch (RemoteException e) { 6961 } 6962 } 6963 6964 if (PackageDexOptimizer.canOptimizePackage(pkg)) { 6965 // If the cache was pruned, any compiled odex files will likely be out of date 6966 // and would have to be patched (would be SELF_PATCHOAT, which is deprecated). 6967 // Instead, force the extraction in this case. 6968 performDexOpt(pkg.packageName, null /* instructionSet */, 6969 false /* checkProfiles */, 6970 causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT, 6971 causePrunedCache); 6972 } 6973 } 6974 } 6975 6976 @Override 6977 public void notifyPackageUse(String packageName) { 6978 synchronized (mPackages) { 6979 PackageParser.Package p = mPackages.get(packageName); 6980 if (p == null) { 6981 return; 6982 } 6983 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6984 } 6985 } 6986 6987 // TODO: this is not used nor needed. Delete it. 6988 @Override 6989 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6990 return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */, 6991 getFullCompilerFilter(), false /* force */); 6992 } 6993 6994 @Override 6995 public boolean performDexOpt(String packageName, String instructionSet, 6996 boolean checkProfiles, int compileReason, boolean force) { 6997 return performDexOptTraced(packageName, instructionSet, checkProfiles, 6998 getCompilerFilterForReason(compileReason), force); 6999 } 7000 7001 @Override 7002 public boolean performDexOptMode(String packageName, String instructionSet, 7003 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7004 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7005 targetCompilerFilter, force); 7006 } 7007 7008 private boolean performDexOptTraced(String packageName, String instructionSet, 7009 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7010 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7011 try { 7012 return performDexOptInternal(packageName, instructionSet, checkProfiles, 7013 targetCompilerFilter, force); 7014 } finally { 7015 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7016 } 7017 } 7018 7019 private boolean performDexOptInternal(String packageName, String instructionSet, 7020 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7021 PackageParser.Package p; 7022 final String targetInstructionSet; 7023 synchronized (mPackages) { 7024 p = mPackages.get(packageName); 7025 if (p == null) { 7026 return false; 7027 } 7028 mPackageUsage.write(false); 7029 7030 targetInstructionSet = instructionSet != null ? instructionSet : 7031 getPrimaryInstructionSet(p.applicationInfo); 7032 } 7033 long callingId = Binder.clearCallingIdentity(); 7034 try { 7035 synchronized (mInstallLock) { 7036 final String[] instructionSets = new String[] { targetInstructionSet }; 7037 int result = performDexOptInternalWithDependenciesLI(p, instructionSets, 7038 checkProfiles, targetCompilerFilter, force); 7039 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 7040 } 7041 } finally { 7042 Binder.restoreCallingIdentity(callingId); 7043 } 7044 } 7045 7046 public ArraySet<String> getOptimizablePackages() { 7047 ArraySet<String> pkgs = new ArraySet<String>(); 7048 synchronized (mPackages) { 7049 for (PackageParser.Package p : mPackages.values()) { 7050 if (PackageDexOptimizer.canOptimizePackage(p)) { 7051 pkgs.add(p.packageName); 7052 } 7053 } 7054 } 7055 return pkgs; 7056 } 7057 7058 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7059 String instructionSets[], boolean checkProfiles, String targetCompilerFilter, 7060 boolean force) { 7061 // Select the dex optimizer based on the force parameter. 7062 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7063 // allocate an object here. 7064 PackageDexOptimizer pdo = force 7065 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7066 : mPackageDexOptimizer; 7067 7068 // Optimize all dependencies first. Note: we ignore the return value and march on 7069 // on errors. 7070 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7071 if (!deps.isEmpty()) { 7072 for (PackageParser.Package depPackage : deps) { 7073 // TODO: Analyze and investigate if we (should) profile libraries. 7074 // Currently this will do a full compilation of the library by default. 7075 pdo.performDexOpt(depPackage, instructionSets, false /* checkProfiles */, 7076 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7077 } 7078 } 7079 7080 return pdo.performDexOpt(p, instructionSets, checkProfiles, targetCompilerFilter); 7081 } 7082 7083 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7084 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7085 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7086 Set<String> collectedNames = new HashSet<>(); 7087 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7088 7089 retValue.remove(p); 7090 7091 return retValue; 7092 } else { 7093 return Collections.emptyList(); 7094 } 7095 } 7096 7097 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7098 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7099 if (!collectedNames.contains(p.packageName)) { 7100 collectedNames.add(p.packageName); 7101 collected.add(p); 7102 7103 if (p.usesLibraries != null) { 7104 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7105 } 7106 if (p.usesOptionalLibraries != null) { 7107 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7108 collectedNames); 7109 } 7110 } 7111 } 7112 7113 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7114 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7115 for (String libName : libs) { 7116 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7117 if (libPkg != null) { 7118 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7119 } 7120 } 7121 } 7122 7123 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7124 synchronized (mPackages) { 7125 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7126 if (lib != null && lib.apk != null) { 7127 return mPackages.get(lib.apk); 7128 } 7129 } 7130 return null; 7131 } 7132 7133 public void shutdown() { 7134 mPackageUsage.write(true); 7135 } 7136 7137 @Override 7138 public void forceDexOpt(String packageName) { 7139 enforceSystemOrRoot("forceDexOpt"); 7140 7141 PackageParser.Package pkg; 7142 synchronized (mPackages) { 7143 pkg = mPackages.get(packageName); 7144 if (pkg == null) { 7145 throw new IllegalArgumentException("Unknown package: " + packageName); 7146 } 7147 } 7148 7149 synchronized (mInstallLock) { 7150 final String[] instructionSets = new String[] { 7151 getPrimaryInstructionSet(pkg.applicationInfo) }; 7152 7153 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7154 7155 // Whoever is calling forceDexOpt wants a fully compiled package. 7156 // Don't use profiles since that may cause compilation to be skipped. 7157 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7158 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7159 true /* force */); 7160 7161 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7162 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7163 throw new IllegalStateException("Failed to dexopt: " + res); 7164 } 7165 } 7166 } 7167 7168 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7169 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7170 Slog.w(TAG, "Unable to update from " + oldPkg.name 7171 + " to " + newPkg.packageName 7172 + ": old package not in system partition"); 7173 return false; 7174 } else if (mPackages.get(oldPkg.name) != null) { 7175 Slog.w(TAG, "Unable to update from " + oldPkg.name 7176 + " to " + newPkg.packageName 7177 + ": old package still exists"); 7178 return false; 7179 } 7180 return true; 7181 } 7182 7183 private boolean removeDataDirsLI(String volumeUuid, String packageName) { 7184 // TODO: triage flags as part of 26466827 7185 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7186 7187 boolean res = true; 7188 final int[] users = sUserManager.getUserIds(); 7189 for (int user : users) { 7190 try { 7191 mInstaller.destroyAppData(volumeUuid, packageName, user, flags); 7192 } catch (InstallerException e) { 7193 Slog.w(TAG, "Failed to delete data directory", e); 7194 res = false; 7195 } 7196 } 7197 return res; 7198 } 7199 7200 void removeCodePathLI(File codePath) { 7201 if (codePath.isDirectory()) { 7202 try { 7203 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7204 } catch (InstallerException e) { 7205 Slog.w(TAG, "Failed to remove code path", e); 7206 } 7207 } else { 7208 codePath.delete(); 7209 } 7210 } 7211 7212 void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) { 7213 try { 7214 mInstaller.destroyAppData(volumeUuid, packageName, userId, flags); 7215 } catch (InstallerException e) { 7216 Slog.w(TAG, "Failed to destroy app data", e); 7217 } 7218 } 7219 7220 void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags, 7221 int appId, String seinfo) { 7222 try { 7223 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo); 7224 } catch (InstallerException e) { 7225 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 7226 } 7227 } 7228 7229 private void deleteProfilesLI(String packageName, boolean destroy) { 7230 final PackageParser.Package pkg; 7231 synchronized (mPackages) { 7232 pkg = mPackages.get(packageName); 7233 } 7234 if (pkg == null) { 7235 Slog.w(TAG, "Failed to delete profiles. No package: " + packageName); 7236 return; 7237 } 7238 deleteProfilesLI(pkg, destroy); 7239 } 7240 7241 private void deleteProfilesLI(PackageParser.Package pkg, boolean destroy) { 7242 try { 7243 if (destroy) { 7244 mInstaller.clearAppProfiles(pkg.packageName); 7245 } else { 7246 mInstaller.destroyAppProfiles(pkg.packageName); 7247 } 7248 } catch (InstallerException ex) { 7249 Log.e(TAG, "Could not delete profiles for package " + pkg.packageName); 7250 } 7251 } 7252 7253 private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 7254 final PackageParser.Package pkg; 7255 synchronized (mPackages) { 7256 pkg = mPackages.get(packageName); 7257 } 7258 if (pkg == null) { 7259 Slog.w(TAG, "Failed to delete code cache directory. No package: " + packageName); 7260 return; 7261 } 7262 deleteCodeCacheDirsLI(pkg); 7263 } 7264 7265 private void deleteCodeCacheDirsLI(PackageParser.Package pkg) { 7266 // TODO: triage flags as part of 26466827 7267 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7268 7269 int[] users = sUserManager.getUserIds(); 7270 int res = 0; 7271 for (int user : users) { 7272 // Remove the parent code cache 7273 try { 7274 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, user, 7275 flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7276 } catch (InstallerException e) { 7277 Slog.w(TAG, "Failed to delete code cache directory", e); 7278 } 7279 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7280 for (int i = 0; i < childCount; i++) { 7281 PackageParser.Package childPkg = pkg.childPackages.get(i); 7282 // Remove the child code cache 7283 try { 7284 mInstaller.clearAppData(childPkg.volumeUuid, childPkg.packageName, 7285 user, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7286 } catch (InstallerException e) { 7287 Slog.w(TAG, "Failed to delete code cache directory", e); 7288 } 7289 } 7290 } 7291 } 7292 7293 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7294 long lastUpdateTime) { 7295 // Set parent install/update time 7296 PackageSetting ps = (PackageSetting) pkg.mExtras; 7297 if (ps != null) { 7298 ps.firstInstallTime = firstInstallTime; 7299 ps.lastUpdateTime = lastUpdateTime; 7300 } 7301 // Set children install/update time 7302 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7303 for (int i = 0; i < childCount; i++) { 7304 PackageParser.Package childPkg = pkg.childPackages.get(i); 7305 ps = (PackageSetting) childPkg.mExtras; 7306 if (ps != null) { 7307 ps.firstInstallTime = firstInstallTime; 7308 ps.lastUpdateTime = lastUpdateTime; 7309 } 7310 } 7311 } 7312 7313 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7314 PackageParser.Package changingLib) { 7315 if (file.path != null) { 7316 usesLibraryFiles.add(file.path); 7317 return; 7318 } 7319 PackageParser.Package p = mPackages.get(file.apk); 7320 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7321 // If we are doing this while in the middle of updating a library apk, 7322 // then we need to make sure to use that new apk for determining the 7323 // dependencies here. (We haven't yet finished committing the new apk 7324 // to the package manager state.) 7325 if (p == null || p.packageName.equals(changingLib.packageName)) { 7326 p = changingLib; 7327 } 7328 } 7329 if (p != null) { 7330 usesLibraryFiles.addAll(p.getAllCodePaths()); 7331 } 7332 } 7333 7334 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7335 PackageParser.Package changingLib) throws PackageManagerException { 7336 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7337 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7338 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7339 for (int i=0; i<N; i++) { 7340 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7341 if (file == null) { 7342 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7343 "Package " + pkg.packageName + " requires unavailable shared library " 7344 + pkg.usesLibraries.get(i) + "; failing!"); 7345 } 7346 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7347 } 7348 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7349 for (int i=0; i<N; i++) { 7350 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7351 if (file == null) { 7352 Slog.w(TAG, "Package " + pkg.packageName 7353 + " desires unavailable shared library " 7354 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7355 } else { 7356 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7357 } 7358 } 7359 N = usesLibraryFiles.size(); 7360 if (N > 0) { 7361 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7362 } else { 7363 pkg.usesLibraryFiles = null; 7364 } 7365 } 7366 } 7367 7368 private static boolean hasString(List<String> list, List<String> which) { 7369 if (list == null) { 7370 return false; 7371 } 7372 for (int i=list.size()-1; i>=0; i--) { 7373 for (int j=which.size()-1; j>=0; j--) { 7374 if (which.get(j).equals(list.get(i))) { 7375 return true; 7376 } 7377 } 7378 } 7379 return false; 7380 } 7381 7382 private void updateAllSharedLibrariesLPw() { 7383 for (PackageParser.Package pkg : mPackages.values()) { 7384 try { 7385 updateSharedLibrariesLPw(pkg, null); 7386 } catch (PackageManagerException e) { 7387 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7388 } 7389 } 7390 } 7391 7392 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7393 PackageParser.Package changingPkg) { 7394 ArrayList<PackageParser.Package> res = null; 7395 for (PackageParser.Package pkg : mPackages.values()) { 7396 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7397 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7398 if (res == null) { 7399 res = new ArrayList<PackageParser.Package>(); 7400 } 7401 res.add(pkg); 7402 try { 7403 updateSharedLibrariesLPw(pkg, changingPkg); 7404 } catch (PackageManagerException e) { 7405 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7406 } 7407 } 7408 } 7409 return res; 7410 } 7411 7412 /** 7413 * Derive the value of the {@code cpuAbiOverride} based on the provided 7414 * value and an optional stored value from the package settings. 7415 */ 7416 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7417 String cpuAbiOverride = null; 7418 7419 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7420 cpuAbiOverride = null; 7421 } else if (abiOverride != null) { 7422 cpuAbiOverride = abiOverride; 7423 } else if (settings != null) { 7424 cpuAbiOverride = settings.cpuAbiOverrideString; 7425 } 7426 7427 return cpuAbiOverride; 7428 } 7429 7430 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 7431 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7432 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7433 // If the package has children and this is the first dive in the function 7434 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7435 // whether all packages (parent and children) would be successfully scanned 7436 // before the actual scan since scanning mutates internal state and we want 7437 // to atomically install the package and its children. 7438 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7439 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7440 scanFlags |= SCAN_CHECK_ONLY; 7441 } 7442 } else { 7443 scanFlags &= ~SCAN_CHECK_ONLY; 7444 } 7445 7446 final PackageParser.Package scannedPkg; 7447 try { 7448 // Scan the parent 7449 scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 7450 // Scan the children 7451 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7452 for (int i = 0; i < childCount; i++) { 7453 PackageParser.Package childPkg = pkg.childPackages.get(i); 7454 scanPackageLI(childPkg, parseFlags, 7455 scanFlags, currentTime, user); 7456 } 7457 } finally { 7458 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7459 } 7460 7461 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7462 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 7463 } 7464 7465 return scannedPkg; 7466 } 7467 7468 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 7469 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7470 boolean success = false; 7471 try { 7472 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 7473 currentTime, user); 7474 success = true; 7475 return res; 7476 } finally { 7477 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7478 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 7479 } 7480 } 7481 } 7482 7483 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 7484 int scanFlags, long currentTime, UserHandle user) 7485 throws PackageManagerException { 7486 final File scanFile = new File(pkg.codePath); 7487 if (pkg.applicationInfo.getCodePath() == null || 7488 pkg.applicationInfo.getResourcePath() == null) { 7489 // Bail out. The resource and code paths haven't been set. 7490 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7491 "Code and resource paths haven't been set correctly"); 7492 } 7493 7494 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7495 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7496 } else { 7497 // Only allow system apps to be flagged as core apps. 7498 pkg.coreApp = false; 7499 } 7500 7501 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7502 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7503 } 7504 7505 if (mCustomResolverComponentName != null && 7506 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7507 setUpCustomResolverActivity(pkg); 7508 } 7509 7510 if (pkg.packageName.equals("android")) { 7511 synchronized (mPackages) { 7512 if (mAndroidApplication != null) { 7513 Slog.w(TAG, "*************************************************"); 7514 Slog.w(TAG, "Core android package being redefined. Skipping."); 7515 Slog.w(TAG, " file=" + scanFile); 7516 Slog.w(TAG, "*************************************************"); 7517 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7518 "Core android package being redefined. Skipping."); 7519 } 7520 7521 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7522 // Set up information for our fall-back user intent resolution activity. 7523 mPlatformPackage = pkg; 7524 pkg.mVersionCode = mSdkVersion; 7525 mAndroidApplication = pkg.applicationInfo; 7526 7527 if (!mResolverReplaced) { 7528 mResolveActivity.applicationInfo = mAndroidApplication; 7529 mResolveActivity.name = ResolverActivity.class.getName(); 7530 mResolveActivity.packageName = mAndroidApplication.packageName; 7531 mResolveActivity.processName = "system:ui"; 7532 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7533 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7534 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7535 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7536 mResolveActivity.exported = true; 7537 mResolveActivity.enabled = true; 7538 mResolveInfo.activityInfo = mResolveActivity; 7539 mResolveInfo.priority = 0; 7540 mResolveInfo.preferredOrder = 0; 7541 mResolveInfo.match = 0; 7542 mResolveComponentName = new ComponentName( 7543 mAndroidApplication.packageName, mResolveActivity.name); 7544 } 7545 } 7546 } 7547 } 7548 7549 if (DEBUG_PACKAGE_SCANNING) { 7550 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7551 Log.d(TAG, "Scanning package " + pkg.packageName); 7552 } 7553 7554 synchronized (mPackages) { 7555 if (mPackages.containsKey(pkg.packageName) 7556 || mSharedLibraries.containsKey(pkg.packageName)) { 7557 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7558 "Application package " + pkg.packageName 7559 + " already installed. Skipping duplicate."); 7560 } 7561 7562 // If we're only installing presumed-existing packages, require that the 7563 // scanned APK is both already known and at the path previously established 7564 // for it. Previously unknown packages we pick up normally, but if we have an 7565 // a priori expectation about this package's install presence, enforce it. 7566 // With a singular exception for new system packages. When an OTA contains 7567 // a new system package, we allow the codepath to change from a system location 7568 // to the user-installed location. If we don't allow this change, any newer, 7569 // user-installed version of the application will be ignored. 7570 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7571 if (mExpectingBetter.containsKey(pkg.packageName)) { 7572 logCriticalInfo(Log.WARN, 7573 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7574 } else { 7575 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7576 if (known != null) { 7577 if (DEBUG_PACKAGE_SCANNING) { 7578 Log.d(TAG, "Examining " + pkg.codePath 7579 + " and requiring known paths " + known.codePathString 7580 + " & " + known.resourcePathString); 7581 } 7582 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7583 || !pkg.applicationInfo.getResourcePath().equals( 7584 known.resourcePathString)) { 7585 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7586 "Application package " + pkg.packageName 7587 + " found at " + pkg.applicationInfo.getCodePath() 7588 + " but expected at " + known.codePathString 7589 + "; ignoring."); 7590 } 7591 } 7592 } 7593 } 7594 } 7595 7596 // Initialize package source and resource directories 7597 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7598 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7599 7600 SharedUserSetting suid = null; 7601 PackageSetting pkgSetting = null; 7602 7603 if (!isSystemApp(pkg)) { 7604 // Only system apps can use these features. 7605 pkg.mOriginalPackages = null; 7606 pkg.mRealPackage = null; 7607 pkg.mAdoptPermissions = null; 7608 } 7609 7610 // Getting the package setting may have a side-effect, so if we 7611 // are only checking if scan would succeed, stash a copy of the 7612 // old setting to restore at the end. 7613 PackageSetting nonMutatedPs = null; 7614 7615 // writer 7616 synchronized (mPackages) { 7617 if (pkg.mSharedUserId != null) { 7618 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7619 if (suid == null) { 7620 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7621 "Creating application package " + pkg.packageName 7622 + " for shared user failed"); 7623 } 7624 if (DEBUG_PACKAGE_SCANNING) { 7625 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7626 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7627 + "): packages=" + suid.packages); 7628 } 7629 } 7630 7631 // Check if we are renaming from an original package name. 7632 PackageSetting origPackage = null; 7633 String realName = null; 7634 if (pkg.mOriginalPackages != null) { 7635 // This package may need to be renamed to a previously 7636 // installed name. Let's check on that... 7637 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7638 if (pkg.mOriginalPackages.contains(renamed)) { 7639 // This package had originally been installed as the 7640 // original name, and we have already taken care of 7641 // transitioning to the new one. Just update the new 7642 // one to continue using the old name. 7643 realName = pkg.mRealPackage; 7644 if (!pkg.packageName.equals(renamed)) { 7645 // Callers into this function may have already taken 7646 // care of renaming the package; only do it here if 7647 // it is not already done. 7648 pkg.setPackageName(renamed); 7649 } 7650 7651 } else { 7652 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7653 if ((origPackage = mSettings.peekPackageLPr( 7654 pkg.mOriginalPackages.get(i))) != null) { 7655 // We do have the package already installed under its 7656 // original name... should we use it? 7657 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7658 // New package is not compatible with original. 7659 origPackage = null; 7660 continue; 7661 } else if (origPackage.sharedUser != null) { 7662 // Make sure uid is compatible between packages. 7663 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7664 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7665 + " to " + pkg.packageName + ": old uid " 7666 + origPackage.sharedUser.name 7667 + " differs from " + pkg.mSharedUserId); 7668 origPackage = null; 7669 continue; 7670 } 7671 } else { 7672 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7673 + pkg.packageName + " to old name " + origPackage.name); 7674 } 7675 break; 7676 } 7677 } 7678 } 7679 } 7680 7681 if (mTransferedPackages.contains(pkg.packageName)) { 7682 Slog.w(TAG, "Package " + pkg.packageName 7683 + " was transferred to another, but its .apk remains"); 7684 } 7685 7686 // See comments in nonMutatedPs declaration 7687 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7688 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 7689 if (foundPs != null) { 7690 nonMutatedPs = new PackageSetting(foundPs); 7691 } 7692 } 7693 7694 // Just create the setting, don't add it yet. For already existing packages 7695 // the PkgSetting exists already and doesn't have to be created. 7696 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7697 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7698 pkg.applicationInfo.primaryCpuAbi, 7699 pkg.applicationInfo.secondaryCpuAbi, 7700 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7701 user, false); 7702 if (pkgSetting == null) { 7703 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7704 "Creating application package " + pkg.packageName + " failed"); 7705 } 7706 7707 if (pkgSetting.origPackage != null) { 7708 // If we are first transitioning from an original package, 7709 // fix up the new package's name now. We need to do this after 7710 // looking up the package under its new name, so getPackageLP 7711 // can take care of fiddling things correctly. 7712 pkg.setPackageName(origPackage.name); 7713 7714 // File a report about this. 7715 String msg = "New package " + pkgSetting.realName 7716 + " renamed to replace old package " + pkgSetting.name; 7717 reportSettingsProblem(Log.WARN, msg); 7718 7719 // Make a note of it. 7720 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7721 mTransferedPackages.add(origPackage.name); 7722 } 7723 7724 // No longer need to retain this. 7725 pkgSetting.origPackage = null; 7726 } 7727 7728 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 7729 // Make a note of it. 7730 mTransferedPackages.add(pkg.packageName); 7731 } 7732 7733 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7734 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7735 } 7736 7737 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7738 // Check all shared libraries and map to their actual file path. 7739 // We only do this here for apps not on a system dir, because those 7740 // are the only ones that can fail an install due to this. We 7741 // will take care of the system apps by updating all of their 7742 // library paths after the scan is done. 7743 updateSharedLibrariesLPw(pkg, null); 7744 } 7745 7746 if (mFoundPolicyFile) { 7747 SELinuxMMAC.assignSeinfoValue(pkg); 7748 } 7749 7750 pkg.applicationInfo.uid = pkgSetting.appId; 7751 pkg.mExtras = pkgSetting; 7752 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7753 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7754 // We just determined the app is signed correctly, so bring 7755 // over the latest parsed certs. 7756 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7757 } else { 7758 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7759 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7760 "Package " + pkg.packageName + " upgrade keys do not match the " 7761 + "previously installed version"); 7762 } else { 7763 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7764 String msg = "System package " + pkg.packageName 7765 + " signature changed; retaining data."; 7766 reportSettingsProblem(Log.WARN, msg); 7767 } 7768 } 7769 } else { 7770 try { 7771 verifySignaturesLP(pkgSetting, pkg); 7772 // We just determined the app is signed correctly, so bring 7773 // over the latest parsed certs. 7774 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7775 } catch (PackageManagerException e) { 7776 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7777 throw e; 7778 } 7779 // The signature has changed, but this package is in the system 7780 // image... let's recover! 7781 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7782 // However... if this package is part of a shared user, but it 7783 // doesn't match the signature of the shared user, let's fail. 7784 // What this means is that you can't change the signatures 7785 // associated with an overall shared user, which doesn't seem all 7786 // that unreasonable. 7787 if (pkgSetting.sharedUser != null) { 7788 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7789 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7790 throw new PackageManagerException( 7791 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7792 "Signature mismatch for shared user: " 7793 + pkgSetting.sharedUser); 7794 } 7795 } 7796 // File a report about this. 7797 String msg = "System package " + pkg.packageName 7798 + " signature changed; retaining data."; 7799 reportSettingsProblem(Log.WARN, msg); 7800 } 7801 } 7802 // Verify that this new package doesn't have any content providers 7803 // that conflict with existing packages. Only do this if the 7804 // package isn't already installed, since we don't want to break 7805 // things that are installed. 7806 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7807 final int N = pkg.providers.size(); 7808 int i; 7809 for (i=0; i<N; i++) { 7810 PackageParser.Provider p = pkg.providers.get(i); 7811 if (p.info.authority != null) { 7812 String names[] = p.info.authority.split(";"); 7813 for (int j = 0; j < names.length; j++) { 7814 if (mProvidersByAuthority.containsKey(names[j])) { 7815 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7816 final String otherPackageName = 7817 ((other != null && other.getComponentName() != null) ? 7818 other.getComponentName().getPackageName() : "?"); 7819 throw new PackageManagerException( 7820 INSTALL_FAILED_CONFLICTING_PROVIDER, 7821 "Can't install because provider name " + names[j] 7822 + " (in package " + pkg.applicationInfo.packageName 7823 + ") is already used by " + otherPackageName); 7824 } 7825 } 7826 } 7827 } 7828 } 7829 7830 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 7831 // This package wants to adopt ownership of permissions from 7832 // another package. 7833 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7834 final String origName = pkg.mAdoptPermissions.get(i); 7835 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7836 if (orig != null) { 7837 if (verifyPackageUpdateLPr(orig, pkg)) { 7838 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7839 + pkg.packageName); 7840 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7841 } 7842 } 7843 } 7844 } 7845 } 7846 7847 final String pkgName = pkg.packageName; 7848 7849 final long scanFileTime = scanFile.lastModified(); 7850 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7851 pkg.applicationInfo.processName = fixProcessName( 7852 pkg.applicationInfo.packageName, 7853 pkg.applicationInfo.processName, 7854 pkg.applicationInfo.uid); 7855 7856 if (pkg != mPlatformPackage) { 7857 // Get all of our default paths setup 7858 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7859 } 7860 7861 final String path = scanFile.getPath(); 7862 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7863 7864 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7865 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7866 7867 // Some system apps still use directory structure for native libraries 7868 // in which case we might end up not detecting abi solely based on apk 7869 // structure. Try to detect abi based on directory structure. 7870 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7871 pkg.applicationInfo.primaryCpuAbi == null) { 7872 setBundledAppAbisAndRoots(pkg, pkgSetting); 7873 setNativeLibraryPaths(pkg); 7874 } 7875 7876 } else { 7877 if ((scanFlags & SCAN_MOVE) != 0) { 7878 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7879 // but we already have this packages package info in the PackageSetting. We just 7880 // use that and derive the native library path based on the new codepath. 7881 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7882 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7883 } 7884 7885 // Set native library paths again. For moves, the path will be updated based on the 7886 // ABIs we've determined above. For non-moves, the path will be updated based on the 7887 // ABIs we determined during compilation, but the path will depend on the final 7888 // package path (after the rename away from the stage path). 7889 setNativeLibraryPaths(pkg); 7890 } 7891 7892 // This is a special case for the "system" package, where the ABI is 7893 // dictated by the zygote configuration (and init.rc). We should keep track 7894 // of this ABI so that we can deal with "normal" applications that run under 7895 // the same UID correctly. 7896 if (mPlatformPackage == pkg) { 7897 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7898 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7899 } 7900 7901 // If there's a mismatch between the abi-override in the package setting 7902 // and the abiOverride specified for the install. Warn about this because we 7903 // would've already compiled the app without taking the package setting into 7904 // account. 7905 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7906 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7907 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7908 " for package " + pkg.packageName); 7909 } 7910 } 7911 7912 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7913 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7914 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7915 7916 // Copy the derived override back to the parsed package, so that we can 7917 // update the package settings accordingly. 7918 pkg.cpuAbiOverride = cpuAbiOverride; 7919 7920 if (DEBUG_ABI_SELECTION) { 7921 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7922 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7923 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7924 } 7925 7926 // Push the derived path down into PackageSettings so we know what to 7927 // clean up at uninstall time. 7928 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7929 7930 if (DEBUG_ABI_SELECTION) { 7931 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7932 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7933 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7934 } 7935 7936 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7937 // We don't do this here during boot because we can do it all 7938 // at once after scanning all existing packages. 7939 // 7940 // We also do this *before* we perform dexopt on this package, so that 7941 // we can avoid redundant dexopts, and also to make sure we've got the 7942 // code and package path correct. 7943 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7944 pkg, true /* boot complete */); 7945 } 7946 7947 if (mFactoryTest && pkg.requestedPermissions.contains( 7948 android.Manifest.permission.FACTORY_TEST)) { 7949 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7950 } 7951 7952 ArrayList<PackageParser.Package> clientLibPkgs = null; 7953 7954 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7955 if (nonMutatedPs != null) { 7956 synchronized (mPackages) { 7957 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 7958 } 7959 } 7960 return pkg; 7961 } 7962 7963 // Only privileged apps and updated privileged apps can add child packages. 7964 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 7965 if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) { 7966 throw new PackageManagerException("Only privileged apps and updated " 7967 + "privileged apps can add child packages. Ignoring package " 7968 + pkg.packageName); 7969 } 7970 final int childCount = pkg.childPackages.size(); 7971 for (int i = 0; i < childCount; i++) { 7972 PackageParser.Package childPkg = pkg.childPackages.get(i); 7973 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 7974 childPkg.packageName)) { 7975 throw new PackageManagerException("Cannot override a child package of " 7976 + "another disabled system app. Ignoring package " + pkg.packageName); 7977 } 7978 } 7979 } 7980 7981 // writer 7982 synchronized (mPackages) { 7983 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7984 // Only system apps can add new shared libraries. 7985 if (pkg.libraryNames != null) { 7986 for (int i=0; i<pkg.libraryNames.size(); i++) { 7987 String name = pkg.libraryNames.get(i); 7988 boolean allowed = false; 7989 if (pkg.isUpdatedSystemApp()) { 7990 // New library entries can only be added through the 7991 // system image. This is important to get rid of a lot 7992 // of nasty edge cases: for example if we allowed a non- 7993 // system update of the app to add a library, then uninstalling 7994 // the update would make the library go away, and assumptions 7995 // we made such as through app install filtering would now 7996 // have allowed apps on the device which aren't compatible 7997 // with it. Better to just have the restriction here, be 7998 // conservative, and create many fewer cases that can negatively 7999 // impact the user experience. 8000 final PackageSetting sysPs = mSettings 8001 .getDisabledSystemPkgLPr(pkg.packageName); 8002 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8003 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8004 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8005 allowed = true; 8006 break; 8007 } 8008 } 8009 } 8010 } else { 8011 allowed = true; 8012 } 8013 if (allowed) { 8014 if (!mSharedLibraries.containsKey(name)) { 8015 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8016 } else if (!name.equals(pkg.packageName)) { 8017 Slog.w(TAG, "Package " + pkg.packageName + " library " 8018 + name + " already exists; skipping"); 8019 } 8020 } else { 8021 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8022 + name + " that is not declared on system image; skipping"); 8023 } 8024 } 8025 if ((scanFlags & SCAN_BOOTING) == 0) { 8026 // If we are not booting, we need to update any applications 8027 // that are clients of our shared library. If we are booting, 8028 // this will all be done once the scan is complete. 8029 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8030 } 8031 } 8032 } 8033 } 8034 8035 // Request the ActivityManager to kill the process(only for existing packages) 8036 // so that we do not end up in a confused state while the user is still using the older 8037 // version of the application while the new one gets installed. 8038 final boolean isReplacing = (scanFlags & SCAN_REPLACING) != 0; 8039 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 8040 if (killApp) { 8041 if (isReplacing) { 8042 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 8043 8044 killApplication(pkg.applicationInfo.packageName, 8045 pkg.applicationInfo.uid, "replace pkg"); 8046 8047 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8048 } 8049 } 8050 8051 // Also need to kill any apps that are dependent on the library. 8052 if (clientLibPkgs != null) { 8053 for (int i=0; i<clientLibPkgs.size(); i++) { 8054 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8055 killApplication(clientPkg.applicationInfo.packageName, 8056 clientPkg.applicationInfo.uid, "update lib"); 8057 } 8058 } 8059 8060 // Make sure we're not adding any bogus keyset info 8061 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8062 ksms.assertScannedPackageValid(pkg); 8063 8064 // writer 8065 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8066 8067 boolean createIdmapFailed = false; 8068 synchronized (mPackages) { 8069 // We don't expect installation to fail beyond this point 8070 8071 // Add the new setting to mSettings 8072 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8073 // Add the new setting to mPackages 8074 mPackages.put(pkg.applicationInfo.packageName, pkg); 8075 // Make sure we don't accidentally delete its data. 8076 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8077 while (iter.hasNext()) { 8078 PackageCleanItem item = iter.next(); 8079 if (pkgName.equals(item.packageName)) { 8080 iter.remove(); 8081 } 8082 } 8083 8084 // Take care of first install / last update times. 8085 if (currentTime != 0) { 8086 if (pkgSetting.firstInstallTime == 0) { 8087 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8088 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8089 pkgSetting.lastUpdateTime = currentTime; 8090 } 8091 } else if (pkgSetting.firstInstallTime == 0) { 8092 // We need *something*. Take time time stamp of the file. 8093 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8094 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8095 if (scanFileTime != pkgSetting.timeStamp) { 8096 // A package on the system image has changed; consider this 8097 // to be an update. 8098 pkgSetting.lastUpdateTime = scanFileTime; 8099 } 8100 } 8101 8102 // Add the package's KeySets to the global KeySetManagerService 8103 ksms.addScannedPackageLPw(pkg); 8104 8105 int N = pkg.providers.size(); 8106 StringBuilder r = null; 8107 int i; 8108 for (i=0; i<N; i++) { 8109 PackageParser.Provider p = pkg.providers.get(i); 8110 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8111 p.info.processName, pkg.applicationInfo.uid); 8112 mProviders.addProvider(p); 8113 p.syncable = p.info.isSyncable; 8114 if (p.info.authority != null) { 8115 String names[] = p.info.authority.split(";"); 8116 p.info.authority = null; 8117 for (int j = 0; j < names.length; j++) { 8118 if (j == 1 && p.syncable) { 8119 // We only want the first authority for a provider to possibly be 8120 // syncable, so if we already added this provider using a different 8121 // authority clear the syncable flag. We copy the provider before 8122 // changing it because the mProviders object contains a reference 8123 // to a provider that we don't want to change. 8124 // Only do this for the second authority since the resulting provider 8125 // object can be the same for all future authorities for this provider. 8126 p = new PackageParser.Provider(p); 8127 p.syncable = false; 8128 } 8129 if (!mProvidersByAuthority.containsKey(names[j])) { 8130 mProvidersByAuthority.put(names[j], p); 8131 if (p.info.authority == null) { 8132 p.info.authority = names[j]; 8133 } else { 8134 p.info.authority = p.info.authority + ";" + names[j]; 8135 } 8136 if (DEBUG_PACKAGE_SCANNING) { 8137 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 8138 Log.d(TAG, "Registered content provider: " + names[j] 8139 + ", className = " + p.info.name + ", isSyncable = " 8140 + p.info.isSyncable); 8141 } 8142 } else { 8143 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8144 Slog.w(TAG, "Skipping provider name " + names[j] + 8145 " (in package " + pkg.applicationInfo.packageName + 8146 "): name already used by " 8147 + ((other != null && other.getComponentName() != null) 8148 ? other.getComponentName().getPackageName() : "?")); 8149 } 8150 } 8151 } 8152 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8153 if (r == null) { 8154 r = new StringBuilder(256); 8155 } else { 8156 r.append(' '); 8157 } 8158 r.append(p.info.name); 8159 } 8160 } 8161 if (r != null) { 8162 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8163 } 8164 8165 N = pkg.services.size(); 8166 r = null; 8167 for (i=0; i<N; i++) { 8168 PackageParser.Service s = pkg.services.get(i); 8169 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8170 s.info.processName, pkg.applicationInfo.uid); 8171 mServices.addService(s); 8172 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8173 if (r == null) { 8174 r = new StringBuilder(256); 8175 } else { 8176 r.append(' '); 8177 } 8178 r.append(s.info.name); 8179 } 8180 } 8181 if (r != null) { 8182 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8183 } 8184 8185 N = pkg.receivers.size(); 8186 r = null; 8187 for (i=0; i<N; i++) { 8188 PackageParser.Activity a = pkg.receivers.get(i); 8189 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8190 a.info.processName, pkg.applicationInfo.uid); 8191 mReceivers.addActivity(a, "receiver"); 8192 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8193 if (r == null) { 8194 r = new StringBuilder(256); 8195 } else { 8196 r.append(' '); 8197 } 8198 r.append(a.info.name); 8199 } 8200 } 8201 if (r != null) { 8202 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8203 } 8204 8205 N = pkg.activities.size(); 8206 r = null; 8207 for (i=0; i<N; i++) { 8208 PackageParser.Activity a = pkg.activities.get(i); 8209 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8210 a.info.processName, pkg.applicationInfo.uid); 8211 mActivities.addActivity(a, "activity"); 8212 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8213 if (r == null) { 8214 r = new StringBuilder(256); 8215 } else { 8216 r.append(' '); 8217 } 8218 r.append(a.info.name); 8219 } 8220 } 8221 if (r != null) { 8222 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8223 } 8224 8225 N = pkg.permissionGroups.size(); 8226 r = null; 8227 for (i=0; i<N; i++) { 8228 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8229 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8230 if (cur == null) { 8231 mPermissionGroups.put(pg.info.name, pg); 8232 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8233 if (r == null) { 8234 r = new StringBuilder(256); 8235 } else { 8236 r.append(' '); 8237 } 8238 r.append(pg.info.name); 8239 } 8240 } else { 8241 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8242 + pg.info.packageName + " ignored: original from " 8243 + cur.info.packageName); 8244 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8245 if (r == null) { 8246 r = new StringBuilder(256); 8247 } else { 8248 r.append(' '); 8249 } 8250 r.append("DUP:"); 8251 r.append(pg.info.name); 8252 } 8253 } 8254 } 8255 if (r != null) { 8256 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8257 } 8258 8259 N = pkg.permissions.size(); 8260 r = null; 8261 for (i=0; i<N; i++) { 8262 PackageParser.Permission p = pkg.permissions.get(i); 8263 8264 // Assume by default that we did not install this permission into the system. 8265 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8266 8267 // Now that permission groups have a special meaning, we ignore permission 8268 // groups for legacy apps to prevent unexpected behavior. In particular, 8269 // permissions for one app being granted to someone just becase they happen 8270 // to be in a group defined by another app (before this had no implications). 8271 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8272 p.group = mPermissionGroups.get(p.info.group); 8273 // Warn for a permission in an unknown group. 8274 if (p.info.group != null && p.group == null) { 8275 Slog.w(TAG, "Permission " + p.info.name + " from package " 8276 + p.info.packageName + " in an unknown group " + p.info.group); 8277 } 8278 } 8279 8280 ArrayMap<String, BasePermission> permissionMap = 8281 p.tree ? mSettings.mPermissionTrees 8282 : mSettings.mPermissions; 8283 BasePermission bp = permissionMap.get(p.info.name); 8284 8285 // Allow system apps to redefine non-system permissions 8286 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8287 final boolean currentOwnerIsSystem = (bp.perm != null 8288 && isSystemApp(bp.perm.owner)); 8289 if (isSystemApp(p.owner)) { 8290 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8291 // It's a built-in permission and no owner, take ownership now 8292 bp.packageSetting = pkgSetting; 8293 bp.perm = p; 8294 bp.uid = pkg.applicationInfo.uid; 8295 bp.sourcePackage = p.info.packageName; 8296 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8297 } else if (!currentOwnerIsSystem) { 8298 String msg = "New decl " + p.owner + " of permission " 8299 + p.info.name + " is system; overriding " + bp.sourcePackage; 8300 reportSettingsProblem(Log.WARN, msg); 8301 bp = null; 8302 } 8303 } 8304 } 8305 8306 if (bp == null) { 8307 bp = new BasePermission(p.info.name, p.info.packageName, 8308 BasePermission.TYPE_NORMAL); 8309 permissionMap.put(p.info.name, bp); 8310 } 8311 8312 if (bp.perm == null) { 8313 if (bp.sourcePackage == null 8314 || bp.sourcePackage.equals(p.info.packageName)) { 8315 BasePermission tree = findPermissionTreeLP(p.info.name); 8316 if (tree == null 8317 || tree.sourcePackage.equals(p.info.packageName)) { 8318 bp.packageSetting = pkgSetting; 8319 bp.perm = p; 8320 bp.uid = pkg.applicationInfo.uid; 8321 bp.sourcePackage = p.info.packageName; 8322 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8323 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8324 if (r == null) { 8325 r = new StringBuilder(256); 8326 } else { 8327 r.append(' '); 8328 } 8329 r.append(p.info.name); 8330 } 8331 } else { 8332 Slog.w(TAG, "Permission " + p.info.name + " from package " 8333 + p.info.packageName + " ignored: base tree " 8334 + tree.name + " is from package " 8335 + tree.sourcePackage); 8336 } 8337 } else { 8338 Slog.w(TAG, "Permission " + p.info.name + " from package " 8339 + p.info.packageName + " ignored: original from " 8340 + bp.sourcePackage); 8341 } 8342 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8343 if (r == null) { 8344 r = new StringBuilder(256); 8345 } else { 8346 r.append(' '); 8347 } 8348 r.append("DUP:"); 8349 r.append(p.info.name); 8350 } 8351 if (bp.perm == p) { 8352 bp.protectionLevel = p.info.protectionLevel; 8353 } 8354 } 8355 8356 if (r != null) { 8357 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8358 } 8359 8360 N = pkg.instrumentation.size(); 8361 r = null; 8362 for (i=0; i<N; i++) { 8363 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8364 a.info.packageName = pkg.applicationInfo.packageName; 8365 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8366 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8367 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8368 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8369 a.info.dataDir = pkg.applicationInfo.dataDir; 8370 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8371 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8372 8373 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8374 // need other information about the application, like the ABI and what not ? 8375 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8376 mInstrumentation.put(a.getComponentName(), a); 8377 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8378 if (r == null) { 8379 r = new StringBuilder(256); 8380 } else { 8381 r.append(' '); 8382 } 8383 r.append(a.info.name); 8384 } 8385 } 8386 if (r != null) { 8387 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8388 } 8389 8390 if (pkg.protectedBroadcasts != null) { 8391 N = pkg.protectedBroadcasts.size(); 8392 for (i=0; i<N; i++) { 8393 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8394 } 8395 } 8396 8397 pkgSetting.setTimeStamp(scanFileTime); 8398 8399 // Create idmap files for pairs of (packages, overlay packages). 8400 // Note: "android", ie framework-res.apk, is handled by native layers. 8401 if (pkg.mOverlayTarget != null) { 8402 // This is an overlay package. 8403 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8404 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8405 mOverlays.put(pkg.mOverlayTarget, 8406 new ArrayMap<String, PackageParser.Package>()); 8407 } 8408 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8409 map.put(pkg.packageName, pkg); 8410 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8411 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8412 createIdmapFailed = true; 8413 } 8414 } 8415 } else if (mOverlays.containsKey(pkg.packageName) && 8416 !pkg.packageName.equals("android")) { 8417 // This is a regular package, with one or more known overlay packages. 8418 createIdmapsForPackageLI(pkg); 8419 } 8420 } 8421 8422 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8423 8424 if (createIdmapFailed) { 8425 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8426 "scanPackageLI failed to createIdmap"); 8427 } 8428 return pkg; 8429 } 8430 8431 /** 8432 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8433 * is derived purely on the basis of the contents of {@code scanFile} and 8434 * {@code cpuAbiOverride}. 8435 * 8436 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8437 */ 8438 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8439 String cpuAbiOverride, boolean extractLibs) 8440 throws PackageManagerException { 8441 // TODO: We can probably be smarter about this stuff. For installed apps, 8442 // we can calculate this information at install time once and for all. For 8443 // system apps, we can probably assume that this information doesn't change 8444 // after the first boot scan. As things stand, we do lots of unnecessary work. 8445 8446 // Give ourselves some initial paths; we'll come back for another 8447 // pass once we've determined ABI below. 8448 setNativeLibraryPaths(pkg); 8449 8450 // We would never need to extract libs for forward-locked and external packages, 8451 // since the container service will do it for us. We shouldn't attempt to 8452 // extract libs from system app when it was not updated. 8453 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8454 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8455 extractLibs = false; 8456 } 8457 8458 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8459 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8460 8461 NativeLibraryHelper.Handle handle = null; 8462 try { 8463 handle = NativeLibraryHelper.Handle.create(pkg); 8464 // TODO(multiArch): This can be null for apps that didn't go through the 8465 // usual installation process. We can calculate it again, like we 8466 // do during install time. 8467 // 8468 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8469 // unnecessary. 8470 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8471 8472 // Null out the abis so that they can be recalculated. 8473 pkg.applicationInfo.primaryCpuAbi = null; 8474 pkg.applicationInfo.secondaryCpuAbi = null; 8475 if (isMultiArch(pkg.applicationInfo)) { 8476 // Warn if we've set an abiOverride for multi-lib packages.. 8477 // By definition, we need to copy both 32 and 64 bit libraries for 8478 // such packages. 8479 if (pkg.cpuAbiOverride != null 8480 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8481 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8482 } 8483 8484 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8485 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8486 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8487 if (extractLibs) { 8488 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8489 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8490 useIsaSpecificSubdirs); 8491 } else { 8492 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8493 } 8494 } 8495 8496 maybeThrowExceptionForMultiArchCopy( 8497 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8498 8499 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8500 if (extractLibs) { 8501 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8502 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8503 useIsaSpecificSubdirs); 8504 } else { 8505 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8506 } 8507 } 8508 8509 maybeThrowExceptionForMultiArchCopy( 8510 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8511 8512 if (abi64 >= 0) { 8513 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8514 } 8515 8516 if (abi32 >= 0) { 8517 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8518 if (abi64 >= 0) { 8519 if (cpuAbiOverride == null && pkg.use32bitAbi) { 8520 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8521 pkg.applicationInfo.primaryCpuAbi = abi; 8522 } else { 8523 pkg.applicationInfo.secondaryCpuAbi = abi; 8524 } 8525 } else { 8526 pkg.applicationInfo.primaryCpuAbi = abi; 8527 } 8528 } 8529 8530 } else { 8531 String[] abiList = (cpuAbiOverride != null) ? 8532 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8533 8534 // Enable gross and lame hacks for apps that are built with old 8535 // SDK tools. We must scan their APKs for renderscript bitcode and 8536 // not launch them if it's present. Don't bother checking on devices 8537 // that don't have 64 bit support. 8538 boolean needsRenderScriptOverride = false; 8539 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8540 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8541 abiList = Build.SUPPORTED_32_BIT_ABIS; 8542 needsRenderScriptOverride = true; 8543 } 8544 8545 final int copyRet; 8546 if (extractLibs) { 8547 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8548 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8549 } else { 8550 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8551 } 8552 8553 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8554 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8555 "Error unpackaging native libs for app, errorCode=" + copyRet); 8556 } 8557 8558 if (copyRet >= 0) { 8559 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8560 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8561 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8562 } else if (needsRenderScriptOverride) { 8563 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8564 } 8565 } 8566 } catch (IOException ioe) { 8567 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8568 } finally { 8569 IoUtils.closeQuietly(handle); 8570 } 8571 8572 // Now that we've calculated the ABIs and determined if it's an internal app, 8573 // we will go ahead and populate the nativeLibraryPath. 8574 setNativeLibraryPaths(pkg); 8575 } 8576 8577 /** 8578 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8579 * i.e, so that all packages can be run inside a single process if required. 8580 * 8581 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8582 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8583 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8584 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8585 * updating a package that belongs to a shared user. 8586 * 8587 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8588 * adds unnecessary complexity. 8589 */ 8590 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8591 PackageParser.Package scannedPackage, boolean bootComplete) { 8592 String requiredInstructionSet = null; 8593 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8594 requiredInstructionSet = VMRuntime.getInstructionSet( 8595 scannedPackage.applicationInfo.primaryCpuAbi); 8596 } 8597 8598 PackageSetting requirer = null; 8599 for (PackageSetting ps : packagesForUser) { 8600 // If packagesForUser contains scannedPackage, we skip it. This will happen 8601 // when scannedPackage is an update of an existing package. Without this check, 8602 // we will never be able to change the ABI of any package belonging to a shared 8603 // user, even if it's compatible with other packages. 8604 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8605 if (ps.primaryCpuAbiString == null) { 8606 continue; 8607 } 8608 8609 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8610 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8611 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8612 // this but there's not much we can do. 8613 String errorMessage = "Instruction set mismatch, " 8614 + ((requirer == null) ? "[caller]" : requirer) 8615 + " requires " + requiredInstructionSet + " whereas " + ps 8616 + " requires " + instructionSet; 8617 Slog.w(TAG, errorMessage); 8618 } 8619 8620 if (requiredInstructionSet == null) { 8621 requiredInstructionSet = instructionSet; 8622 requirer = ps; 8623 } 8624 } 8625 } 8626 8627 if (requiredInstructionSet != null) { 8628 String adjustedAbi; 8629 if (requirer != null) { 8630 // requirer != null implies that either scannedPackage was null or that scannedPackage 8631 // did not require an ABI, in which case we have to adjust scannedPackage to match 8632 // the ABI of the set (which is the same as requirer's ABI) 8633 adjustedAbi = requirer.primaryCpuAbiString; 8634 if (scannedPackage != null) { 8635 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8636 } 8637 } else { 8638 // requirer == null implies that we're updating all ABIs in the set to 8639 // match scannedPackage. 8640 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8641 } 8642 8643 for (PackageSetting ps : packagesForUser) { 8644 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8645 if (ps.primaryCpuAbiString != null) { 8646 continue; 8647 } 8648 8649 ps.primaryCpuAbiString = adjustedAbi; 8650 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8651 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8652 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8653 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8654 + " (requirer=" 8655 + (requirer == null ? "null" : requirer.pkg.packageName) 8656 + ", scannedPackage=" 8657 + (scannedPackage != null ? scannedPackage.packageName : "null") 8658 + ")"); 8659 try { 8660 mInstaller.rmdex(ps.codePathString, 8661 getDexCodeInstructionSet(getPreferredInstructionSet())); 8662 } catch (InstallerException ignored) { 8663 } 8664 } 8665 } 8666 } 8667 } 8668 } 8669 8670 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8671 synchronized (mPackages) { 8672 mResolverReplaced = true; 8673 // Set up information for custom user intent resolution activity. 8674 mResolveActivity.applicationInfo = pkg.applicationInfo; 8675 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8676 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8677 mResolveActivity.processName = pkg.applicationInfo.packageName; 8678 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8679 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8680 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8681 mResolveActivity.theme = 0; 8682 mResolveActivity.exported = true; 8683 mResolveActivity.enabled = true; 8684 mResolveInfo.activityInfo = mResolveActivity; 8685 mResolveInfo.priority = 0; 8686 mResolveInfo.preferredOrder = 0; 8687 mResolveInfo.match = 0; 8688 mResolveComponentName = mCustomResolverComponentName; 8689 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8690 mResolveComponentName); 8691 } 8692 } 8693 8694 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8695 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8696 8697 // Set up information for ephemeral installer activity 8698 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8699 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8700 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8701 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8702 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8703 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8704 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8705 mEphemeralInstallerActivity.theme = 0; 8706 mEphemeralInstallerActivity.exported = true; 8707 mEphemeralInstallerActivity.enabled = true; 8708 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8709 mEphemeralInstallerInfo.priority = 0; 8710 mEphemeralInstallerInfo.preferredOrder = 0; 8711 mEphemeralInstallerInfo.match = 0; 8712 8713 if (DEBUG_EPHEMERAL) { 8714 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8715 } 8716 } 8717 8718 private static String calculateBundledApkRoot(final String codePathString) { 8719 final File codePath = new File(codePathString); 8720 final File codeRoot; 8721 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8722 codeRoot = Environment.getRootDirectory(); 8723 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8724 codeRoot = Environment.getOemDirectory(); 8725 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8726 codeRoot = Environment.getVendorDirectory(); 8727 } else { 8728 // Unrecognized code path; take its top real segment as the apk root: 8729 // e.g. /something/app/blah.apk => /something 8730 try { 8731 File f = codePath.getCanonicalFile(); 8732 File parent = f.getParentFile(); // non-null because codePath is a file 8733 File tmp; 8734 while ((tmp = parent.getParentFile()) != null) { 8735 f = parent; 8736 parent = tmp; 8737 } 8738 codeRoot = f; 8739 Slog.w(TAG, "Unrecognized code path " 8740 + codePath + " - using " + codeRoot); 8741 } catch (IOException e) { 8742 // Can't canonicalize the code path -- shenanigans? 8743 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8744 return Environment.getRootDirectory().getPath(); 8745 } 8746 } 8747 return codeRoot.getPath(); 8748 } 8749 8750 /** 8751 * Derive and set the location of native libraries for the given package, 8752 * which varies depending on where and how the package was installed. 8753 */ 8754 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8755 final ApplicationInfo info = pkg.applicationInfo; 8756 final String codePath = pkg.codePath; 8757 final File codeFile = new File(codePath); 8758 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8759 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8760 8761 info.nativeLibraryRootDir = null; 8762 info.nativeLibraryRootRequiresIsa = false; 8763 info.nativeLibraryDir = null; 8764 info.secondaryNativeLibraryDir = null; 8765 8766 if (isApkFile(codeFile)) { 8767 // Monolithic install 8768 if (bundledApp) { 8769 // If "/system/lib64/apkname" exists, assume that is the per-package 8770 // native library directory to use; otherwise use "/system/lib/apkname". 8771 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8772 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8773 getPrimaryInstructionSet(info)); 8774 8775 // This is a bundled system app so choose the path based on the ABI. 8776 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8777 // is just the default path. 8778 final String apkName = deriveCodePathName(codePath); 8779 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8780 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8781 apkName).getAbsolutePath(); 8782 8783 if (info.secondaryCpuAbi != null) { 8784 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8785 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8786 secondaryLibDir, apkName).getAbsolutePath(); 8787 } 8788 } else if (asecApp) { 8789 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8790 .getAbsolutePath(); 8791 } else { 8792 final String apkName = deriveCodePathName(codePath); 8793 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8794 .getAbsolutePath(); 8795 } 8796 8797 info.nativeLibraryRootRequiresIsa = false; 8798 info.nativeLibraryDir = info.nativeLibraryRootDir; 8799 } else { 8800 // Cluster install 8801 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8802 info.nativeLibraryRootRequiresIsa = true; 8803 8804 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8805 getPrimaryInstructionSet(info)).getAbsolutePath(); 8806 8807 if (info.secondaryCpuAbi != null) { 8808 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8809 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8810 } 8811 } 8812 } 8813 8814 /** 8815 * Calculate the abis and roots for a bundled app. These can uniquely 8816 * be determined from the contents of the system partition, i.e whether 8817 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8818 * of this information, and instead assume that the system was built 8819 * sensibly. 8820 */ 8821 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8822 PackageSetting pkgSetting) { 8823 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8824 8825 // If "/system/lib64/apkname" exists, assume that is the per-package 8826 // native library directory to use; otherwise use "/system/lib/apkname". 8827 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8828 setBundledAppAbi(pkg, apkRoot, apkName); 8829 // pkgSetting might be null during rescan following uninstall of updates 8830 // to a bundled app, so accommodate that possibility. The settings in 8831 // that case will be established later from the parsed package. 8832 // 8833 // If the settings aren't null, sync them up with what we've just derived. 8834 // note that apkRoot isn't stored in the package settings. 8835 if (pkgSetting != null) { 8836 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8837 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8838 } 8839 } 8840 8841 /** 8842 * Deduces the ABI of a bundled app and sets the relevant fields on the 8843 * parsed pkg object. 8844 * 8845 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8846 * under which system libraries are installed. 8847 * @param apkName the name of the installed package. 8848 */ 8849 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8850 final File codeFile = new File(pkg.codePath); 8851 8852 final boolean has64BitLibs; 8853 final boolean has32BitLibs; 8854 if (isApkFile(codeFile)) { 8855 // Monolithic install 8856 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8857 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8858 } else { 8859 // Cluster install 8860 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8861 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8862 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8863 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8864 has64BitLibs = (new File(rootDir, isa)).exists(); 8865 } else { 8866 has64BitLibs = false; 8867 } 8868 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8869 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8870 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8871 has32BitLibs = (new File(rootDir, isa)).exists(); 8872 } else { 8873 has32BitLibs = false; 8874 } 8875 } 8876 8877 if (has64BitLibs && !has32BitLibs) { 8878 // The package has 64 bit libs, but not 32 bit libs. Its primary 8879 // ABI should be 64 bit. We can safely assume here that the bundled 8880 // native libraries correspond to the most preferred ABI in the list. 8881 8882 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8883 pkg.applicationInfo.secondaryCpuAbi = null; 8884 } else if (has32BitLibs && !has64BitLibs) { 8885 // The package has 32 bit libs but not 64 bit libs. Its primary 8886 // ABI should be 32 bit. 8887 8888 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8889 pkg.applicationInfo.secondaryCpuAbi = null; 8890 } else if (has32BitLibs && has64BitLibs) { 8891 // The application has both 64 and 32 bit bundled libraries. We check 8892 // here that the app declares multiArch support, and warn if it doesn't. 8893 // 8894 // We will be lenient here and record both ABIs. The primary will be the 8895 // ABI that's higher on the list, i.e, a device that's configured to prefer 8896 // 64 bit apps will see a 64 bit primary ABI, 8897 8898 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8899 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 8900 } 8901 8902 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8903 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8904 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8905 } else { 8906 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8907 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8908 } 8909 } else { 8910 pkg.applicationInfo.primaryCpuAbi = null; 8911 pkg.applicationInfo.secondaryCpuAbi = null; 8912 } 8913 } 8914 8915 private void killPackage(PackageParser.Package pkg, String reason) { 8916 // Kill the parent package 8917 killApplication(pkg.packageName, pkg.applicationInfo.uid, reason); 8918 // Kill the child packages 8919 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8920 for (int i = 0; i < childCount; i++) { 8921 PackageParser.Package childPkg = pkg.childPackages.get(i); 8922 killApplication(childPkg.packageName, childPkg.applicationInfo.uid, reason); 8923 } 8924 } 8925 8926 private void killApplication(String pkgName, int appId, String reason) { 8927 // Request the ActivityManager to kill the process(only for existing packages) 8928 // so that we do not end up in a confused state while the user is still using the older 8929 // version of the application while the new one gets installed. 8930 IActivityManager am = ActivityManagerNative.getDefault(); 8931 if (am != null) { 8932 try { 8933 am.killApplicationWithAppId(pkgName, appId, reason); 8934 } catch (RemoteException e) { 8935 } 8936 } 8937 } 8938 8939 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 8940 // Remove the parent package setting 8941 PackageSetting ps = (PackageSetting) pkg.mExtras; 8942 if (ps != null) { 8943 removePackageLI(ps, chatty); 8944 } 8945 // Remove the child package setting 8946 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8947 for (int i = 0; i < childCount; i++) { 8948 PackageParser.Package childPkg = pkg.childPackages.get(i); 8949 ps = (PackageSetting) childPkg.mExtras; 8950 if (ps != null) { 8951 removePackageLI(ps, chatty); 8952 } 8953 } 8954 } 8955 8956 void removePackageLI(PackageSetting ps, boolean chatty) { 8957 if (DEBUG_INSTALL) { 8958 if (chatty) 8959 Log.d(TAG, "Removing package " + ps.name); 8960 } 8961 8962 // writer 8963 synchronized (mPackages) { 8964 mPackages.remove(ps.name); 8965 final PackageParser.Package pkg = ps.pkg; 8966 if (pkg != null) { 8967 cleanPackageDataStructuresLILPw(pkg, chatty); 8968 } 8969 } 8970 } 8971 8972 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8973 if (DEBUG_INSTALL) { 8974 if (chatty) 8975 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8976 } 8977 8978 // writer 8979 synchronized (mPackages) { 8980 // Remove the parent package 8981 mPackages.remove(pkg.applicationInfo.packageName); 8982 cleanPackageDataStructuresLILPw(pkg, chatty); 8983 8984 // Remove the child packages 8985 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8986 for (int i = 0; i < childCount; i++) { 8987 PackageParser.Package childPkg = pkg.childPackages.get(i); 8988 mPackages.remove(childPkg.applicationInfo.packageName); 8989 cleanPackageDataStructuresLILPw(childPkg, chatty); 8990 } 8991 } 8992 } 8993 8994 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8995 int N = pkg.providers.size(); 8996 StringBuilder r = null; 8997 int i; 8998 for (i=0; i<N; i++) { 8999 PackageParser.Provider p = pkg.providers.get(i); 9000 mProviders.removeProvider(p); 9001 if (p.info.authority == null) { 9002 9003 /* There was another ContentProvider with this authority when 9004 * this app was installed so this authority is null, 9005 * Ignore it as we don't have to unregister the provider. 9006 */ 9007 continue; 9008 } 9009 String names[] = p.info.authority.split(";"); 9010 for (int j = 0; j < names.length; j++) { 9011 if (mProvidersByAuthority.get(names[j]) == p) { 9012 mProvidersByAuthority.remove(names[j]); 9013 if (DEBUG_REMOVE) { 9014 if (chatty) 9015 Log.d(TAG, "Unregistered content provider: " + names[j] 9016 + ", className = " + p.info.name + ", isSyncable = " 9017 + p.info.isSyncable); 9018 } 9019 } 9020 } 9021 if (DEBUG_REMOVE && chatty) { 9022 if (r == null) { 9023 r = new StringBuilder(256); 9024 } else { 9025 r.append(' '); 9026 } 9027 r.append(p.info.name); 9028 } 9029 } 9030 if (r != null) { 9031 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9032 } 9033 9034 N = pkg.services.size(); 9035 r = null; 9036 for (i=0; i<N; i++) { 9037 PackageParser.Service s = pkg.services.get(i); 9038 mServices.removeService(s); 9039 if (chatty) { 9040 if (r == null) { 9041 r = new StringBuilder(256); 9042 } else { 9043 r.append(' '); 9044 } 9045 r.append(s.info.name); 9046 } 9047 } 9048 if (r != null) { 9049 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9050 } 9051 9052 N = pkg.receivers.size(); 9053 r = null; 9054 for (i=0; i<N; i++) { 9055 PackageParser.Activity a = pkg.receivers.get(i); 9056 mReceivers.removeActivity(a, "receiver"); 9057 if (DEBUG_REMOVE && chatty) { 9058 if (r == null) { 9059 r = new StringBuilder(256); 9060 } else { 9061 r.append(' '); 9062 } 9063 r.append(a.info.name); 9064 } 9065 } 9066 if (r != null) { 9067 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9068 } 9069 9070 N = pkg.activities.size(); 9071 r = null; 9072 for (i=0; i<N; i++) { 9073 PackageParser.Activity a = pkg.activities.get(i); 9074 mActivities.removeActivity(a, "activity"); 9075 if (DEBUG_REMOVE && chatty) { 9076 if (r == null) { 9077 r = new StringBuilder(256); 9078 } else { 9079 r.append(' '); 9080 } 9081 r.append(a.info.name); 9082 } 9083 } 9084 if (r != null) { 9085 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9086 } 9087 9088 N = pkg.permissions.size(); 9089 r = null; 9090 for (i=0; i<N; i++) { 9091 PackageParser.Permission p = pkg.permissions.get(i); 9092 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9093 if (bp == null) { 9094 bp = mSettings.mPermissionTrees.get(p.info.name); 9095 } 9096 if (bp != null && bp.perm == p) { 9097 bp.perm = null; 9098 if (DEBUG_REMOVE && chatty) { 9099 if (r == null) { 9100 r = new StringBuilder(256); 9101 } else { 9102 r.append(' '); 9103 } 9104 r.append(p.info.name); 9105 } 9106 } 9107 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9108 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9109 if (appOpPkgs != null) { 9110 appOpPkgs.remove(pkg.packageName); 9111 } 9112 } 9113 } 9114 if (r != null) { 9115 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9116 } 9117 9118 N = pkg.requestedPermissions.size(); 9119 r = null; 9120 for (i=0; i<N; i++) { 9121 String perm = pkg.requestedPermissions.get(i); 9122 BasePermission bp = mSettings.mPermissions.get(perm); 9123 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9124 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9125 if (appOpPkgs != null) { 9126 appOpPkgs.remove(pkg.packageName); 9127 if (appOpPkgs.isEmpty()) { 9128 mAppOpPermissionPackages.remove(perm); 9129 } 9130 } 9131 } 9132 } 9133 if (r != null) { 9134 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9135 } 9136 9137 N = pkg.instrumentation.size(); 9138 r = null; 9139 for (i=0; i<N; i++) { 9140 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9141 mInstrumentation.remove(a.getComponentName()); 9142 if (DEBUG_REMOVE && chatty) { 9143 if (r == null) { 9144 r = new StringBuilder(256); 9145 } else { 9146 r.append(' '); 9147 } 9148 r.append(a.info.name); 9149 } 9150 } 9151 if (r != null) { 9152 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9153 } 9154 9155 r = null; 9156 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9157 // Only system apps can hold shared libraries. 9158 if (pkg.libraryNames != null) { 9159 for (i=0; i<pkg.libraryNames.size(); i++) { 9160 String name = pkg.libraryNames.get(i); 9161 SharedLibraryEntry cur = mSharedLibraries.get(name); 9162 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9163 mSharedLibraries.remove(name); 9164 if (DEBUG_REMOVE && chatty) { 9165 if (r == null) { 9166 r = new StringBuilder(256); 9167 } else { 9168 r.append(' '); 9169 } 9170 r.append(name); 9171 } 9172 } 9173 } 9174 } 9175 } 9176 if (r != null) { 9177 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9178 } 9179 } 9180 9181 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9182 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9183 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9184 return true; 9185 } 9186 } 9187 return false; 9188 } 9189 9190 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9191 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9192 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9193 9194 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9195 // Update the parent permissions 9196 updatePermissionsLPw(pkg.packageName, pkg, flags); 9197 // Update the child permissions 9198 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9199 for (int i = 0; i < childCount; i++) { 9200 PackageParser.Package childPkg = pkg.childPackages.get(i); 9201 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9202 } 9203 } 9204 9205 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9206 int flags) { 9207 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9208 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9209 } 9210 9211 private void updatePermissionsLPw(String changingPkg, 9212 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9213 // Make sure there are no dangling permission trees. 9214 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9215 while (it.hasNext()) { 9216 final BasePermission bp = it.next(); 9217 if (bp.packageSetting == null) { 9218 // We may not yet have parsed the package, so just see if 9219 // we still know about its settings. 9220 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9221 } 9222 if (bp.packageSetting == null) { 9223 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9224 + " from package " + bp.sourcePackage); 9225 it.remove(); 9226 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9227 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9228 Slog.i(TAG, "Removing old permission tree: " + bp.name 9229 + " from package " + bp.sourcePackage); 9230 flags |= UPDATE_PERMISSIONS_ALL; 9231 it.remove(); 9232 } 9233 } 9234 } 9235 9236 // Make sure all dynamic permissions have been assigned to a package, 9237 // and make sure there are no dangling permissions. 9238 it = mSettings.mPermissions.values().iterator(); 9239 while (it.hasNext()) { 9240 final BasePermission bp = it.next(); 9241 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9242 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9243 + bp.name + " pkg=" + bp.sourcePackage 9244 + " info=" + bp.pendingInfo); 9245 if (bp.packageSetting == null && bp.pendingInfo != null) { 9246 final BasePermission tree = findPermissionTreeLP(bp.name); 9247 if (tree != null && tree.perm != null) { 9248 bp.packageSetting = tree.packageSetting; 9249 bp.perm = new PackageParser.Permission(tree.perm.owner, 9250 new PermissionInfo(bp.pendingInfo)); 9251 bp.perm.info.packageName = tree.perm.info.packageName; 9252 bp.perm.info.name = bp.name; 9253 bp.uid = tree.uid; 9254 } 9255 } 9256 } 9257 if (bp.packageSetting == null) { 9258 // We may not yet have parsed the package, so just see if 9259 // we still know about its settings. 9260 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9261 } 9262 if (bp.packageSetting == null) { 9263 Slog.w(TAG, "Removing dangling permission: " + bp.name 9264 + " from package " + bp.sourcePackage); 9265 it.remove(); 9266 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9267 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9268 Slog.i(TAG, "Removing old permission: " + bp.name 9269 + " from package " + bp.sourcePackage); 9270 flags |= UPDATE_PERMISSIONS_ALL; 9271 it.remove(); 9272 } 9273 } 9274 } 9275 9276 // Now update the permissions for all packages, in particular 9277 // replace the granted permissions of the system packages. 9278 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9279 for (PackageParser.Package pkg : mPackages.values()) { 9280 if (pkg != pkgInfo) { 9281 // Only replace for packages on requested volume 9282 final String volumeUuid = getVolumeUuidForPackage(pkg); 9283 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9284 && Objects.equals(replaceVolumeUuid, volumeUuid); 9285 grantPermissionsLPw(pkg, replace, changingPkg); 9286 } 9287 } 9288 } 9289 9290 if (pkgInfo != null) { 9291 // Only replace for packages on requested volume 9292 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9293 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9294 && Objects.equals(replaceVolumeUuid, volumeUuid); 9295 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9296 } 9297 } 9298 9299 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9300 String packageOfInterest) { 9301 // IMPORTANT: There are two types of permissions: install and runtime. 9302 // Install time permissions are granted when the app is installed to 9303 // all device users and users added in the future. Runtime permissions 9304 // are granted at runtime explicitly to specific users. Normal and signature 9305 // protected permissions are install time permissions. Dangerous permissions 9306 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9307 // otherwise they are runtime permissions. This function does not manage 9308 // runtime permissions except for the case an app targeting Lollipop MR1 9309 // being upgraded to target a newer SDK, in which case dangerous permissions 9310 // are transformed from install time to runtime ones. 9311 9312 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9313 if (ps == null) { 9314 return; 9315 } 9316 9317 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9318 9319 PermissionsState permissionsState = ps.getPermissionsState(); 9320 PermissionsState origPermissions = permissionsState; 9321 9322 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9323 9324 boolean runtimePermissionsRevoked = false; 9325 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9326 9327 boolean changedInstallPermission = false; 9328 9329 if (replace) { 9330 ps.installPermissionsFixed = false; 9331 if (!ps.isSharedUser()) { 9332 origPermissions = new PermissionsState(permissionsState); 9333 permissionsState.reset(); 9334 } else { 9335 // We need to know only about runtime permission changes since the 9336 // calling code always writes the install permissions state but 9337 // the runtime ones are written only if changed. The only cases of 9338 // changed runtime permissions here are promotion of an install to 9339 // runtime and revocation of a runtime from a shared user. 9340 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9341 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9342 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9343 runtimePermissionsRevoked = true; 9344 } 9345 } 9346 } 9347 9348 permissionsState.setGlobalGids(mGlobalGids); 9349 9350 final int N = pkg.requestedPermissions.size(); 9351 for (int i=0; i<N; i++) { 9352 final String name = pkg.requestedPermissions.get(i); 9353 final BasePermission bp = mSettings.mPermissions.get(name); 9354 9355 if (DEBUG_INSTALL) { 9356 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9357 } 9358 9359 if (bp == null || bp.packageSetting == null) { 9360 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9361 Slog.w(TAG, "Unknown permission " + name 9362 + " in package " + pkg.packageName); 9363 } 9364 continue; 9365 } 9366 9367 final String perm = bp.name; 9368 boolean allowedSig = false; 9369 int grant = GRANT_DENIED; 9370 9371 // Keep track of app op permissions. 9372 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9373 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9374 if (pkgs == null) { 9375 pkgs = new ArraySet<>(); 9376 mAppOpPermissionPackages.put(bp.name, pkgs); 9377 } 9378 pkgs.add(pkg.packageName); 9379 } 9380 9381 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9382 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9383 >= Build.VERSION_CODES.M; 9384 switch (level) { 9385 case PermissionInfo.PROTECTION_NORMAL: { 9386 // For all apps normal permissions are install time ones. 9387 grant = GRANT_INSTALL; 9388 } break; 9389 9390 case PermissionInfo.PROTECTION_DANGEROUS: { 9391 // If a permission review is required for legacy apps we represent 9392 // their permissions as always granted runtime ones since we need 9393 // to keep the review required permission flag per user while an 9394 // install permission's state is shared across all users. 9395 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9396 // For legacy apps dangerous permissions are install time ones. 9397 grant = GRANT_INSTALL; 9398 } else if (origPermissions.hasInstallPermission(bp.name)) { 9399 // For legacy apps that became modern, install becomes runtime. 9400 grant = GRANT_UPGRADE; 9401 } else if (mPromoteSystemApps 9402 && isSystemApp(ps) 9403 && mExistingSystemPackages.contains(ps.name)) { 9404 // For legacy system apps, install becomes runtime. 9405 // We cannot check hasInstallPermission() for system apps since those 9406 // permissions were granted implicitly and not persisted pre-M. 9407 grant = GRANT_UPGRADE; 9408 } else { 9409 // For modern apps keep runtime permissions unchanged. 9410 grant = GRANT_RUNTIME; 9411 } 9412 } break; 9413 9414 case PermissionInfo.PROTECTION_SIGNATURE: { 9415 // For all apps signature permissions are install time ones. 9416 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9417 if (allowedSig) { 9418 grant = GRANT_INSTALL; 9419 } 9420 } break; 9421 } 9422 9423 if (DEBUG_INSTALL) { 9424 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9425 } 9426 9427 if (grant != GRANT_DENIED) { 9428 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9429 // If this is an existing, non-system package, then 9430 // we can't add any new permissions to it. 9431 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9432 // Except... if this is a permission that was added 9433 // to the platform (note: need to only do this when 9434 // updating the platform). 9435 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9436 grant = GRANT_DENIED; 9437 } 9438 } 9439 } 9440 9441 switch (grant) { 9442 case GRANT_INSTALL: { 9443 // Revoke this as runtime permission to handle the case of 9444 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 9445 for (int userId : UserManagerService.getInstance().getUserIds()) { 9446 if (origPermissions.getRuntimePermissionState( 9447 bp.name, userId) != null) { 9448 // Revoke the runtime permission and clear the flags. 9449 origPermissions.revokeRuntimePermission(bp, userId); 9450 origPermissions.updatePermissionFlags(bp, userId, 9451 PackageManager.MASK_PERMISSION_FLAGS, 0); 9452 // If we revoked a permission permission, we have to write. 9453 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9454 changedRuntimePermissionUserIds, userId); 9455 } 9456 } 9457 // Grant an install permission. 9458 if (permissionsState.grantInstallPermission(bp) != 9459 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9460 changedInstallPermission = true; 9461 } 9462 } break; 9463 9464 case GRANT_RUNTIME: { 9465 // Grant previously granted runtime permissions. 9466 for (int userId : UserManagerService.getInstance().getUserIds()) { 9467 PermissionState permissionState = origPermissions 9468 .getRuntimePermissionState(bp.name, userId); 9469 int flags = permissionState != null 9470 ? permissionState.getFlags() : 0; 9471 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9472 if (permissionsState.grantRuntimePermission(bp, userId) == 9473 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9474 // If we cannot put the permission as it was, we have to write. 9475 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9476 changedRuntimePermissionUserIds, userId); 9477 } 9478 // If the app supports runtime permissions no need for a review. 9479 if (Build.PERMISSIONS_REVIEW_REQUIRED 9480 && appSupportsRuntimePermissions 9481 && (flags & PackageManager 9482 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9483 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9484 // Since we changed the flags, we have to write. 9485 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9486 changedRuntimePermissionUserIds, userId); 9487 } 9488 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9489 && !appSupportsRuntimePermissions) { 9490 // For legacy apps that need a permission review, every new 9491 // runtime permission is granted but it is pending a review. 9492 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9493 permissionsState.grantRuntimePermission(bp, userId); 9494 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9495 // We changed the permission and flags, hence have to write. 9496 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9497 changedRuntimePermissionUserIds, userId); 9498 } 9499 } 9500 // Propagate the permission flags. 9501 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9502 } 9503 } break; 9504 9505 case GRANT_UPGRADE: { 9506 // Grant runtime permissions for a previously held install permission. 9507 PermissionState permissionState = origPermissions 9508 .getInstallPermissionState(bp.name); 9509 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9510 9511 if (origPermissions.revokeInstallPermission(bp) 9512 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9513 // We will be transferring the permission flags, so clear them. 9514 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9515 PackageManager.MASK_PERMISSION_FLAGS, 0); 9516 changedInstallPermission = true; 9517 } 9518 9519 // If the permission is not to be promoted to runtime we ignore it and 9520 // also its other flags as they are not applicable to install permissions. 9521 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9522 for (int userId : currentUserIds) { 9523 if (permissionsState.grantRuntimePermission(bp, userId) != 9524 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9525 // Transfer the permission flags. 9526 permissionsState.updatePermissionFlags(bp, userId, 9527 flags, flags); 9528 // If we granted the permission, we have to write. 9529 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9530 changedRuntimePermissionUserIds, userId); 9531 } 9532 } 9533 } 9534 } break; 9535 9536 default: { 9537 if (packageOfInterest == null 9538 || packageOfInterest.equals(pkg.packageName)) { 9539 Slog.w(TAG, "Not granting permission " + perm 9540 + " to package " + pkg.packageName 9541 + " because it was previously installed without"); 9542 } 9543 } break; 9544 } 9545 } else { 9546 if (permissionsState.revokeInstallPermission(bp) != 9547 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9548 // Also drop the permission flags. 9549 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9550 PackageManager.MASK_PERMISSION_FLAGS, 0); 9551 changedInstallPermission = true; 9552 Slog.i(TAG, "Un-granting permission " + perm 9553 + " from package " + pkg.packageName 9554 + " (protectionLevel=" + bp.protectionLevel 9555 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9556 + ")"); 9557 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9558 // Don't print warning for app op permissions, since it is fine for them 9559 // not to be granted, there is a UI for the user to decide. 9560 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9561 Slog.w(TAG, "Not granting permission " + perm 9562 + " to package " + pkg.packageName 9563 + " (protectionLevel=" + bp.protectionLevel 9564 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9565 + ")"); 9566 } 9567 } 9568 } 9569 } 9570 9571 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9572 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9573 // This is the first that we have heard about this package, so the 9574 // permissions we have now selected are fixed until explicitly 9575 // changed. 9576 ps.installPermissionsFixed = true; 9577 } 9578 9579 // Persist the runtime permissions state for users with changes. If permissions 9580 // were revoked because no app in the shared user declares them we have to 9581 // write synchronously to avoid losing runtime permissions state. 9582 for (int userId : changedRuntimePermissionUserIds) { 9583 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9584 } 9585 9586 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9587 } 9588 9589 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9590 boolean allowed = false; 9591 final int NP = PackageParser.NEW_PERMISSIONS.length; 9592 for (int ip=0; ip<NP; ip++) { 9593 final PackageParser.NewPermissionInfo npi 9594 = PackageParser.NEW_PERMISSIONS[ip]; 9595 if (npi.name.equals(perm) 9596 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9597 allowed = true; 9598 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9599 + pkg.packageName); 9600 break; 9601 } 9602 } 9603 return allowed; 9604 } 9605 9606 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9607 BasePermission bp, PermissionsState origPermissions) { 9608 boolean allowed; 9609 allowed = (compareSignatures( 9610 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9611 == PackageManager.SIGNATURE_MATCH) 9612 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9613 == PackageManager.SIGNATURE_MATCH); 9614 if (!allowed && (bp.protectionLevel 9615 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9616 if (isSystemApp(pkg)) { 9617 // For updated system applications, a system permission 9618 // is granted only if it had been defined by the original application. 9619 if (pkg.isUpdatedSystemApp()) { 9620 final PackageSetting sysPs = mSettings 9621 .getDisabledSystemPkgLPr(pkg.packageName); 9622 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9623 // If the original was granted this permission, we take 9624 // that grant decision as read and propagate it to the 9625 // update. 9626 if (sysPs.isPrivileged()) { 9627 allowed = true; 9628 } 9629 } else { 9630 // The system apk may have been updated with an older 9631 // version of the one on the data partition, but which 9632 // granted a new system permission that it didn't have 9633 // before. In this case we do want to allow the app to 9634 // now get the new permission if the ancestral apk is 9635 // privileged to get it. 9636 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9637 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9638 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9639 allowed = true; 9640 break; 9641 } 9642 } 9643 } 9644 // Also if a privileged parent package on the system image or any of 9645 // its children requested a privileged permission, the updated child 9646 // packages can also get the permission. 9647 if (pkg.parentPackage != null) { 9648 final PackageSetting disabledSysParentPs = mSettings 9649 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 9650 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 9651 && disabledSysParentPs.isPrivileged()) { 9652 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 9653 allowed = true; 9654 } else if (disabledSysParentPs.pkg.childPackages != null) { 9655 final int count = disabledSysParentPs.pkg.childPackages.size(); 9656 for (int i = 0; i < count; i++) { 9657 PackageParser.Package disabledSysChildPkg = 9658 disabledSysParentPs.pkg.childPackages.get(i); 9659 if (isPackageRequestingPermission(disabledSysChildPkg, 9660 perm)) { 9661 allowed = true; 9662 break; 9663 } 9664 } 9665 } 9666 } 9667 } 9668 } 9669 } else { 9670 allowed = isPrivilegedApp(pkg); 9671 } 9672 } 9673 } 9674 if (!allowed) { 9675 if (!allowed && (bp.protectionLevel 9676 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9677 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9678 // If this was a previously normal/dangerous permission that got moved 9679 // to a system permission as part of the runtime permission redesign, then 9680 // we still want to blindly grant it to old apps. 9681 allowed = true; 9682 } 9683 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9684 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9685 // If this permission is to be granted to the system installer and 9686 // this app is an installer, then it gets the permission. 9687 allowed = true; 9688 } 9689 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9690 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9691 // If this permission is to be granted to the system verifier and 9692 // this app is a verifier, then it gets the permission. 9693 allowed = true; 9694 } 9695 if (!allowed && (bp.protectionLevel 9696 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9697 && isSystemApp(pkg)) { 9698 // Any pre-installed system app is allowed to get this permission. 9699 allowed = true; 9700 } 9701 if (!allowed && (bp.protectionLevel 9702 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9703 // For development permissions, a development permission 9704 // is granted only if it was already granted. 9705 allowed = origPermissions.hasInstallPermission(perm); 9706 } 9707 } 9708 return allowed; 9709 } 9710 9711 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 9712 final int permCount = pkg.requestedPermissions.size(); 9713 for (int j = 0; j < permCount; j++) { 9714 String requestedPermission = pkg.requestedPermissions.get(j); 9715 if (permission.equals(requestedPermission)) { 9716 return true; 9717 } 9718 } 9719 return false; 9720 } 9721 9722 final class ActivityIntentResolver 9723 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9724 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9725 boolean defaultOnly, int userId) { 9726 if (!sUserManager.exists(userId)) return null; 9727 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9728 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9729 } 9730 9731 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9732 int userId) { 9733 if (!sUserManager.exists(userId)) return null; 9734 mFlags = flags; 9735 return super.queryIntent(intent, resolvedType, 9736 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9737 } 9738 9739 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9740 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9741 if (!sUserManager.exists(userId)) return null; 9742 if (packageActivities == null) { 9743 return null; 9744 } 9745 mFlags = flags; 9746 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9747 final int N = packageActivities.size(); 9748 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9749 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9750 9751 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9752 for (int i = 0; i < N; ++i) { 9753 intentFilters = packageActivities.get(i).intents; 9754 if (intentFilters != null && intentFilters.size() > 0) { 9755 PackageParser.ActivityIntentInfo[] array = 9756 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9757 intentFilters.toArray(array); 9758 listCut.add(array); 9759 } 9760 } 9761 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9762 } 9763 9764 public final void addActivity(PackageParser.Activity a, String type) { 9765 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 9766 mActivities.put(a.getComponentName(), a); 9767 if (DEBUG_SHOW_INFO) 9768 Log.v( 9769 TAG, " " + type + " " + 9770 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 9771 if (DEBUG_SHOW_INFO) 9772 Log.v(TAG, " Class=" + a.info.name); 9773 final int NI = a.intents.size(); 9774 for (int j=0; j<NI; j++) { 9775 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9776 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 9777 intent.setPriority(0); 9778 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 9779 + a.className + " with priority > 0, forcing to 0"); 9780 } 9781 if (DEBUG_SHOW_INFO) { 9782 Log.v(TAG, " IntentFilter:"); 9783 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9784 } 9785 if (!intent.debugCheck()) { 9786 Log.w(TAG, "==> For Activity " + a.info.name); 9787 } 9788 addFilter(intent); 9789 } 9790 } 9791 9792 public final void removeActivity(PackageParser.Activity a, String type) { 9793 mActivities.remove(a.getComponentName()); 9794 if (DEBUG_SHOW_INFO) { 9795 Log.v(TAG, " " + type + " " 9796 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 9797 : a.info.name) + ":"); 9798 Log.v(TAG, " Class=" + a.info.name); 9799 } 9800 final int NI = a.intents.size(); 9801 for (int j=0; j<NI; j++) { 9802 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9803 if (DEBUG_SHOW_INFO) { 9804 Log.v(TAG, " IntentFilter:"); 9805 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9806 } 9807 removeFilter(intent); 9808 } 9809 } 9810 9811 @Override 9812 protected boolean allowFilterResult( 9813 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 9814 ActivityInfo filterAi = filter.activity.info; 9815 for (int i=dest.size()-1; i>=0; i--) { 9816 ActivityInfo destAi = dest.get(i).activityInfo; 9817 if (destAi.name == filterAi.name 9818 && destAi.packageName == filterAi.packageName) { 9819 return false; 9820 } 9821 } 9822 return true; 9823 } 9824 9825 @Override 9826 protected ActivityIntentInfo[] newArray(int size) { 9827 return new ActivityIntentInfo[size]; 9828 } 9829 9830 @Override 9831 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 9832 if (!sUserManager.exists(userId)) return true; 9833 PackageParser.Package p = filter.activity.owner; 9834 if (p != null) { 9835 PackageSetting ps = (PackageSetting)p.mExtras; 9836 if (ps != null) { 9837 // System apps are never considered stopped for purposes of 9838 // filtering, because there may be no way for the user to 9839 // actually re-launch them. 9840 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 9841 && ps.getStopped(userId); 9842 } 9843 } 9844 return false; 9845 } 9846 9847 @Override 9848 protected boolean isPackageForFilter(String packageName, 9849 PackageParser.ActivityIntentInfo info) { 9850 return packageName.equals(info.activity.owner.packageName); 9851 } 9852 9853 @Override 9854 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 9855 int match, int userId) { 9856 if (!sUserManager.exists(userId)) return null; 9857 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 9858 return null; 9859 } 9860 final PackageParser.Activity activity = info.activity; 9861 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 9862 if (ps == null) { 9863 return null; 9864 } 9865 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 9866 ps.readUserState(userId), userId); 9867 if (ai == null) { 9868 return null; 9869 } 9870 final ResolveInfo res = new ResolveInfo(); 9871 res.activityInfo = ai; 9872 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9873 res.filter = info; 9874 } 9875 if (info != null) { 9876 res.handleAllWebDataURI = info.handleAllWebDataURI(); 9877 } 9878 res.priority = info.getPriority(); 9879 res.preferredOrder = activity.owner.mPreferredOrder; 9880 //System.out.println("Result: " + res.activityInfo.className + 9881 // " = " + res.priority); 9882 res.match = match; 9883 res.isDefault = info.hasDefault; 9884 res.labelRes = info.labelRes; 9885 res.nonLocalizedLabel = info.nonLocalizedLabel; 9886 if (userNeedsBadging(userId)) { 9887 res.noResourceId = true; 9888 } else { 9889 res.icon = info.icon; 9890 } 9891 res.iconResourceId = info.icon; 9892 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9893 return res; 9894 } 9895 9896 @Override 9897 protected void sortResults(List<ResolveInfo> results) { 9898 Collections.sort(results, mResolvePrioritySorter); 9899 } 9900 9901 @Override 9902 protected void dumpFilter(PrintWriter out, String prefix, 9903 PackageParser.ActivityIntentInfo filter) { 9904 out.print(prefix); out.print( 9905 Integer.toHexString(System.identityHashCode(filter.activity))); 9906 out.print(' '); 9907 filter.activity.printComponentShortName(out); 9908 out.print(" filter "); 9909 out.println(Integer.toHexString(System.identityHashCode(filter))); 9910 } 9911 9912 @Override 9913 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9914 return filter.activity; 9915 } 9916 9917 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9918 PackageParser.Activity activity = (PackageParser.Activity)label; 9919 out.print(prefix); out.print( 9920 Integer.toHexString(System.identityHashCode(activity))); 9921 out.print(' '); 9922 activity.printComponentShortName(out); 9923 if (count > 1) { 9924 out.print(" ("); out.print(count); out.print(" filters)"); 9925 } 9926 out.println(); 9927 } 9928 9929// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9930// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9931// final List<ResolveInfo> retList = Lists.newArrayList(); 9932// while (i.hasNext()) { 9933// final ResolveInfo resolveInfo = i.next(); 9934// if (isEnabledLP(resolveInfo.activityInfo)) { 9935// retList.add(resolveInfo); 9936// } 9937// } 9938// return retList; 9939// } 9940 9941 // Keys are String (activity class name), values are Activity. 9942 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9943 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9944 private int mFlags; 9945 } 9946 9947 private final class ServiceIntentResolver 9948 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9949 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9950 boolean defaultOnly, int userId) { 9951 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9952 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9953 } 9954 9955 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9956 int userId) { 9957 if (!sUserManager.exists(userId)) return null; 9958 mFlags = flags; 9959 return super.queryIntent(intent, resolvedType, 9960 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9961 } 9962 9963 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9964 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9965 if (!sUserManager.exists(userId)) return null; 9966 if (packageServices == null) { 9967 return null; 9968 } 9969 mFlags = flags; 9970 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9971 final int N = packageServices.size(); 9972 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9973 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9974 9975 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9976 for (int i = 0; i < N; ++i) { 9977 intentFilters = packageServices.get(i).intents; 9978 if (intentFilters != null && intentFilters.size() > 0) { 9979 PackageParser.ServiceIntentInfo[] array = 9980 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9981 intentFilters.toArray(array); 9982 listCut.add(array); 9983 } 9984 } 9985 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9986 } 9987 9988 public final void addService(PackageParser.Service s) { 9989 mServices.put(s.getComponentName(), s); 9990 if (DEBUG_SHOW_INFO) { 9991 Log.v(TAG, " " 9992 + (s.info.nonLocalizedLabel != null 9993 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9994 Log.v(TAG, " Class=" + s.info.name); 9995 } 9996 final int NI = s.intents.size(); 9997 int j; 9998 for (j=0; j<NI; j++) { 9999 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10000 if (DEBUG_SHOW_INFO) { 10001 Log.v(TAG, " IntentFilter:"); 10002 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10003 } 10004 if (!intent.debugCheck()) { 10005 Log.w(TAG, "==> For Service " + s.info.name); 10006 } 10007 addFilter(intent); 10008 } 10009 } 10010 10011 public final void removeService(PackageParser.Service s) { 10012 mServices.remove(s.getComponentName()); 10013 if (DEBUG_SHOW_INFO) { 10014 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10015 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10016 Log.v(TAG, " Class=" + s.info.name); 10017 } 10018 final int NI = s.intents.size(); 10019 int j; 10020 for (j=0; j<NI; j++) { 10021 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10022 if (DEBUG_SHOW_INFO) { 10023 Log.v(TAG, " IntentFilter:"); 10024 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10025 } 10026 removeFilter(intent); 10027 } 10028 } 10029 10030 @Override 10031 protected boolean allowFilterResult( 10032 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10033 ServiceInfo filterSi = filter.service.info; 10034 for (int i=dest.size()-1; i>=0; i--) { 10035 ServiceInfo destAi = dest.get(i).serviceInfo; 10036 if (destAi.name == filterSi.name 10037 && destAi.packageName == filterSi.packageName) { 10038 return false; 10039 } 10040 } 10041 return true; 10042 } 10043 10044 @Override 10045 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10046 return new PackageParser.ServiceIntentInfo[size]; 10047 } 10048 10049 @Override 10050 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10051 if (!sUserManager.exists(userId)) return true; 10052 PackageParser.Package p = filter.service.owner; 10053 if (p != null) { 10054 PackageSetting ps = (PackageSetting)p.mExtras; 10055 if (ps != null) { 10056 // System apps are never considered stopped for purposes of 10057 // filtering, because there may be no way for the user to 10058 // actually re-launch them. 10059 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10060 && ps.getStopped(userId); 10061 } 10062 } 10063 return false; 10064 } 10065 10066 @Override 10067 protected boolean isPackageForFilter(String packageName, 10068 PackageParser.ServiceIntentInfo info) { 10069 return packageName.equals(info.service.owner.packageName); 10070 } 10071 10072 @Override 10073 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10074 int match, int userId) { 10075 if (!sUserManager.exists(userId)) return null; 10076 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10077 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10078 return null; 10079 } 10080 final PackageParser.Service service = info.service; 10081 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10082 if (ps == null) { 10083 return null; 10084 } 10085 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10086 ps.readUserState(userId), userId); 10087 if (si == null) { 10088 return null; 10089 } 10090 final ResolveInfo res = new ResolveInfo(); 10091 res.serviceInfo = si; 10092 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10093 res.filter = filter; 10094 } 10095 res.priority = info.getPriority(); 10096 res.preferredOrder = service.owner.mPreferredOrder; 10097 res.match = match; 10098 res.isDefault = info.hasDefault; 10099 res.labelRes = info.labelRes; 10100 res.nonLocalizedLabel = info.nonLocalizedLabel; 10101 res.icon = info.icon; 10102 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10103 return res; 10104 } 10105 10106 @Override 10107 protected void sortResults(List<ResolveInfo> results) { 10108 Collections.sort(results, mResolvePrioritySorter); 10109 } 10110 10111 @Override 10112 protected void dumpFilter(PrintWriter out, String prefix, 10113 PackageParser.ServiceIntentInfo filter) { 10114 out.print(prefix); out.print( 10115 Integer.toHexString(System.identityHashCode(filter.service))); 10116 out.print(' '); 10117 filter.service.printComponentShortName(out); 10118 out.print(" filter "); 10119 out.println(Integer.toHexString(System.identityHashCode(filter))); 10120 } 10121 10122 @Override 10123 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10124 return filter.service; 10125 } 10126 10127 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10128 PackageParser.Service service = (PackageParser.Service)label; 10129 out.print(prefix); out.print( 10130 Integer.toHexString(System.identityHashCode(service))); 10131 out.print(' '); 10132 service.printComponentShortName(out); 10133 if (count > 1) { 10134 out.print(" ("); out.print(count); out.print(" filters)"); 10135 } 10136 out.println(); 10137 } 10138 10139// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10140// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10141// final List<ResolveInfo> retList = Lists.newArrayList(); 10142// while (i.hasNext()) { 10143// final ResolveInfo resolveInfo = (ResolveInfo) i; 10144// if (isEnabledLP(resolveInfo.serviceInfo)) { 10145// retList.add(resolveInfo); 10146// } 10147// } 10148// return retList; 10149// } 10150 10151 // Keys are String (activity class name), values are Activity. 10152 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10153 = new ArrayMap<ComponentName, PackageParser.Service>(); 10154 private int mFlags; 10155 }; 10156 10157 private final class ProviderIntentResolver 10158 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10159 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10160 boolean defaultOnly, int userId) { 10161 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10162 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10163 } 10164 10165 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10166 int userId) { 10167 if (!sUserManager.exists(userId)) 10168 return null; 10169 mFlags = flags; 10170 return super.queryIntent(intent, resolvedType, 10171 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10172 } 10173 10174 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10175 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10176 if (!sUserManager.exists(userId)) 10177 return null; 10178 if (packageProviders == null) { 10179 return null; 10180 } 10181 mFlags = flags; 10182 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10183 final int N = packageProviders.size(); 10184 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10185 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10186 10187 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10188 for (int i = 0; i < N; ++i) { 10189 intentFilters = packageProviders.get(i).intents; 10190 if (intentFilters != null && intentFilters.size() > 0) { 10191 PackageParser.ProviderIntentInfo[] array = 10192 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10193 intentFilters.toArray(array); 10194 listCut.add(array); 10195 } 10196 } 10197 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10198 } 10199 10200 public final void addProvider(PackageParser.Provider p) { 10201 if (mProviders.containsKey(p.getComponentName())) { 10202 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10203 return; 10204 } 10205 10206 mProviders.put(p.getComponentName(), p); 10207 if (DEBUG_SHOW_INFO) { 10208 Log.v(TAG, " " 10209 + (p.info.nonLocalizedLabel != null 10210 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10211 Log.v(TAG, " Class=" + p.info.name); 10212 } 10213 final int NI = p.intents.size(); 10214 int j; 10215 for (j = 0; j < NI; j++) { 10216 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10217 if (DEBUG_SHOW_INFO) { 10218 Log.v(TAG, " IntentFilter:"); 10219 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10220 } 10221 if (!intent.debugCheck()) { 10222 Log.w(TAG, "==> For Provider " + p.info.name); 10223 } 10224 addFilter(intent); 10225 } 10226 } 10227 10228 public final void removeProvider(PackageParser.Provider p) { 10229 mProviders.remove(p.getComponentName()); 10230 if (DEBUG_SHOW_INFO) { 10231 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10232 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10233 Log.v(TAG, " Class=" + p.info.name); 10234 } 10235 final int NI = p.intents.size(); 10236 int j; 10237 for (j = 0; j < NI; j++) { 10238 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10239 if (DEBUG_SHOW_INFO) { 10240 Log.v(TAG, " IntentFilter:"); 10241 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10242 } 10243 removeFilter(intent); 10244 } 10245 } 10246 10247 @Override 10248 protected boolean allowFilterResult( 10249 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10250 ProviderInfo filterPi = filter.provider.info; 10251 for (int i = dest.size() - 1; i >= 0; i--) { 10252 ProviderInfo destPi = dest.get(i).providerInfo; 10253 if (destPi.name == filterPi.name 10254 && destPi.packageName == filterPi.packageName) { 10255 return false; 10256 } 10257 } 10258 return true; 10259 } 10260 10261 @Override 10262 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10263 return new PackageParser.ProviderIntentInfo[size]; 10264 } 10265 10266 @Override 10267 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10268 if (!sUserManager.exists(userId)) 10269 return true; 10270 PackageParser.Package p = filter.provider.owner; 10271 if (p != null) { 10272 PackageSetting ps = (PackageSetting) p.mExtras; 10273 if (ps != null) { 10274 // System apps are never considered stopped for purposes of 10275 // filtering, because there may be no way for the user to 10276 // actually re-launch them. 10277 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10278 && ps.getStopped(userId); 10279 } 10280 } 10281 return false; 10282 } 10283 10284 @Override 10285 protected boolean isPackageForFilter(String packageName, 10286 PackageParser.ProviderIntentInfo info) { 10287 return packageName.equals(info.provider.owner.packageName); 10288 } 10289 10290 @Override 10291 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10292 int match, int userId) { 10293 if (!sUserManager.exists(userId)) 10294 return null; 10295 final PackageParser.ProviderIntentInfo info = filter; 10296 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10297 return null; 10298 } 10299 final PackageParser.Provider provider = info.provider; 10300 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10301 if (ps == null) { 10302 return null; 10303 } 10304 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10305 ps.readUserState(userId), userId); 10306 if (pi == null) { 10307 return null; 10308 } 10309 final ResolveInfo res = new ResolveInfo(); 10310 res.providerInfo = pi; 10311 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10312 res.filter = filter; 10313 } 10314 res.priority = info.getPriority(); 10315 res.preferredOrder = provider.owner.mPreferredOrder; 10316 res.match = match; 10317 res.isDefault = info.hasDefault; 10318 res.labelRes = info.labelRes; 10319 res.nonLocalizedLabel = info.nonLocalizedLabel; 10320 res.icon = info.icon; 10321 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10322 return res; 10323 } 10324 10325 @Override 10326 protected void sortResults(List<ResolveInfo> results) { 10327 Collections.sort(results, mResolvePrioritySorter); 10328 } 10329 10330 @Override 10331 protected void dumpFilter(PrintWriter out, String prefix, 10332 PackageParser.ProviderIntentInfo filter) { 10333 out.print(prefix); 10334 out.print( 10335 Integer.toHexString(System.identityHashCode(filter.provider))); 10336 out.print(' '); 10337 filter.provider.printComponentShortName(out); 10338 out.print(" filter "); 10339 out.println(Integer.toHexString(System.identityHashCode(filter))); 10340 } 10341 10342 @Override 10343 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 10344 return filter.provider; 10345 } 10346 10347 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10348 PackageParser.Provider provider = (PackageParser.Provider)label; 10349 out.print(prefix); out.print( 10350 Integer.toHexString(System.identityHashCode(provider))); 10351 out.print(' '); 10352 provider.printComponentShortName(out); 10353 if (count > 1) { 10354 out.print(" ("); out.print(count); out.print(" filters)"); 10355 } 10356 out.println(); 10357 } 10358 10359 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 10360 = new ArrayMap<ComponentName, PackageParser.Provider>(); 10361 private int mFlags; 10362 } 10363 10364 private static final class EphemeralIntentResolver 10365 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 10366 @Override 10367 protected EphemeralResolveIntentInfo[] newArray(int size) { 10368 return new EphemeralResolveIntentInfo[size]; 10369 } 10370 10371 @Override 10372 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 10373 return true; 10374 } 10375 10376 @Override 10377 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 10378 int userId) { 10379 if (!sUserManager.exists(userId)) { 10380 return null; 10381 } 10382 return info.getEphemeralResolveInfo(); 10383 } 10384 } 10385 10386 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 10387 new Comparator<ResolveInfo>() { 10388 public int compare(ResolveInfo r1, ResolveInfo r2) { 10389 int v1 = r1.priority; 10390 int v2 = r2.priority; 10391 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 10392 if (v1 != v2) { 10393 return (v1 > v2) ? -1 : 1; 10394 } 10395 v1 = r1.preferredOrder; 10396 v2 = r2.preferredOrder; 10397 if (v1 != v2) { 10398 return (v1 > v2) ? -1 : 1; 10399 } 10400 if (r1.isDefault != r2.isDefault) { 10401 return r1.isDefault ? -1 : 1; 10402 } 10403 v1 = r1.match; 10404 v2 = r2.match; 10405 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 10406 if (v1 != v2) { 10407 return (v1 > v2) ? -1 : 1; 10408 } 10409 if (r1.system != r2.system) { 10410 return r1.system ? -1 : 1; 10411 } 10412 if (r1.activityInfo != null) { 10413 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 10414 } 10415 if (r1.serviceInfo != null) { 10416 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 10417 } 10418 if (r1.providerInfo != null) { 10419 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 10420 } 10421 return 0; 10422 } 10423 }; 10424 10425 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 10426 new Comparator<ProviderInfo>() { 10427 public int compare(ProviderInfo p1, ProviderInfo p2) { 10428 final int v1 = p1.initOrder; 10429 final int v2 = p2.initOrder; 10430 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 10431 } 10432 }; 10433 10434 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 10435 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 10436 final int[] userIds) { 10437 mHandler.post(new Runnable() { 10438 @Override 10439 public void run() { 10440 try { 10441 final IActivityManager am = ActivityManagerNative.getDefault(); 10442 if (am == null) return; 10443 final int[] resolvedUserIds; 10444 if (userIds == null) { 10445 resolvedUserIds = am.getRunningUserIds(); 10446 } else { 10447 resolvedUserIds = userIds; 10448 } 10449 for (int id : resolvedUserIds) { 10450 final Intent intent = new Intent(action, 10451 pkg != null ? Uri.fromParts("package", pkg, null) : null); 10452 if (extras != null) { 10453 intent.putExtras(extras); 10454 } 10455 if (targetPkg != null) { 10456 intent.setPackage(targetPkg); 10457 } 10458 // Modify the UID when posting to other users 10459 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 10460 if (uid > 0 && UserHandle.getUserId(uid) != id) { 10461 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 10462 intent.putExtra(Intent.EXTRA_UID, uid); 10463 } 10464 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 10465 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 10466 if (DEBUG_BROADCASTS) { 10467 RuntimeException here = new RuntimeException("here"); 10468 here.fillInStackTrace(); 10469 Slog.d(TAG, "Sending to user " + id + ": " 10470 + intent.toShortString(false, true, false, false) 10471 + " " + intent.getExtras(), here); 10472 } 10473 am.broadcastIntent(null, intent, null, finishedReceiver, 10474 0, null, null, null, android.app.AppOpsManager.OP_NONE, 10475 null, finishedReceiver != null, false, id); 10476 } 10477 } catch (RemoteException ex) { 10478 } 10479 } 10480 }); 10481 } 10482 10483 /** 10484 * Check if the external storage media is available. This is true if there 10485 * is a mounted external storage medium or if the external storage is 10486 * emulated. 10487 */ 10488 private boolean isExternalMediaAvailable() { 10489 return mMediaMounted || Environment.isExternalStorageEmulated(); 10490 } 10491 10492 @Override 10493 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 10494 // writer 10495 synchronized (mPackages) { 10496 if (!isExternalMediaAvailable()) { 10497 // If the external storage is no longer mounted at this point, 10498 // the caller may not have been able to delete all of this 10499 // packages files and can not delete any more. Bail. 10500 return null; 10501 } 10502 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 10503 if (lastPackage != null) { 10504 pkgs.remove(lastPackage); 10505 } 10506 if (pkgs.size() > 0) { 10507 return pkgs.get(0); 10508 } 10509 } 10510 return null; 10511 } 10512 10513 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 10514 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 10515 userId, andCode ? 1 : 0, packageName); 10516 if (mSystemReady) { 10517 msg.sendToTarget(); 10518 } else { 10519 if (mPostSystemReadyMessages == null) { 10520 mPostSystemReadyMessages = new ArrayList<>(); 10521 } 10522 mPostSystemReadyMessages.add(msg); 10523 } 10524 } 10525 10526 void startCleaningPackages() { 10527 // reader 10528 if (!isExternalMediaAvailable()) { 10529 return; 10530 } 10531 synchronized (mPackages) { 10532 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 10533 return; 10534 } 10535 } 10536 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 10537 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 10538 IActivityManager am = ActivityManagerNative.getDefault(); 10539 if (am != null) { 10540 try { 10541 am.startService(null, intent, null, mContext.getOpPackageName(), 10542 UserHandle.USER_SYSTEM); 10543 } catch (RemoteException e) { 10544 } 10545 } 10546 } 10547 10548 @Override 10549 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 10550 int installFlags, String installerPackageName, int userId) { 10551 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 10552 10553 final int callingUid = Binder.getCallingUid(); 10554 enforceCrossUserPermission(callingUid, userId, 10555 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 10556 10557 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10558 try { 10559 if (observer != null) { 10560 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 10561 } 10562 } catch (RemoteException re) { 10563 } 10564 return; 10565 } 10566 10567 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 10568 installFlags |= PackageManager.INSTALL_FROM_ADB; 10569 10570 } else { 10571 // Caller holds INSTALL_PACKAGES permission, so we're less strict 10572 // about installerPackageName. 10573 10574 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 10575 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 10576 } 10577 10578 UserHandle user; 10579 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 10580 user = UserHandle.ALL; 10581 } else { 10582 user = new UserHandle(userId); 10583 } 10584 10585 // Only system components can circumvent runtime permissions when installing. 10586 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 10587 && mContext.checkCallingOrSelfPermission(Manifest.permission 10588 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 10589 throw new SecurityException("You need the " 10590 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 10591 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 10592 } 10593 10594 final File originFile = new File(originPath); 10595 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 10596 10597 final Message msg = mHandler.obtainMessage(INIT_COPY); 10598 final VerificationInfo verificationInfo = new VerificationInfo( 10599 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 10600 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 10601 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 10602 null /*packageAbiOverride*/, null /*grantedPermissions*/); 10603 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 10604 msg.obj = params; 10605 10606 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 10607 System.identityHashCode(msg.obj)); 10608 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10609 System.identityHashCode(msg.obj)); 10610 10611 mHandler.sendMessage(msg); 10612 } 10613 10614 void installStage(String packageName, File stagedDir, String stagedCid, 10615 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 10616 String installerPackageName, int installerUid, UserHandle user) { 10617 if (DEBUG_EPHEMERAL) { 10618 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10619 Slog.d(TAG, "Ephemeral install of " + packageName); 10620 } 10621 } 10622 final VerificationInfo verificationInfo = new VerificationInfo( 10623 sessionParams.originatingUri, sessionParams.referrerUri, 10624 sessionParams.originatingUid, installerUid); 10625 10626 final OriginInfo origin; 10627 if (stagedDir != null) { 10628 origin = OriginInfo.fromStagedFile(stagedDir); 10629 } else { 10630 origin = OriginInfo.fromStagedContainer(stagedCid); 10631 } 10632 10633 final Message msg = mHandler.obtainMessage(INIT_COPY); 10634 final InstallParams params = new InstallParams(origin, null, observer, 10635 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 10636 verificationInfo, user, sessionParams.abiOverride, 10637 sessionParams.grantedRuntimePermissions); 10638 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 10639 msg.obj = params; 10640 10641 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 10642 System.identityHashCode(msg.obj)); 10643 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10644 System.identityHashCode(msg.obj)); 10645 10646 mHandler.sendMessage(msg); 10647 } 10648 10649 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 10650 int userId) { 10651 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 10652 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 10653 } 10654 10655 private void sendPackageAddedForUser(String packageName, boolean isSystem, 10656 int appId, int userId) { 10657 Bundle extras = new Bundle(1); 10658 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 10659 10660 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 10661 packageName, extras, 0, null, null, new int[] {userId}); 10662 try { 10663 IActivityManager am = ActivityManagerNative.getDefault(); 10664 if (isSystem && am.isUserRunning(userId, 0)) { 10665 // The just-installed/enabled app is bundled on the system, so presumed 10666 // to be able to run automatically without needing an explicit launch. 10667 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 10668 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 10669 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 10670 .setPackage(packageName); 10671 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 10672 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 10673 } 10674 } catch (RemoteException e) { 10675 // shouldn't happen 10676 Slog.w(TAG, "Unable to bootstrap installed package", e); 10677 } 10678 } 10679 10680 @Override 10681 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 10682 int userId) { 10683 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10684 PackageSetting pkgSetting; 10685 final int uid = Binder.getCallingUid(); 10686 enforceCrossUserPermission(uid, userId, 10687 true /* requireFullPermission */, true /* checkShell */, 10688 "setApplicationHiddenSetting for user " + userId); 10689 10690 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 10691 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 10692 return false; 10693 } 10694 10695 long callingId = Binder.clearCallingIdentity(); 10696 try { 10697 boolean sendAdded = false; 10698 boolean sendRemoved = false; 10699 // writer 10700 synchronized (mPackages) { 10701 pkgSetting = mSettings.mPackages.get(packageName); 10702 if (pkgSetting == null) { 10703 return false; 10704 } 10705 if (pkgSetting.getHidden(userId) != hidden) { 10706 pkgSetting.setHidden(hidden, userId); 10707 mSettings.writePackageRestrictionsLPr(userId); 10708 if (hidden) { 10709 sendRemoved = true; 10710 } else { 10711 sendAdded = true; 10712 } 10713 } 10714 } 10715 if (sendAdded) { 10716 sendPackageAddedForUser(packageName, pkgSetting, userId); 10717 return true; 10718 } 10719 if (sendRemoved) { 10720 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 10721 "hiding pkg"); 10722 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 10723 return true; 10724 } 10725 } finally { 10726 Binder.restoreCallingIdentity(callingId); 10727 } 10728 return false; 10729 } 10730 10731 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 10732 int userId) { 10733 final PackageRemovedInfo info = new PackageRemovedInfo(); 10734 info.removedPackage = packageName; 10735 info.removedUsers = new int[] {userId}; 10736 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 10737 info.sendPackageRemovedBroadcasts(true /*killApp*/); 10738 } 10739 10740 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 10741 if (pkgList.length > 0) { 10742 Bundle extras = new Bundle(1); 10743 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 10744 10745 sendPackageBroadcast( 10746 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 10747 : Intent.ACTION_PACKAGES_UNSUSPENDED, 10748 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 10749 new int[] {userId}); 10750 } 10751 } 10752 10753 /** 10754 * Returns true if application is not found or there was an error. Otherwise it returns 10755 * the hidden state of the package for the given user. 10756 */ 10757 @Override 10758 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 10759 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10760 enforceCrossUserPermission(Binder.getCallingUid(), userId, 10761 true /* requireFullPermission */, false /* checkShell */, 10762 "getApplicationHidden for user " + userId); 10763 PackageSetting pkgSetting; 10764 long callingId = Binder.clearCallingIdentity(); 10765 try { 10766 // writer 10767 synchronized (mPackages) { 10768 pkgSetting = mSettings.mPackages.get(packageName); 10769 if (pkgSetting == null) { 10770 return true; 10771 } 10772 return pkgSetting.getHidden(userId); 10773 } 10774 } finally { 10775 Binder.restoreCallingIdentity(callingId); 10776 } 10777 } 10778 10779 /** 10780 * @hide 10781 */ 10782 @Override 10783 public int installExistingPackageAsUser(String packageName, int userId) { 10784 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 10785 null); 10786 PackageSetting pkgSetting; 10787 final int uid = Binder.getCallingUid(); 10788 enforceCrossUserPermission(uid, userId, 10789 true /* requireFullPermission */, true /* checkShell */, 10790 "installExistingPackage for user " + userId); 10791 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10792 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 10793 } 10794 10795 long callingId = Binder.clearCallingIdentity(); 10796 try { 10797 boolean installed = false; 10798 10799 // writer 10800 synchronized (mPackages) { 10801 pkgSetting = mSettings.mPackages.get(packageName); 10802 if (pkgSetting == null) { 10803 return PackageManager.INSTALL_FAILED_INVALID_URI; 10804 } 10805 if (!pkgSetting.getInstalled(userId)) { 10806 pkgSetting.setInstalled(true, userId); 10807 pkgSetting.setHidden(false, userId); 10808 mSettings.writePackageRestrictionsLPr(userId); 10809 installed = true; 10810 } 10811 } 10812 10813 if (installed) { 10814 if (pkgSetting.pkg != null) { 10815 prepareAppDataAfterInstall(pkgSetting.pkg); 10816 } 10817 sendPackageAddedForUser(packageName, pkgSetting, userId); 10818 } 10819 } finally { 10820 Binder.restoreCallingIdentity(callingId); 10821 } 10822 10823 return PackageManager.INSTALL_SUCCEEDED; 10824 } 10825 10826 boolean isUserRestricted(int userId, String restrictionKey) { 10827 Bundle restrictions = sUserManager.getUserRestrictions(userId); 10828 if (restrictions.getBoolean(restrictionKey, false)) { 10829 Log.w(TAG, "User is restricted: " + restrictionKey); 10830 return true; 10831 } 10832 return false; 10833 } 10834 10835 @Override 10836 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 10837 int userId) { 10838 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10839 enforceCrossUserPermission(Binder.getCallingUid(), userId, 10840 true /* requireFullPermission */, true /* checkShell */, 10841 "setPackagesSuspended for user " + userId); 10842 10843 if (ArrayUtils.isEmpty(packageNames)) { 10844 return packageNames; 10845 } 10846 10847 // List of package names for whom the suspended state has changed. 10848 List<String> changedPackages = new ArrayList<>(packageNames.length); 10849 // List of package names for whom the suspended state is not set as requested in this 10850 // method. 10851 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 10852 for (int i = 0; i < packageNames.length; i++) { 10853 String packageName = packageNames[i]; 10854 long callingId = Binder.clearCallingIdentity(); 10855 try { 10856 boolean changed = false; 10857 final int appId; 10858 synchronized (mPackages) { 10859 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10860 if (pkgSetting == null) { 10861 Slog.w(TAG, "Could not find package setting for package \"" + packageName 10862 + "\". Skipping suspending/un-suspending."); 10863 unactionedPackages.add(packageName); 10864 continue; 10865 } 10866 appId = pkgSetting.appId; 10867 if (pkgSetting.getSuspended(userId) != suspended) { 10868 if (!canSuspendPackageForUserLocked(packageName, userId)) { 10869 unactionedPackages.add(packageName); 10870 continue; 10871 } 10872 pkgSetting.setSuspended(suspended, userId); 10873 mSettings.writePackageRestrictionsLPr(userId); 10874 changed = true; 10875 changedPackages.add(packageName); 10876 } 10877 } 10878 10879 if (changed && suspended) { 10880 killApplication(packageName, UserHandle.getUid(userId, appId), 10881 "suspending package"); 10882 } 10883 } finally { 10884 Binder.restoreCallingIdentity(callingId); 10885 } 10886 } 10887 10888 if (!changedPackages.isEmpty()) { 10889 sendPackagesSuspendedForUser(changedPackages.toArray( 10890 new String[changedPackages.size()]), userId, suspended); 10891 } 10892 10893 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 10894 } 10895 10896 @Override 10897 public boolean isPackageSuspendedForUser(String packageName, int userId) { 10898 enforceCrossUserPermission(Binder.getCallingUid(), userId, 10899 true /* requireFullPermission */, false /* checkShell */, 10900 "isPackageSuspendedForUser for user " + userId); 10901 synchronized (mPackages) { 10902 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10903 if (pkgSetting == null) { 10904 throw new IllegalArgumentException("Unknown target package: " + packageName); 10905 } 10906 return pkgSetting.getSuspended(userId); 10907 } 10908 } 10909 10910 /** 10911 * TODO: cache and disallow blocking the active dialer. 10912 * 10913 * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions 10914 */ 10915 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 10916 if (isPackageDeviceAdmin(packageName, userId)) { 10917 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 10918 + "\": has an active device admin"); 10919 return false; 10920 } 10921 10922 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 10923 if (packageName.equals(activeLauncherPackageName)) { 10924 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 10925 + "\": contains the active launcher"); 10926 return false; 10927 } 10928 10929 if (packageName.equals(mRequiredInstallerPackage)) { 10930 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 10931 + "\": required for package installation"); 10932 return false; 10933 } 10934 10935 if (packageName.equals(mRequiredVerifierPackage)) { 10936 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 10937 + "\": required for package verification"); 10938 return false; 10939 } 10940 10941 final PackageParser.Package pkg = mPackages.get(packageName); 10942 if (pkg != null && isPrivilegedApp(pkg)) { 10943 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 10944 + "\": is a privileged app"); 10945 return false; 10946 } 10947 10948 return true; 10949 } 10950 10951 private String getActiveLauncherPackageName(int userId) { 10952 Intent intent = new Intent(Intent.ACTION_MAIN); 10953 intent.addCategory(Intent.CATEGORY_HOME); 10954 ResolveInfo resolveInfo = resolveIntent( 10955 intent, 10956 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 10957 PackageManager.MATCH_DEFAULT_ONLY, 10958 userId); 10959 10960 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 10961 } 10962 10963 @Override 10964 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 10965 mContext.enforceCallingOrSelfPermission( 10966 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10967 "Only package verification agents can verify applications"); 10968 10969 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10970 final PackageVerificationResponse response = new PackageVerificationResponse( 10971 verificationCode, Binder.getCallingUid()); 10972 msg.arg1 = id; 10973 msg.obj = response; 10974 mHandler.sendMessage(msg); 10975 } 10976 10977 @Override 10978 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 10979 long millisecondsToDelay) { 10980 mContext.enforceCallingOrSelfPermission( 10981 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10982 "Only package verification agents can extend verification timeouts"); 10983 10984 final PackageVerificationState state = mPendingVerification.get(id); 10985 final PackageVerificationResponse response = new PackageVerificationResponse( 10986 verificationCodeAtTimeout, Binder.getCallingUid()); 10987 10988 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 10989 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 10990 } 10991 if (millisecondsToDelay < 0) { 10992 millisecondsToDelay = 0; 10993 } 10994 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 10995 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 10996 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 10997 } 10998 10999 if ((state != null) && !state.timeoutExtended()) { 11000 state.extendTimeout(); 11001 11002 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11003 msg.arg1 = id; 11004 msg.obj = response; 11005 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11006 } 11007 } 11008 11009 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11010 int verificationCode, UserHandle user) { 11011 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11012 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11013 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11014 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11015 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11016 11017 mContext.sendBroadcastAsUser(intent, user, 11018 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11019 } 11020 11021 private ComponentName matchComponentForVerifier(String packageName, 11022 List<ResolveInfo> receivers) { 11023 ActivityInfo targetReceiver = null; 11024 11025 final int NR = receivers.size(); 11026 for (int i = 0; i < NR; i++) { 11027 final ResolveInfo info = receivers.get(i); 11028 if (info.activityInfo == null) { 11029 continue; 11030 } 11031 11032 if (packageName.equals(info.activityInfo.packageName)) { 11033 targetReceiver = info.activityInfo; 11034 break; 11035 } 11036 } 11037 11038 if (targetReceiver == null) { 11039 return null; 11040 } 11041 11042 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11043 } 11044 11045 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11046 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11047 if (pkgInfo.verifiers.length == 0) { 11048 return null; 11049 } 11050 11051 final int N = pkgInfo.verifiers.length; 11052 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11053 for (int i = 0; i < N; i++) { 11054 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11055 11056 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11057 receivers); 11058 if (comp == null) { 11059 continue; 11060 } 11061 11062 final int verifierUid = getUidForVerifier(verifierInfo); 11063 if (verifierUid == -1) { 11064 continue; 11065 } 11066 11067 if (DEBUG_VERIFY) { 11068 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11069 + " with the correct signature"); 11070 } 11071 sufficientVerifiers.add(comp); 11072 verificationState.addSufficientVerifier(verifierUid); 11073 } 11074 11075 return sufficientVerifiers; 11076 } 11077 11078 private int getUidForVerifier(VerifierInfo verifierInfo) { 11079 synchronized (mPackages) { 11080 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11081 if (pkg == null) { 11082 return -1; 11083 } else if (pkg.mSignatures.length != 1) { 11084 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11085 + " has more than one signature; ignoring"); 11086 return -1; 11087 } 11088 11089 /* 11090 * If the public key of the package's signature does not match 11091 * our expected public key, then this is a different package and 11092 * we should skip. 11093 */ 11094 11095 final byte[] expectedPublicKey; 11096 try { 11097 final Signature verifierSig = pkg.mSignatures[0]; 11098 final PublicKey publicKey = verifierSig.getPublicKey(); 11099 expectedPublicKey = publicKey.getEncoded(); 11100 } catch (CertificateException e) { 11101 return -1; 11102 } 11103 11104 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11105 11106 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11107 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11108 + " does not have the expected public key; ignoring"); 11109 return -1; 11110 } 11111 11112 return pkg.applicationInfo.uid; 11113 } 11114 } 11115 11116 @Override 11117 public void finishPackageInstall(int token) { 11118 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11119 11120 if (DEBUG_INSTALL) { 11121 Slog.v(TAG, "BM finishing package install for " + token); 11122 } 11123 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11124 11125 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11126 mHandler.sendMessage(msg); 11127 } 11128 11129 /** 11130 * Get the verification agent timeout. 11131 * 11132 * @return verification timeout in milliseconds 11133 */ 11134 private long getVerificationTimeout() { 11135 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11136 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11137 DEFAULT_VERIFICATION_TIMEOUT); 11138 } 11139 11140 /** 11141 * Get the default verification agent response code. 11142 * 11143 * @return default verification response code 11144 */ 11145 private int getDefaultVerificationResponse() { 11146 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11147 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11148 DEFAULT_VERIFICATION_RESPONSE); 11149 } 11150 11151 /** 11152 * Check whether or not package verification has been enabled. 11153 * 11154 * @return true if verification should be performed 11155 */ 11156 private boolean isVerificationEnabled(int userId, int installFlags) { 11157 if (!DEFAULT_VERIFY_ENABLE) { 11158 return false; 11159 } 11160 // Ephemeral apps don't get the full verification treatment 11161 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11162 if (DEBUG_EPHEMERAL) { 11163 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11164 } 11165 return false; 11166 } 11167 11168 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11169 11170 // Check if installing from ADB 11171 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11172 // Do not run verification in a test harness environment 11173 if (ActivityManager.isRunningInTestHarness()) { 11174 return false; 11175 } 11176 if (ensureVerifyAppsEnabled) { 11177 return true; 11178 } 11179 // Check if the developer does not want package verification for ADB installs 11180 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11181 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11182 return false; 11183 } 11184 } 11185 11186 if (ensureVerifyAppsEnabled) { 11187 return true; 11188 } 11189 11190 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11191 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11192 } 11193 11194 @Override 11195 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11196 throws RemoteException { 11197 mContext.enforceCallingOrSelfPermission( 11198 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11199 "Only intentfilter verification agents can verify applications"); 11200 11201 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11202 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11203 Binder.getCallingUid(), verificationCode, failedDomains); 11204 msg.arg1 = id; 11205 msg.obj = response; 11206 mHandler.sendMessage(msg); 11207 } 11208 11209 @Override 11210 public int getIntentVerificationStatus(String packageName, int userId) { 11211 synchronized (mPackages) { 11212 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11213 } 11214 } 11215 11216 @Override 11217 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11218 mContext.enforceCallingOrSelfPermission( 11219 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11220 11221 boolean result = false; 11222 synchronized (mPackages) { 11223 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11224 } 11225 if (result) { 11226 scheduleWritePackageRestrictionsLocked(userId); 11227 } 11228 return result; 11229 } 11230 11231 @Override 11232 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11233 String packageName) { 11234 synchronized (mPackages) { 11235 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11236 } 11237 } 11238 11239 @Override 11240 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11241 if (TextUtils.isEmpty(packageName)) { 11242 return ParceledListSlice.emptyList(); 11243 } 11244 synchronized (mPackages) { 11245 PackageParser.Package pkg = mPackages.get(packageName); 11246 if (pkg == null || pkg.activities == null) { 11247 return ParceledListSlice.emptyList(); 11248 } 11249 final int count = pkg.activities.size(); 11250 ArrayList<IntentFilter> result = new ArrayList<>(); 11251 for (int n=0; n<count; n++) { 11252 PackageParser.Activity activity = pkg.activities.get(n); 11253 if (activity.intents != null && activity.intents.size() > 0) { 11254 result.addAll(activity.intents); 11255 } 11256 } 11257 return new ParceledListSlice<>(result); 11258 } 11259 } 11260 11261 @Override 11262 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11263 mContext.enforceCallingOrSelfPermission( 11264 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11265 11266 synchronized (mPackages) { 11267 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11268 if (packageName != null) { 11269 result |= updateIntentVerificationStatus(packageName, 11270 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11271 userId); 11272 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11273 packageName, userId); 11274 } 11275 return result; 11276 } 11277 } 11278 11279 @Override 11280 public String getDefaultBrowserPackageName(int userId) { 11281 synchronized (mPackages) { 11282 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11283 } 11284 } 11285 11286 /** 11287 * Get the "allow unknown sources" setting. 11288 * 11289 * @return the current "allow unknown sources" setting 11290 */ 11291 private int getUnknownSourcesSettings() { 11292 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11293 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 11294 -1); 11295 } 11296 11297 @Override 11298 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11299 final int uid = Binder.getCallingUid(); 11300 // writer 11301 synchronized (mPackages) { 11302 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11303 if (targetPackageSetting == null) { 11304 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11305 } 11306 11307 PackageSetting installerPackageSetting; 11308 if (installerPackageName != null) { 11309 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11310 if (installerPackageSetting == null) { 11311 throw new IllegalArgumentException("Unknown installer package: " 11312 + installerPackageName); 11313 } 11314 } else { 11315 installerPackageSetting = null; 11316 } 11317 11318 Signature[] callerSignature; 11319 Object obj = mSettings.getUserIdLPr(uid); 11320 if (obj != null) { 11321 if (obj instanceof SharedUserSetting) { 11322 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11323 } else if (obj instanceof PackageSetting) { 11324 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11325 } else { 11326 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11327 } 11328 } else { 11329 throw new SecurityException("Unknown calling UID: " + uid); 11330 } 11331 11332 // Verify: can't set installerPackageName to a package that is 11333 // not signed with the same cert as the caller. 11334 if (installerPackageSetting != null) { 11335 if (compareSignatures(callerSignature, 11336 installerPackageSetting.signatures.mSignatures) 11337 != PackageManager.SIGNATURE_MATCH) { 11338 throw new SecurityException( 11339 "Caller does not have same cert as new installer package " 11340 + installerPackageName); 11341 } 11342 } 11343 11344 // Verify: if target already has an installer package, it must 11345 // be signed with the same cert as the caller. 11346 if (targetPackageSetting.installerPackageName != null) { 11347 PackageSetting setting = mSettings.mPackages.get( 11348 targetPackageSetting.installerPackageName); 11349 // If the currently set package isn't valid, then it's always 11350 // okay to change it. 11351 if (setting != null) { 11352 if (compareSignatures(callerSignature, 11353 setting.signatures.mSignatures) 11354 != PackageManager.SIGNATURE_MATCH) { 11355 throw new SecurityException( 11356 "Caller does not have same cert as old installer package " 11357 + targetPackageSetting.installerPackageName); 11358 } 11359 } 11360 } 11361 11362 // Okay! 11363 targetPackageSetting.installerPackageName = installerPackageName; 11364 scheduleWriteSettingsLocked(); 11365 } 11366 } 11367 11368 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 11369 // Queue up an async operation since the package installation may take a little while. 11370 mHandler.post(new Runnable() { 11371 public void run() { 11372 mHandler.removeCallbacks(this); 11373 // Result object to be returned 11374 PackageInstalledInfo res = new PackageInstalledInfo(); 11375 res.setReturnCode(currentStatus); 11376 res.uid = -1; 11377 res.pkg = null; 11378 res.removedInfo = null; 11379 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11380 args.doPreInstall(res.returnCode); 11381 synchronized (mInstallLock) { 11382 installPackageTracedLI(args, res); 11383 } 11384 args.doPostInstall(res.returnCode, res.uid); 11385 } 11386 11387 // A restore should be performed at this point if (a) the install 11388 // succeeded, (b) the operation is not an update, and (c) the new 11389 // package has not opted out of backup participation. 11390 final boolean update = res.removedInfo != null 11391 && res.removedInfo.removedPackage != null; 11392 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 11393 boolean doRestore = !update 11394 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 11395 11396 // Set up the post-install work request bookkeeping. This will be used 11397 // and cleaned up by the post-install event handling regardless of whether 11398 // there's a restore pass performed. Token values are >= 1. 11399 int token; 11400 if (mNextInstallToken < 0) mNextInstallToken = 1; 11401 token = mNextInstallToken++; 11402 11403 PostInstallData data = new PostInstallData(args, res); 11404 mRunningInstalls.put(token, data); 11405 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 11406 11407 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 11408 // Pass responsibility to the Backup Manager. It will perform a 11409 // restore if appropriate, then pass responsibility back to the 11410 // Package Manager to run the post-install observer callbacks 11411 // and broadcasts. 11412 IBackupManager bm = IBackupManager.Stub.asInterface( 11413 ServiceManager.getService(Context.BACKUP_SERVICE)); 11414 if (bm != null) { 11415 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 11416 + " to BM for possible restore"); 11417 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11418 try { 11419 // TODO: http://b/22388012 11420 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 11421 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 11422 } else { 11423 doRestore = false; 11424 } 11425 } catch (RemoteException e) { 11426 // can't happen; the backup manager is local 11427 } catch (Exception e) { 11428 Slog.e(TAG, "Exception trying to enqueue restore", e); 11429 doRestore = false; 11430 } 11431 } else { 11432 Slog.e(TAG, "Backup Manager not found!"); 11433 doRestore = false; 11434 } 11435 } 11436 11437 if (!doRestore) { 11438 // No restore possible, or the Backup Manager was mysteriously not 11439 // available -- just fire the post-install work request directly. 11440 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 11441 11442 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 11443 11444 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11445 mHandler.sendMessage(msg); 11446 } 11447 } 11448 }); 11449 } 11450 11451 private abstract class HandlerParams { 11452 private static final int MAX_RETRIES = 4; 11453 11454 /** 11455 * Number of times startCopy() has been attempted and had a non-fatal 11456 * error. 11457 */ 11458 private int mRetries = 0; 11459 11460 /** User handle for the user requesting the information or installation. */ 11461 private final UserHandle mUser; 11462 String traceMethod; 11463 int traceCookie; 11464 11465 HandlerParams(UserHandle user) { 11466 mUser = user; 11467 } 11468 11469 UserHandle getUser() { 11470 return mUser; 11471 } 11472 11473 HandlerParams setTraceMethod(String traceMethod) { 11474 this.traceMethod = traceMethod; 11475 return this; 11476 } 11477 11478 HandlerParams setTraceCookie(int traceCookie) { 11479 this.traceCookie = traceCookie; 11480 return this; 11481 } 11482 11483 final boolean startCopy() { 11484 boolean res; 11485 try { 11486 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 11487 11488 if (++mRetries > MAX_RETRIES) { 11489 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 11490 mHandler.sendEmptyMessage(MCS_GIVE_UP); 11491 handleServiceError(); 11492 return false; 11493 } else { 11494 handleStartCopy(); 11495 res = true; 11496 } 11497 } catch (RemoteException e) { 11498 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 11499 mHandler.sendEmptyMessage(MCS_RECONNECT); 11500 res = false; 11501 } 11502 handleReturnCode(); 11503 return res; 11504 } 11505 11506 final void serviceError() { 11507 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 11508 handleServiceError(); 11509 handleReturnCode(); 11510 } 11511 11512 abstract void handleStartCopy() throws RemoteException; 11513 abstract void handleServiceError(); 11514 abstract void handleReturnCode(); 11515 } 11516 11517 class MeasureParams extends HandlerParams { 11518 private final PackageStats mStats; 11519 private boolean mSuccess; 11520 11521 private final IPackageStatsObserver mObserver; 11522 11523 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 11524 super(new UserHandle(stats.userHandle)); 11525 mObserver = observer; 11526 mStats = stats; 11527 } 11528 11529 @Override 11530 public String toString() { 11531 return "MeasureParams{" 11532 + Integer.toHexString(System.identityHashCode(this)) 11533 + " " + mStats.packageName + "}"; 11534 } 11535 11536 @Override 11537 void handleStartCopy() throws RemoteException { 11538 synchronized (mInstallLock) { 11539 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 11540 } 11541 11542 if (mSuccess) { 11543 final boolean mounted; 11544 if (Environment.isExternalStorageEmulated()) { 11545 mounted = true; 11546 } else { 11547 final String status = Environment.getExternalStorageState(); 11548 mounted = (Environment.MEDIA_MOUNTED.equals(status) 11549 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 11550 } 11551 11552 if (mounted) { 11553 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 11554 11555 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 11556 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 11557 11558 mStats.externalDataSize = calculateDirectorySize(mContainerService, 11559 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 11560 11561 // Always subtract cache size, since it's a subdirectory 11562 mStats.externalDataSize -= mStats.externalCacheSize; 11563 11564 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 11565 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 11566 11567 mStats.externalObbSize = calculateDirectorySize(mContainerService, 11568 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 11569 } 11570 } 11571 } 11572 11573 @Override 11574 void handleReturnCode() { 11575 if (mObserver != null) { 11576 try { 11577 mObserver.onGetStatsCompleted(mStats, mSuccess); 11578 } catch (RemoteException e) { 11579 Slog.i(TAG, "Observer no longer exists."); 11580 } 11581 } 11582 } 11583 11584 @Override 11585 void handleServiceError() { 11586 Slog.e(TAG, "Could not measure application " + mStats.packageName 11587 + " external storage"); 11588 } 11589 } 11590 11591 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 11592 throws RemoteException { 11593 long result = 0; 11594 for (File path : paths) { 11595 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 11596 } 11597 return result; 11598 } 11599 11600 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 11601 for (File path : paths) { 11602 try { 11603 mcs.clearDirectory(path.getAbsolutePath()); 11604 } catch (RemoteException e) { 11605 } 11606 } 11607 } 11608 11609 static class OriginInfo { 11610 /** 11611 * Location where install is coming from, before it has been 11612 * copied/renamed into place. This could be a single monolithic APK 11613 * file, or a cluster directory. This location may be untrusted. 11614 */ 11615 final File file; 11616 final String cid; 11617 11618 /** 11619 * Flag indicating that {@link #file} or {@link #cid} has already been 11620 * staged, meaning downstream users don't need to defensively copy the 11621 * contents. 11622 */ 11623 final boolean staged; 11624 11625 /** 11626 * Flag indicating that {@link #file} or {@link #cid} is an already 11627 * installed app that is being moved. 11628 */ 11629 final boolean existing; 11630 11631 final String resolvedPath; 11632 final File resolvedFile; 11633 11634 static OriginInfo fromNothing() { 11635 return new OriginInfo(null, null, false, false); 11636 } 11637 11638 static OriginInfo fromUntrustedFile(File file) { 11639 return new OriginInfo(file, null, false, false); 11640 } 11641 11642 static OriginInfo fromExistingFile(File file) { 11643 return new OriginInfo(file, null, false, true); 11644 } 11645 11646 static OriginInfo fromStagedFile(File file) { 11647 return new OriginInfo(file, null, true, false); 11648 } 11649 11650 static OriginInfo fromStagedContainer(String cid) { 11651 return new OriginInfo(null, cid, true, false); 11652 } 11653 11654 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 11655 this.file = file; 11656 this.cid = cid; 11657 this.staged = staged; 11658 this.existing = existing; 11659 11660 if (cid != null) { 11661 resolvedPath = PackageHelper.getSdDir(cid); 11662 resolvedFile = new File(resolvedPath); 11663 } else if (file != null) { 11664 resolvedPath = file.getAbsolutePath(); 11665 resolvedFile = file; 11666 } else { 11667 resolvedPath = null; 11668 resolvedFile = null; 11669 } 11670 } 11671 } 11672 11673 static class MoveInfo { 11674 final int moveId; 11675 final String fromUuid; 11676 final String toUuid; 11677 final String packageName; 11678 final String dataAppName; 11679 final int appId; 11680 final String seinfo; 11681 final int targetSdkVersion; 11682 11683 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 11684 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 11685 this.moveId = moveId; 11686 this.fromUuid = fromUuid; 11687 this.toUuid = toUuid; 11688 this.packageName = packageName; 11689 this.dataAppName = dataAppName; 11690 this.appId = appId; 11691 this.seinfo = seinfo; 11692 this.targetSdkVersion = targetSdkVersion; 11693 } 11694 } 11695 11696 static class VerificationInfo { 11697 /** A constant used to indicate that a uid value is not present. */ 11698 public static final int NO_UID = -1; 11699 11700 /** URI referencing where the package was downloaded from. */ 11701 final Uri originatingUri; 11702 11703 /** HTTP referrer URI associated with the originatingURI. */ 11704 final Uri referrer; 11705 11706 /** UID of the application that the install request originated from. */ 11707 final int originatingUid; 11708 11709 /** UID of application requesting the install */ 11710 final int installerUid; 11711 11712 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 11713 this.originatingUri = originatingUri; 11714 this.referrer = referrer; 11715 this.originatingUid = originatingUid; 11716 this.installerUid = installerUid; 11717 } 11718 } 11719 11720 class InstallParams extends HandlerParams { 11721 final OriginInfo origin; 11722 final MoveInfo move; 11723 final IPackageInstallObserver2 observer; 11724 int installFlags; 11725 final String installerPackageName; 11726 final String volumeUuid; 11727 private InstallArgs mArgs; 11728 private int mRet; 11729 final String packageAbiOverride; 11730 final String[] grantedRuntimePermissions; 11731 final VerificationInfo verificationInfo; 11732 11733 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11734 int installFlags, String installerPackageName, String volumeUuid, 11735 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 11736 String[] grantedPermissions) { 11737 super(user); 11738 this.origin = origin; 11739 this.move = move; 11740 this.observer = observer; 11741 this.installFlags = installFlags; 11742 this.installerPackageName = installerPackageName; 11743 this.volumeUuid = volumeUuid; 11744 this.verificationInfo = verificationInfo; 11745 this.packageAbiOverride = packageAbiOverride; 11746 this.grantedRuntimePermissions = grantedPermissions; 11747 } 11748 11749 @Override 11750 public String toString() { 11751 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 11752 + " file=" + origin.file + " cid=" + origin.cid + "}"; 11753 } 11754 11755 private int installLocationPolicy(PackageInfoLite pkgLite) { 11756 String packageName = pkgLite.packageName; 11757 int installLocation = pkgLite.installLocation; 11758 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11759 // reader 11760 synchronized (mPackages) { 11761 // Currently installed package which the new package is attempting to replace or 11762 // null if no such package is installed. 11763 PackageParser.Package installedPkg = mPackages.get(packageName); 11764 // Package which currently owns the data which the new package will own if installed. 11765 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 11766 // will be null whereas dataOwnerPkg will contain information about the package 11767 // which was uninstalled while keeping its data. 11768 PackageParser.Package dataOwnerPkg = installedPkg; 11769 if (dataOwnerPkg == null) { 11770 PackageSetting ps = mSettings.mPackages.get(packageName); 11771 if (ps != null) { 11772 dataOwnerPkg = ps.pkg; 11773 } 11774 } 11775 11776 if (dataOwnerPkg != null) { 11777 // If installed, the package will get access to data left on the device by its 11778 // predecessor. As a security measure, this is permited only if this is not a 11779 // version downgrade or if the predecessor package is marked as debuggable and 11780 // a downgrade is explicitly requested. 11781 if (((dataOwnerPkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) 11782 || ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0)) { 11783 try { 11784 checkDowngrade(dataOwnerPkg, pkgLite); 11785 } catch (PackageManagerException e) { 11786 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 11787 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 11788 } 11789 } 11790 } 11791 11792 if (installedPkg != null) { 11793 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11794 // Check for updated system application. 11795 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11796 if (onSd) { 11797 Slog.w(TAG, "Cannot install update to system app on sdcard"); 11798 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 11799 } 11800 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11801 } else { 11802 if (onSd) { 11803 // Install flag overrides everything. 11804 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11805 } 11806 // If current upgrade specifies particular preference 11807 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 11808 // Application explicitly specified internal. 11809 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11810 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 11811 // App explictly prefers external. Let policy decide 11812 } else { 11813 // Prefer previous location 11814 if (isExternal(installedPkg)) { 11815 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11816 } 11817 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11818 } 11819 } 11820 } else { 11821 // Invalid install. Return error code 11822 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 11823 } 11824 } 11825 } 11826 // All the special cases have been taken care of. 11827 // Return result based on recommended install location. 11828 if (onSd) { 11829 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11830 } 11831 return pkgLite.recommendedInstallLocation; 11832 } 11833 11834 /* 11835 * Invoke remote method to get package information and install 11836 * location values. Override install location based on default 11837 * policy if needed and then create install arguments based 11838 * on the install location. 11839 */ 11840 public void handleStartCopy() throws RemoteException { 11841 int ret = PackageManager.INSTALL_SUCCEEDED; 11842 11843 // If we're already staged, we've firmly committed to an install location 11844 if (origin.staged) { 11845 if (origin.file != null) { 11846 installFlags |= PackageManager.INSTALL_INTERNAL; 11847 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11848 } else if (origin.cid != null) { 11849 installFlags |= PackageManager.INSTALL_EXTERNAL; 11850 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11851 } else { 11852 throw new IllegalStateException("Invalid stage location"); 11853 } 11854 } 11855 11856 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11857 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 11858 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11859 PackageInfoLite pkgLite = null; 11860 11861 if (onInt && onSd) { 11862 // Check if both bits are set. 11863 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 11864 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11865 } else if (onSd && ephemeral) { 11866 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 11867 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11868 } else { 11869 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 11870 packageAbiOverride); 11871 11872 if (DEBUG_EPHEMERAL && ephemeral) { 11873 Slog.v(TAG, "pkgLite for install: " + pkgLite); 11874 } 11875 11876 /* 11877 * If we have too little free space, try to free cache 11878 * before giving up. 11879 */ 11880 if (!origin.staged && pkgLite.recommendedInstallLocation 11881 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11882 // TODO: focus freeing disk space on the target device 11883 final StorageManager storage = StorageManager.from(mContext); 11884 final long lowThreshold = storage.getStorageLowBytes( 11885 Environment.getDataDirectory()); 11886 11887 final long sizeBytes = mContainerService.calculateInstalledSize( 11888 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 11889 11890 try { 11891 mInstaller.freeCache(null, sizeBytes + lowThreshold); 11892 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 11893 installFlags, packageAbiOverride); 11894 } catch (InstallerException e) { 11895 Slog.w(TAG, "Failed to free cache", e); 11896 } 11897 11898 /* 11899 * The cache free must have deleted the file we 11900 * downloaded to install. 11901 * 11902 * TODO: fix the "freeCache" call to not delete 11903 * the file we care about. 11904 */ 11905 if (pkgLite.recommendedInstallLocation 11906 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11907 pkgLite.recommendedInstallLocation 11908 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 11909 } 11910 } 11911 } 11912 11913 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11914 int loc = pkgLite.recommendedInstallLocation; 11915 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 11916 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11917 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 11918 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 11919 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11920 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11921 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 11922 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 11923 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11924 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 11925 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 11926 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 11927 } else { 11928 // Override with defaults if needed. 11929 loc = installLocationPolicy(pkgLite); 11930 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 11931 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 11932 } else if (!onSd && !onInt) { 11933 // Override install location with flags 11934 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 11935 // Set the flag to install on external media. 11936 installFlags |= PackageManager.INSTALL_EXTERNAL; 11937 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11938 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 11939 if (DEBUG_EPHEMERAL) { 11940 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 11941 } 11942 installFlags |= PackageManager.INSTALL_EPHEMERAL; 11943 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 11944 |PackageManager.INSTALL_INTERNAL); 11945 } else { 11946 // Make sure the flag for installing on external 11947 // media is unset 11948 installFlags |= PackageManager.INSTALL_INTERNAL; 11949 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11950 } 11951 } 11952 } 11953 } 11954 11955 final InstallArgs args = createInstallArgs(this); 11956 mArgs = args; 11957 11958 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11959 // TODO: http://b/22976637 11960 // Apps installed for "all" users use the device owner to verify the app 11961 UserHandle verifierUser = getUser(); 11962 if (verifierUser == UserHandle.ALL) { 11963 verifierUser = UserHandle.SYSTEM; 11964 } 11965 11966 /* 11967 * Determine if we have any installed package verifiers. If we 11968 * do, then we'll defer to them to verify the packages. 11969 */ 11970 final int requiredUid = mRequiredVerifierPackage == null ? -1 11971 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 11972 verifierUser.getIdentifier()); 11973 if (!origin.existing && requiredUid != -1 11974 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 11975 final Intent verification = new Intent( 11976 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 11977 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 11978 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 11979 PACKAGE_MIME_TYPE); 11980 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11981 11982 // Query all live verifiers based on current user state 11983 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 11984 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 11985 11986 if (DEBUG_VERIFY) { 11987 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 11988 + verification.toString() + " with " + pkgLite.verifiers.length 11989 + " optional verifiers"); 11990 } 11991 11992 final int verificationId = mPendingVerificationToken++; 11993 11994 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11995 11996 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 11997 installerPackageName); 11998 11999 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12000 installFlags); 12001 12002 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12003 pkgLite.packageName); 12004 12005 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12006 pkgLite.versionCode); 12007 12008 if (verificationInfo != null) { 12009 if (verificationInfo.originatingUri != null) { 12010 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12011 verificationInfo.originatingUri); 12012 } 12013 if (verificationInfo.referrer != null) { 12014 verification.putExtra(Intent.EXTRA_REFERRER, 12015 verificationInfo.referrer); 12016 } 12017 if (verificationInfo.originatingUid >= 0) { 12018 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12019 verificationInfo.originatingUid); 12020 } 12021 if (verificationInfo.installerUid >= 0) { 12022 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12023 verificationInfo.installerUid); 12024 } 12025 } 12026 12027 final PackageVerificationState verificationState = new PackageVerificationState( 12028 requiredUid, args); 12029 12030 mPendingVerification.append(verificationId, verificationState); 12031 12032 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12033 receivers, verificationState); 12034 12035 /* 12036 * If any sufficient verifiers were listed in the package 12037 * manifest, attempt to ask them. 12038 */ 12039 if (sufficientVerifiers != null) { 12040 final int N = sufficientVerifiers.size(); 12041 if (N == 0) { 12042 Slog.i(TAG, "Additional verifiers required, but none installed."); 12043 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12044 } else { 12045 for (int i = 0; i < N; i++) { 12046 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12047 12048 final Intent sufficientIntent = new Intent(verification); 12049 sufficientIntent.setComponent(verifierComponent); 12050 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12051 } 12052 } 12053 } 12054 12055 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12056 mRequiredVerifierPackage, receivers); 12057 if (ret == PackageManager.INSTALL_SUCCEEDED 12058 && mRequiredVerifierPackage != null) { 12059 Trace.asyncTraceBegin( 12060 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12061 /* 12062 * Send the intent to the required verification agent, 12063 * but only start the verification timeout after the 12064 * target BroadcastReceivers have run. 12065 */ 12066 verification.setComponent(requiredVerifierComponent); 12067 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12068 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12069 new BroadcastReceiver() { 12070 @Override 12071 public void onReceive(Context context, Intent intent) { 12072 final Message msg = mHandler 12073 .obtainMessage(CHECK_PENDING_VERIFICATION); 12074 msg.arg1 = verificationId; 12075 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12076 } 12077 }, null, 0, null, null); 12078 12079 /* 12080 * We don't want the copy to proceed until verification 12081 * succeeds, so null out this field. 12082 */ 12083 mArgs = null; 12084 } 12085 } else { 12086 /* 12087 * No package verification is enabled, so immediately start 12088 * the remote call to initiate copy using temporary file. 12089 */ 12090 ret = args.copyApk(mContainerService, true); 12091 } 12092 } 12093 12094 mRet = ret; 12095 } 12096 12097 @Override 12098 void handleReturnCode() { 12099 // If mArgs is null, then MCS couldn't be reached. When it 12100 // reconnects, it will try again to install. At that point, this 12101 // will succeed. 12102 if (mArgs != null) { 12103 processPendingInstall(mArgs, mRet); 12104 } 12105 } 12106 12107 @Override 12108 void handleServiceError() { 12109 mArgs = createInstallArgs(this); 12110 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12111 } 12112 12113 public boolean isForwardLocked() { 12114 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12115 } 12116 } 12117 12118 /** 12119 * Used during creation of InstallArgs 12120 * 12121 * @param installFlags package installation flags 12122 * @return true if should be installed on external storage 12123 */ 12124 private static boolean installOnExternalAsec(int installFlags) { 12125 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12126 return false; 12127 } 12128 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12129 return true; 12130 } 12131 return false; 12132 } 12133 12134 /** 12135 * Used during creation of InstallArgs 12136 * 12137 * @param installFlags package installation flags 12138 * @return true if should be installed as forward locked 12139 */ 12140 private static boolean installForwardLocked(int installFlags) { 12141 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12142 } 12143 12144 private InstallArgs createInstallArgs(InstallParams params) { 12145 if (params.move != null) { 12146 return new MoveInstallArgs(params); 12147 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12148 return new AsecInstallArgs(params); 12149 } else { 12150 return new FileInstallArgs(params); 12151 } 12152 } 12153 12154 /** 12155 * Create args that describe an existing installed package. Typically used 12156 * when cleaning up old installs, or used as a move source. 12157 */ 12158 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12159 String resourcePath, String[] instructionSets) { 12160 final boolean isInAsec; 12161 if (installOnExternalAsec(installFlags)) { 12162 /* Apps on SD card are always in ASEC containers. */ 12163 isInAsec = true; 12164 } else if (installForwardLocked(installFlags) 12165 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12166 /* 12167 * Forward-locked apps are only in ASEC containers if they're the 12168 * new style 12169 */ 12170 isInAsec = true; 12171 } else { 12172 isInAsec = false; 12173 } 12174 12175 if (isInAsec) { 12176 return new AsecInstallArgs(codePath, instructionSets, 12177 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12178 } else { 12179 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12180 } 12181 } 12182 12183 static abstract class InstallArgs { 12184 /** @see InstallParams#origin */ 12185 final OriginInfo origin; 12186 /** @see InstallParams#move */ 12187 final MoveInfo move; 12188 12189 final IPackageInstallObserver2 observer; 12190 // Always refers to PackageManager flags only 12191 final int installFlags; 12192 final String installerPackageName; 12193 final String volumeUuid; 12194 final UserHandle user; 12195 final String abiOverride; 12196 final String[] installGrantPermissions; 12197 /** If non-null, drop an async trace when the install completes */ 12198 final String traceMethod; 12199 final int traceCookie; 12200 12201 // The list of instruction sets supported by this app. This is currently 12202 // only used during the rmdex() phase to clean up resources. We can get rid of this 12203 // if we move dex files under the common app path. 12204 /* nullable */ String[] instructionSets; 12205 12206 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12207 int installFlags, String installerPackageName, String volumeUuid, 12208 UserHandle user, String[] instructionSets, 12209 String abiOverride, String[] installGrantPermissions, 12210 String traceMethod, int traceCookie) { 12211 this.origin = origin; 12212 this.move = move; 12213 this.installFlags = installFlags; 12214 this.observer = observer; 12215 this.installerPackageName = installerPackageName; 12216 this.volumeUuid = volumeUuid; 12217 this.user = user; 12218 this.instructionSets = instructionSets; 12219 this.abiOverride = abiOverride; 12220 this.installGrantPermissions = installGrantPermissions; 12221 this.traceMethod = traceMethod; 12222 this.traceCookie = traceCookie; 12223 } 12224 12225 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12226 abstract int doPreInstall(int status); 12227 12228 /** 12229 * Rename package into final resting place. All paths on the given 12230 * scanned package should be updated to reflect the rename. 12231 */ 12232 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12233 abstract int doPostInstall(int status, int uid); 12234 12235 /** @see PackageSettingBase#codePathString */ 12236 abstract String getCodePath(); 12237 /** @see PackageSettingBase#resourcePathString */ 12238 abstract String getResourcePath(); 12239 12240 // Need installer lock especially for dex file removal. 12241 abstract void cleanUpResourcesLI(); 12242 abstract boolean doPostDeleteLI(boolean delete); 12243 12244 /** 12245 * Called before the source arguments are copied. This is used mostly 12246 * for MoveParams when it needs to read the source file to put it in the 12247 * destination. 12248 */ 12249 int doPreCopy() { 12250 return PackageManager.INSTALL_SUCCEEDED; 12251 } 12252 12253 /** 12254 * Called after the source arguments are copied. This is used mostly for 12255 * MoveParams when it needs to read the source file to put it in the 12256 * destination. 12257 * 12258 * @return 12259 */ 12260 int doPostCopy(int uid) { 12261 return PackageManager.INSTALL_SUCCEEDED; 12262 } 12263 12264 protected boolean isFwdLocked() { 12265 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12266 } 12267 12268 protected boolean isExternalAsec() { 12269 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12270 } 12271 12272 protected boolean isEphemeral() { 12273 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12274 } 12275 12276 UserHandle getUser() { 12277 return user; 12278 } 12279 } 12280 12281 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 12282 if (!allCodePaths.isEmpty()) { 12283 if (instructionSets == null) { 12284 throw new IllegalStateException("instructionSet == null"); 12285 } 12286 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 12287 for (String codePath : allCodePaths) { 12288 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 12289 try { 12290 mInstaller.rmdex(codePath, dexCodeInstructionSet); 12291 } catch (InstallerException ignored) { 12292 } 12293 } 12294 } 12295 } 12296 } 12297 12298 /** 12299 * Logic to handle installation of non-ASEC applications, including copying 12300 * and renaming logic. 12301 */ 12302 class FileInstallArgs extends InstallArgs { 12303 private File codeFile; 12304 private File resourceFile; 12305 12306 // Example topology: 12307 // /data/app/com.example/base.apk 12308 // /data/app/com.example/split_foo.apk 12309 // /data/app/com.example/lib/arm/libfoo.so 12310 // /data/app/com.example/lib/arm64/libfoo.so 12311 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 12312 12313 /** New install */ 12314 FileInstallArgs(InstallParams params) { 12315 super(params.origin, params.move, params.observer, params.installFlags, 12316 params.installerPackageName, params.volumeUuid, 12317 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12318 params.grantedRuntimePermissions, 12319 params.traceMethod, params.traceCookie); 12320 if (isFwdLocked()) { 12321 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 12322 } 12323 } 12324 12325 /** Existing install */ 12326 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 12327 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 12328 null, null, null, 0); 12329 this.codeFile = (codePath != null) ? new File(codePath) : null; 12330 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 12331 } 12332 12333 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12334 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 12335 try { 12336 return doCopyApk(imcs, temp); 12337 } finally { 12338 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12339 } 12340 } 12341 12342 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12343 if (origin.staged) { 12344 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 12345 codeFile = origin.file; 12346 resourceFile = origin.file; 12347 return PackageManager.INSTALL_SUCCEEDED; 12348 } 12349 12350 try { 12351 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12352 final File tempDir = 12353 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 12354 codeFile = tempDir; 12355 resourceFile = tempDir; 12356 } catch (IOException e) { 12357 Slog.w(TAG, "Failed to create copy file: " + e); 12358 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12359 } 12360 12361 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 12362 @Override 12363 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 12364 if (!FileUtils.isValidExtFilename(name)) { 12365 throw new IllegalArgumentException("Invalid filename: " + name); 12366 } 12367 try { 12368 final File file = new File(codeFile, name); 12369 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 12370 O_RDWR | O_CREAT, 0644); 12371 Os.chmod(file.getAbsolutePath(), 0644); 12372 return new ParcelFileDescriptor(fd); 12373 } catch (ErrnoException e) { 12374 throw new RemoteException("Failed to open: " + e.getMessage()); 12375 } 12376 } 12377 }; 12378 12379 int ret = PackageManager.INSTALL_SUCCEEDED; 12380 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 12381 if (ret != PackageManager.INSTALL_SUCCEEDED) { 12382 Slog.e(TAG, "Failed to copy package"); 12383 return ret; 12384 } 12385 12386 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 12387 NativeLibraryHelper.Handle handle = null; 12388 try { 12389 handle = NativeLibraryHelper.Handle.create(codeFile); 12390 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 12391 abiOverride); 12392 } catch (IOException e) { 12393 Slog.e(TAG, "Copying native libraries failed", e); 12394 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12395 } finally { 12396 IoUtils.closeQuietly(handle); 12397 } 12398 12399 return ret; 12400 } 12401 12402 int doPreInstall(int status) { 12403 if (status != PackageManager.INSTALL_SUCCEEDED) { 12404 cleanUp(); 12405 } 12406 return status; 12407 } 12408 12409 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12410 if (status != PackageManager.INSTALL_SUCCEEDED) { 12411 cleanUp(); 12412 return false; 12413 } 12414 12415 final File targetDir = codeFile.getParentFile(); 12416 final File beforeCodeFile = codeFile; 12417 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 12418 12419 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 12420 try { 12421 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 12422 } catch (ErrnoException e) { 12423 Slog.w(TAG, "Failed to rename", e); 12424 return false; 12425 } 12426 12427 if (!SELinux.restoreconRecursive(afterCodeFile)) { 12428 Slog.w(TAG, "Failed to restorecon"); 12429 return false; 12430 } 12431 12432 // Reflect the rename internally 12433 codeFile = afterCodeFile; 12434 resourceFile = afterCodeFile; 12435 12436 // Reflect the rename in scanned details 12437 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12438 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12439 afterCodeFile, pkg.baseCodePath)); 12440 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12441 afterCodeFile, pkg.splitCodePaths)); 12442 12443 // Reflect the rename in app info 12444 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12445 pkg.setApplicationInfoCodePath(pkg.codePath); 12446 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12447 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12448 pkg.setApplicationInfoResourcePath(pkg.codePath); 12449 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12450 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12451 12452 return true; 12453 } 12454 12455 int doPostInstall(int status, int uid) { 12456 if (status != PackageManager.INSTALL_SUCCEEDED) { 12457 cleanUp(); 12458 } 12459 return status; 12460 } 12461 12462 @Override 12463 String getCodePath() { 12464 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12465 } 12466 12467 @Override 12468 String getResourcePath() { 12469 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12470 } 12471 12472 private boolean cleanUp() { 12473 if (codeFile == null || !codeFile.exists()) { 12474 return false; 12475 } 12476 12477 removeCodePathLI(codeFile); 12478 12479 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 12480 resourceFile.delete(); 12481 } 12482 12483 return true; 12484 } 12485 12486 void cleanUpResourcesLI() { 12487 // Try enumerating all code paths before deleting 12488 List<String> allCodePaths = Collections.EMPTY_LIST; 12489 if (codeFile != null && codeFile.exists()) { 12490 try { 12491 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12492 allCodePaths = pkg.getAllCodePaths(); 12493 } catch (PackageParserException e) { 12494 // Ignored; we tried our best 12495 } 12496 } 12497 12498 cleanUp(); 12499 removeDexFiles(allCodePaths, instructionSets); 12500 } 12501 12502 boolean doPostDeleteLI(boolean delete) { 12503 // XXX err, shouldn't we respect the delete flag? 12504 cleanUpResourcesLI(); 12505 return true; 12506 } 12507 } 12508 12509 private boolean isAsecExternal(String cid) { 12510 final String asecPath = PackageHelper.getSdFilesystem(cid); 12511 return !asecPath.startsWith(mAsecInternalPath); 12512 } 12513 12514 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 12515 PackageManagerException { 12516 if (copyRet < 0) { 12517 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 12518 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 12519 throw new PackageManagerException(copyRet, message); 12520 } 12521 } 12522 } 12523 12524 /** 12525 * Extract the MountService "container ID" from the full code path of an 12526 * .apk. 12527 */ 12528 static String cidFromCodePath(String fullCodePath) { 12529 int eidx = fullCodePath.lastIndexOf("/"); 12530 String subStr1 = fullCodePath.substring(0, eidx); 12531 int sidx = subStr1.lastIndexOf("/"); 12532 return subStr1.substring(sidx+1, eidx); 12533 } 12534 12535 /** 12536 * Logic to handle installation of ASEC applications, including copying and 12537 * renaming logic. 12538 */ 12539 class AsecInstallArgs extends InstallArgs { 12540 static final String RES_FILE_NAME = "pkg.apk"; 12541 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 12542 12543 String cid; 12544 String packagePath; 12545 String resourcePath; 12546 12547 /** New install */ 12548 AsecInstallArgs(InstallParams params) { 12549 super(params.origin, params.move, params.observer, params.installFlags, 12550 params.installerPackageName, params.volumeUuid, 12551 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12552 params.grantedRuntimePermissions, 12553 params.traceMethod, params.traceCookie); 12554 } 12555 12556 /** Existing install */ 12557 AsecInstallArgs(String fullCodePath, String[] instructionSets, 12558 boolean isExternal, boolean isForwardLocked) { 12559 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 12560 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12561 instructionSets, null, null, null, 0); 12562 // Hackily pretend we're still looking at a full code path 12563 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 12564 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 12565 } 12566 12567 // Extract cid from fullCodePath 12568 int eidx = fullCodePath.lastIndexOf("/"); 12569 String subStr1 = fullCodePath.substring(0, eidx); 12570 int sidx = subStr1.lastIndexOf("/"); 12571 cid = subStr1.substring(sidx+1, eidx); 12572 setMountPath(subStr1); 12573 } 12574 12575 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 12576 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 12577 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12578 instructionSets, null, null, null, 0); 12579 this.cid = cid; 12580 setMountPath(PackageHelper.getSdDir(cid)); 12581 } 12582 12583 void createCopyFile() { 12584 cid = mInstallerService.allocateExternalStageCidLegacy(); 12585 } 12586 12587 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12588 if (origin.staged && origin.cid != null) { 12589 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 12590 cid = origin.cid; 12591 setMountPath(PackageHelper.getSdDir(cid)); 12592 return PackageManager.INSTALL_SUCCEEDED; 12593 } 12594 12595 if (temp) { 12596 createCopyFile(); 12597 } else { 12598 /* 12599 * Pre-emptively destroy the container since it's destroyed if 12600 * copying fails due to it existing anyway. 12601 */ 12602 PackageHelper.destroySdDir(cid); 12603 } 12604 12605 final String newMountPath = imcs.copyPackageToContainer( 12606 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 12607 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 12608 12609 if (newMountPath != null) { 12610 setMountPath(newMountPath); 12611 return PackageManager.INSTALL_SUCCEEDED; 12612 } else { 12613 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12614 } 12615 } 12616 12617 @Override 12618 String getCodePath() { 12619 return packagePath; 12620 } 12621 12622 @Override 12623 String getResourcePath() { 12624 return resourcePath; 12625 } 12626 12627 int doPreInstall(int status) { 12628 if (status != PackageManager.INSTALL_SUCCEEDED) { 12629 // Destroy container 12630 PackageHelper.destroySdDir(cid); 12631 } else { 12632 boolean mounted = PackageHelper.isContainerMounted(cid); 12633 if (!mounted) { 12634 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 12635 Process.SYSTEM_UID); 12636 if (newMountPath != null) { 12637 setMountPath(newMountPath); 12638 } else { 12639 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12640 } 12641 } 12642 } 12643 return status; 12644 } 12645 12646 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12647 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 12648 String newMountPath = null; 12649 if (PackageHelper.isContainerMounted(cid)) { 12650 // Unmount the container 12651 if (!PackageHelper.unMountSdDir(cid)) { 12652 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 12653 return false; 12654 } 12655 } 12656 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 12657 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 12658 " which might be stale. Will try to clean up."); 12659 // Clean up the stale container and proceed to recreate. 12660 if (!PackageHelper.destroySdDir(newCacheId)) { 12661 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 12662 return false; 12663 } 12664 // Successfully cleaned up stale container. Try to rename again. 12665 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 12666 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 12667 + " inspite of cleaning it up."); 12668 return false; 12669 } 12670 } 12671 if (!PackageHelper.isContainerMounted(newCacheId)) { 12672 Slog.w(TAG, "Mounting container " + newCacheId); 12673 newMountPath = PackageHelper.mountSdDir(newCacheId, 12674 getEncryptKey(), Process.SYSTEM_UID); 12675 } else { 12676 newMountPath = PackageHelper.getSdDir(newCacheId); 12677 } 12678 if (newMountPath == null) { 12679 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 12680 return false; 12681 } 12682 Log.i(TAG, "Succesfully renamed " + cid + 12683 " to " + newCacheId + 12684 " at new path: " + newMountPath); 12685 cid = newCacheId; 12686 12687 final File beforeCodeFile = new File(packagePath); 12688 setMountPath(newMountPath); 12689 final File afterCodeFile = new File(packagePath); 12690 12691 // Reflect the rename in scanned details 12692 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12693 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12694 afterCodeFile, pkg.baseCodePath)); 12695 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12696 afterCodeFile, pkg.splitCodePaths)); 12697 12698 // Reflect the rename in app info 12699 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12700 pkg.setApplicationInfoCodePath(pkg.codePath); 12701 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12702 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12703 pkg.setApplicationInfoResourcePath(pkg.codePath); 12704 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12705 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12706 12707 return true; 12708 } 12709 12710 private void setMountPath(String mountPath) { 12711 final File mountFile = new File(mountPath); 12712 12713 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 12714 if (monolithicFile.exists()) { 12715 packagePath = monolithicFile.getAbsolutePath(); 12716 if (isFwdLocked()) { 12717 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 12718 } else { 12719 resourcePath = packagePath; 12720 } 12721 } else { 12722 packagePath = mountFile.getAbsolutePath(); 12723 resourcePath = packagePath; 12724 } 12725 } 12726 12727 int doPostInstall(int status, int uid) { 12728 if (status != PackageManager.INSTALL_SUCCEEDED) { 12729 cleanUp(); 12730 } else { 12731 final int groupOwner; 12732 final String protectedFile; 12733 if (isFwdLocked()) { 12734 groupOwner = UserHandle.getSharedAppGid(uid); 12735 protectedFile = RES_FILE_NAME; 12736 } else { 12737 groupOwner = -1; 12738 protectedFile = null; 12739 } 12740 12741 if (uid < Process.FIRST_APPLICATION_UID 12742 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 12743 Slog.e(TAG, "Failed to finalize " + cid); 12744 PackageHelper.destroySdDir(cid); 12745 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12746 } 12747 12748 boolean mounted = PackageHelper.isContainerMounted(cid); 12749 if (!mounted) { 12750 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 12751 } 12752 } 12753 return status; 12754 } 12755 12756 private void cleanUp() { 12757 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 12758 12759 // Destroy secure container 12760 PackageHelper.destroySdDir(cid); 12761 } 12762 12763 private List<String> getAllCodePaths() { 12764 final File codeFile = new File(getCodePath()); 12765 if (codeFile != null && codeFile.exists()) { 12766 try { 12767 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12768 return pkg.getAllCodePaths(); 12769 } catch (PackageParserException e) { 12770 // Ignored; we tried our best 12771 } 12772 } 12773 return Collections.EMPTY_LIST; 12774 } 12775 12776 void cleanUpResourcesLI() { 12777 // Enumerate all code paths before deleting 12778 cleanUpResourcesLI(getAllCodePaths()); 12779 } 12780 12781 private void cleanUpResourcesLI(List<String> allCodePaths) { 12782 cleanUp(); 12783 removeDexFiles(allCodePaths, instructionSets); 12784 } 12785 12786 String getPackageName() { 12787 return getAsecPackageName(cid); 12788 } 12789 12790 boolean doPostDeleteLI(boolean delete) { 12791 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 12792 final List<String> allCodePaths = getAllCodePaths(); 12793 boolean mounted = PackageHelper.isContainerMounted(cid); 12794 if (mounted) { 12795 // Unmount first 12796 if (PackageHelper.unMountSdDir(cid)) { 12797 mounted = false; 12798 } 12799 } 12800 if (!mounted && delete) { 12801 cleanUpResourcesLI(allCodePaths); 12802 } 12803 return !mounted; 12804 } 12805 12806 @Override 12807 int doPreCopy() { 12808 if (isFwdLocked()) { 12809 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 12810 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 12811 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12812 } 12813 } 12814 12815 return PackageManager.INSTALL_SUCCEEDED; 12816 } 12817 12818 @Override 12819 int doPostCopy(int uid) { 12820 if (isFwdLocked()) { 12821 if (uid < Process.FIRST_APPLICATION_UID 12822 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 12823 RES_FILE_NAME)) { 12824 Slog.e(TAG, "Failed to finalize " + cid); 12825 PackageHelper.destroySdDir(cid); 12826 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12827 } 12828 } 12829 12830 return PackageManager.INSTALL_SUCCEEDED; 12831 } 12832 } 12833 12834 /** 12835 * Logic to handle movement of existing installed applications. 12836 */ 12837 class MoveInstallArgs extends InstallArgs { 12838 private File codeFile; 12839 private File resourceFile; 12840 12841 /** New install */ 12842 MoveInstallArgs(InstallParams params) { 12843 super(params.origin, params.move, params.observer, params.installFlags, 12844 params.installerPackageName, params.volumeUuid, 12845 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12846 params.grantedRuntimePermissions, 12847 params.traceMethod, params.traceCookie); 12848 } 12849 12850 int copyApk(IMediaContainerService imcs, boolean temp) { 12851 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 12852 + move.fromUuid + " to " + move.toUuid); 12853 synchronized (mInstaller) { 12854 try { 12855 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 12856 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 12857 } catch (InstallerException e) { 12858 Slog.w(TAG, "Failed to move app", e); 12859 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12860 } 12861 } 12862 12863 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 12864 resourceFile = codeFile; 12865 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 12866 12867 return PackageManager.INSTALL_SUCCEEDED; 12868 } 12869 12870 int doPreInstall(int status) { 12871 if (status != PackageManager.INSTALL_SUCCEEDED) { 12872 cleanUp(move.toUuid); 12873 } 12874 return status; 12875 } 12876 12877 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12878 if (status != PackageManager.INSTALL_SUCCEEDED) { 12879 cleanUp(move.toUuid); 12880 return false; 12881 } 12882 12883 // Reflect the move in app info 12884 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12885 pkg.setApplicationInfoCodePath(pkg.codePath); 12886 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12887 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12888 pkg.setApplicationInfoResourcePath(pkg.codePath); 12889 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12890 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12891 12892 return true; 12893 } 12894 12895 int doPostInstall(int status, int uid) { 12896 if (status == PackageManager.INSTALL_SUCCEEDED) { 12897 cleanUp(move.fromUuid); 12898 } else { 12899 cleanUp(move.toUuid); 12900 } 12901 return status; 12902 } 12903 12904 @Override 12905 String getCodePath() { 12906 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12907 } 12908 12909 @Override 12910 String getResourcePath() { 12911 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12912 } 12913 12914 private boolean cleanUp(String volumeUuid) { 12915 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 12916 move.dataAppName); 12917 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 12918 synchronized (mInstallLock) { 12919 // Clean up both app data and code 12920 removeDataDirsLI(volumeUuid, move.packageName); 12921 removeCodePathLI(codeFile); 12922 } 12923 return true; 12924 } 12925 12926 void cleanUpResourcesLI() { 12927 throw new UnsupportedOperationException(); 12928 } 12929 12930 boolean doPostDeleteLI(boolean delete) { 12931 throw new UnsupportedOperationException(); 12932 } 12933 } 12934 12935 static String getAsecPackageName(String packageCid) { 12936 int idx = packageCid.lastIndexOf("-"); 12937 if (idx == -1) { 12938 return packageCid; 12939 } 12940 return packageCid.substring(0, idx); 12941 } 12942 12943 // Utility method used to create code paths based on package name and available index. 12944 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 12945 String idxStr = ""; 12946 int idx = 1; 12947 // Fall back to default value of idx=1 if prefix is not 12948 // part of oldCodePath 12949 if (oldCodePath != null) { 12950 String subStr = oldCodePath; 12951 // Drop the suffix right away 12952 if (suffix != null && subStr.endsWith(suffix)) { 12953 subStr = subStr.substring(0, subStr.length() - suffix.length()); 12954 } 12955 // If oldCodePath already contains prefix find out the 12956 // ending index to either increment or decrement. 12957 int sidx = subStr.lastIndexOf(prefix); 12958 if (sidx != -1) { 12959 subStr = subStr.substring(sidx + prefix.length()); 12960 if (subStr != null) { 12961 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 12962 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 12963 } 12964 try { 12965 idx = Integer.parseInt(subStr); 12966 if (idx <= 1) { 12967 idx++; 12968 } else { 12969 idx--; 12970 } 12971 } catch(NumberFormatException e) { 12972 } 12973 } 12974 } 12975 } 12976 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 12977 return prefix + idxStr; 12978 } 12979 12980 private File getNextCodePath(File targetDir, String packageName) { 12981 int suffix = 1; 12982 File result; 12983 do { 12984 result = new File(targetDir, packageName + "-" + suffix); 12985 suffix++; 12986 } while (result.exists()); 12987 return result; 12988 } 12989 12990 // Utility method that returns the relative package path with respect 12991 // to the installation directory. Like say for /data/data/com.test-1.apk 12992 // string com.test-1 is returned. 12993 static String deriveCodePathName(String codePath) { 12994 if (codePath == null) { 12995 return null; 12996 } 12997 final File codeFile = new File(codePath); 12998 final String name = codeFile.getName(); 12999 if (codeFile.isDirectory()) { 13000 return name; 13001 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13002 final int lastDot = name.lastIndexOf('.'); 13003 return name.substring(0, lastDot); 13004 } else { 13005 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13006 return null; 13007 } 13008 } 13009 13010 static class PackageInstalledInfo { 13011 String name; 13012 int uid; 13013 // The set of users that originally had this package installed. 13014 int[] origUsers; 13015 // The set of users that now have this package installed. 13016 int[] newUsers; 13017 PackageParser.Package pkg; 13018 int returnCode; 13019 String returnMsg; 13020 PackageRemovedInfo removedInfo; 13021 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13022 13023 public void setError(int code, String msg) { 13024 setReturnCode(code); 13025 setReturnMessage(msg); 13026 Slog.w(TAG, msg); 13027 } 13028 13029 public void setError(String msg, PackageParserException e) { 13030 setReturnCode(e.error); 13031 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13032 Slog.w(TAG, msg, e); 13033 } 13034 13035 public void setError(String msg, PackageManagerException e) { 13036 returnCode = e.error; 13037 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13038 Slog.w(TAG, msg, e); 13039 } 13040 13041 public void setReturnCode(int returnCode) { 13042 this.returnCode = returnCode; 13043 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13044 for (int i = 0; i < childCount; i++) { 13045 addedChildPackages.valueAt(i).returnCode = returnCode; 13046 } 13047 } 13048 13049 private void setReturnMessage(String returnMsg) { 13050 this.returnMsg = returnMsg; 13051 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13052 for (int i = 0; i < childCount; i++) { 13053 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13054 } 13055 } 13056 13057 // In some error cases we want to convey more info back to the observer 13058 String origPackage; 13059 String origPermission; 13060 } 13061 13062 /* 13063 * Install a non-existing package. 13064 */ 13065 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 13066 UserHandle user, String installerPackageName, String volumeUuid, 13067 PackageInstalledInfo res) { 13068 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13069 13070 // Remember this for later, in case we need to rollback this install 13071 String pkgName = pkg.packageName; 13072 13073 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13074 13075 synchronized(mPackages) { 13076 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13077 // A package with the same name is already installed, though 13078 // it has been renamed to an older name. The package we 13079 // are trying to install should be installed as an update to 13080 // the existing one, but that has not been requested, so bail. 13081 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13082 + " without first uninstalling package running as " 13083 + mSettings.mRenamedPackages.get(pkgName)); 13084 return; 13085 } 13086 if (mPackages.containsKey(pkgName)) { 13087 // Don't allow installation over an existing package with the same name. 13088 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13089 + " without first uninstalling."); 13090 return; 13091 } 13092 } 13093 13094 try { 13095 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 13096 System.currentTimeMillis(), user); 13097 13098 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13099 13100 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13101 prepareAppDataAfterInstall(newPackage); 13102 13103 } else { 13104 // Remove package from internal structures, but keep around any 13105 // data that might have already existed 13106 deletePackageLI(pkgName, UserHandle.ALL, false, null, 13107 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13108 } 13109 } catch (PackageManagerException e) { 13110 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13111 } 13112 13113 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13114 } 13115 13116 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13117 // Can't rotate keys during boot or if sharedUser. 13118 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13119 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13120 return false; 13121 } 13122 // app is using upgradeKeySets; make sure all are valid 13123 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13124 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13125 for (int i = 0; i < upgradeKeySets.length; i++) { 13126 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13127 Slog.wtf(TAG, "Package " 13128 + (oldPs.name != null ? oldPs.name : "<null>") 13129 + " contains upgrade-key-set reference to unknown key-set: " 13130 + upgradeKeySets[i] 13131 + " reverting to signatures check."); 13132 return false; 13133 } 13134 } 13135 return true; 13136 } 13137 13138 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13139 // Upgrade keysets are being used. Determine if new package has a superset of the 13140 // required keys. 13141 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13142 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13143 for (int i = 0; i < upgradeKeySets.length; i++) { 13144 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13145 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13146 return true; 13147 } 13148 } 13149 return false; 13150 } 13151 13152 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 13153 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13154 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13155 13156 final PackageParser.Package oldPackage; 13157 final String pkgName = pkg.packageName; 13158 final int[] allUsers; 13159 final boolean weFroze; 13160 13161 // First find the old package info and check signatures 13162 synchronized(mPackages) { 13163 oldPackage = mPackages.get(pkgName); 13164 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13165 if (isEphemeral && !oldIsEphemeral) { 13166 // can't downgrade from full to ephemeral 13167 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13168 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13169 return; 13170 } 13171 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13172 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13173 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13174 if (!checkUpgradeKeySetLP(ps, pkg)) { 13175 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13176 "New package not signed by keys specified by upgrade-keysets: " 13177 + pkgName); 13178 return; 13179 } 13180 } else { 13181 // default to original signature matching 13182 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13183 != PackageManager.SIGNATURE_MATCH) { 13184 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13185 "New package has a different signature: " + pkgName); 13186 return; 13187 } 13188 } 13189 13190 // In case of rollback, remember per-user/profile install state 13191 allUsers = sUserManager.getUserIds(); 13192 13193 // Mark the app as frozen to prevent launching during the upgrade 13194 // process, and then kill all running instances 13195 if (!ps.frozen) { 13196 ps.frozen = true; 13197 weFroze = true; 13198 } else { 13199 weFroze = false; 13200 } 13201 } 13202 13203 try { 13204 replacePackageDirtyLI(pkg, oldPackage, parseFlags, scanFlags, user, allUsers, 13205 installerPackageName, res); 13206 } finally { 13207 // Regardless of success or failure of upgrade steps above, always 13208 // unfreeze the package if we froze it 13209 if (weFroze) { 13210 unfreezePackage(pkgName); 13211 } 13212 } 13213 } 13214 13215 private void replacePackageDirtyLI(PackageParser.Package pkg, PackageParser.Package oldPackage, 13216 int parseFlags, int scanFlags, UserHandle user, int[] allUsers, 13217 String installerPackageName, PackageInstalledInfo res) { 13218 // Update what is removed 13219 res.removedInfo = new PackageRemovedInfo(); 13220 res.removedInfo.uid = oldPackage.applicationInfo.uid; 13221 res.removedInfo.removedPackage = oldPackage.packageName; 13222 res.removedInfo.isUpdate = true; 13223 final int childCount = (oldPackage.childPackages != null) 13224 ? oldPackage.childPackages.size() : 0; 13225 for (int i = 0; i < childCount; i++) { 13226 boolean childPackageUpdated = false; 13227 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 13228 if (res.addedChildPackages != null) { 13229 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13230 if (childRes != null) { 13231 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 13232 childRes.removedInfo.removedPackage = childPkg.packageName; 13233 childRes.removedInfo.isUpdate = true; 13234 childPackageUpdated = true; 13235 } 13236 } 13237 if (!childPackageUpdated) { 13238 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 13239 childRemovedRes.removedPackage = childPkg.packageName; 13240 childRemovedRes.isUpdate = false; 13241 childRemovedRes.dataRemoved = true; 13242 synchronized (mPackages) { 13243 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13244 if (childPs != null) { 13245 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 13246 } 13247 } 13248 if (res.removedInfo.removedChildPackages == null) { 13249 res.removedInfo.removedChildPackages = new ArrayMap<>(); 13250 } 13251 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 13252 } 13253 } 13254 13255 boolean sysPkg = (isSystemApp(oldPackage)); 13256 if (sysPkg) { 13257 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 13258 user, allUsers, installerPackageName, res); 13259 } else { 13260 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 13261 user, allUsers, installerPackageName, res); 13262 } 13263 } 13264 13265 public List<String> getPreviousCodePaths(String packageName) { 13266 final PackageSetting ps = mSettings.mPackages.get(packageName); 13267 final List<String> result = new ArrayList<String>(); 13268 if (ps != null && ps.oldCodePaths != null) { 13269 result.addAll(ps.oldCodePaths); 13270 } 13271 return result; 13272 } 13273 13274 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 13275 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13276 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13277 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 13278 + deletedPackage); 13279 13280 String pkgName = deletedPackage.packageName; 13281 boolean deletedPkg = true; 13282 boolean addedPkg = false; 13283 boolean updatedSettings = false; 13284 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 13285 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 13286 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 13287 13288 final long origUpdateTime = (pkg.mExtras != null) 13289 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 13290 13291 // First delete the existing package while retaining the data directory 13292 if (!deletePackageLI(pkgName, null, true, allUsers, deleteFlags, 13293 res.removedInfo, true, pkg)) { 13294 // If the existing package wasn't successfully deleted 13295 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 13296 deletedPkg = false; 13297 } else { 13298 // Successfully deleted the old package; proceed with replace. 13299 13300 // If deleted package lived in a container, give users a chance to 13301 // relinquish resources before killing. 13302 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 13303 if (DEBUG_INSTALL) { 13304 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 13305 } 13306 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 13307 final ArrayList<String> pkgList = new ArrayList<String>(1); 13308 pkgList.add(deletedPackage.applicationInfo.packageName); 13309 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 13310 } 13311 13312 deleteCodeCacheDirsLI(pkg); 13313 deleteProfilesLI(pkg, /*destroy*/ false); 13314 13315 try { 13316 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 13317 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 13318 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13319 13320 // Update the in-memory copy of the previous code paths. 13321 PackageSetting ps = mSettings.mPackages.get(pkgName); 13322 if (!killApp) { 13323 if (ps.oldCodePaths == null) { 13324 ps.oldCodePaths = new ArraySet<>(); 13325 } 13326 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 13327 if (deletedPackage.splitCodePaths != null) { 13328 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 13329 } 13330 } else { 13331 ps.oldCodePaths = null; 13332 } 13333 if (ps.childPackageNames != null) { 13334 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 13335 final String childPkgName = ps.childPackageNames.get(i); 13336 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 13337 childPs.oldCodePaths = ps.oldCodePaths; 13338 } 13339 } 13340 prepareAppDataAfterInstall(newPackage); 13341 addedPkg = true; 13342 } catch (PackageManagerException e) { 13343 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13344 } 13345 } 13346 13347 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13348 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 13349 13350 // Revert all internal state mutations and added folders for the failed install 13351 if (addedPkg) { 13352 deletePackageLI(pkgName, null, true, allUsers, deleteFlags, 13353 res.removedInfo, true, null); 13354 } 13355 13356 // Restore the old package 13357 if (deletedPkg) { 13358 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 13359 File restoreFile = new File(deletedPackage.codePath); 13360 // Parse old package 13361 boolean oldExternal = isExternal(deletedPackage); 13362 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 13363 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 13364 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 13365 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 13366 try { 13367 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 13368 null); 13369 } catch (PackageManagerException e) { 13370 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 13371 + e.getMessage()); 13372 return; 13373 } 13374 13375 synchronized (mPackages) { 13376 // Ensure the installer package name up to date 13377 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13378 13379 // Update permissions for restored package 13380 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13381 13382 mSettings.writeLPr(); 13383 } 13384 13385 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 13386 } 13387 } else { 13388 synchronized (mPackages) { 13389 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 13390 if (ps != null) { 13391 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 13392 if (res.removedInfo.removedChildPackages != null) { 13393 final int childCount = res.removedInfo.removedChildPackages.size(); 13394 // Iterate in reverse as we may modify the collection 13395 for (int i = childCount - 1; i >= 0; i--) { 13396 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 13397 if (res.addedChildPackages.containsKey(childPackageName)) { 13398 res.removedInfo.removedChildPackages.removeAt(i); 13399 } else { 13400 PackageRemovedInfo childInfo = res.removedInfo 13401 .removedChildPackages.valueAt(i); 13402 childInfo.removedForAllUsers = mPackages.get( 13403 childInfo.removedPackage) == null; 13404 } 13405 } 13406 } 13407 } 13408 } 13409 } 13410 } 13411 13412 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 13413 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13414 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13415 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 13416 + ", old=" + deletedPackage); 13417 13418 final boolean disabledSystem; 13419 13420 // Set the system/privileged flags as needed 13421 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 13422 if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 13423 != 0) { 13424 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13425 } 13426 13427 // Kill package processes including services, providers, etc. 13428 killPackage(deletedPackage, "replace sys pkg"); 13429 13430 // Remove existing system package 13431 removePackageLI(deletedPackage, true); 13432 13433 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 13434 if (!disabledSystem) { 13435 // We didn't need to disable the .apk as a current system package, 13436 // which means we are replacing another update that is already 13437 // installed. We need to make sure to delete the older one's .apk. 13438 res.removedInfo.args = createInstallArgsForExisting(0, 13439 deletedPackage.applicationInfo.getCodePath(), 13440 deletedPackage.applicationInfo.getResourcePath(), 13441 getAppDexInstructionSets(deletedPackage.applicationInfo)); 13442 } else { 13443 res.removedInfo.args = null; 13444 } 13445 13446 // Successfully disabled the old package. Now proceed with re-installation 13447 deleteCodeCacheDirsLI(pkg); 13448 deleteProfilesLI(pkg, /*destroy*/ false); 13449 13450 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13451 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 13452 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 13453 13454 PackageParser.Package newPackage = null; 13455 try { 13456 // Add the package to the internal data structures 13457 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 13458 13459 // Set the update and install times 13460 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 13461 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 13462 System.currentTimeMillis()); 13463 13464 // Check for shared user id changes 13465 String invalidPackageName = getParentOrChildPackageChangedSharedUser( 13466 deletedPackage, newPackage); 13467 if (invalidPackageName != null) { 13468 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13469 "Forbidding shared user change from " + deletedPkgSetting.sharedUser 13470 + " to " + invalidPackageName); 13471 } 13472 13473 // Update the package dynamic state if succeeded 13474 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13475 // Now that the install succeeded make sure we remove data 13476 // directories for any child package the update removed. 13477 final int deletedChildCount = (deletedPackage.childPackages != null) 13478 ? deletedPackage.childPackages.size() : 0; 13479 final int newChildCount = (newPackage.childPackages != null) 13480 ? newPackage.childPackages.size() : 0; 13481 for (int i = 0; i < deletedChildCount; i++) { 13482 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 13483 boolean childPackageDeleted = true; 13484 for (int j = 0; j < newChildCount; j++) { 13485 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 13486 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 13487 childPackageDeleted = false; 13488 break; 13489 } 13490 } 13491 if (childPackageDeleted) { 13492 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 13493 deletedChildPkg.packageName); 13494 if (ps != null && res.removedInfo.removedChildPackages != null) { 13495 PackageRemovedInfo removedChildRes = res.removedInfo 13496 .removedChildPackages.get(deletedChildPkg.packageName); 13497 removePackageDataLI(ps, allUsers, removedChildRes, 0, false); 13498 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 13499 } 13500 } 13501 } 13502 13503 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13504 prepareAppDataAfterInstall(newPackage); 13505 } 13506 } catch (PackageManagerException e) { 13507 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 13508 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13509 } 13510 13511 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13512 // Re installation failed. Restore old information 13513 // Remove new pkg information 13514 if (newPackage != null) { 13515 removeInstalledPackageLI(newPackage, true); 13516 } 13517 // Add back the old system package 13518 try { 13519 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 13520 } catch (PackageManagerException e) { 13521 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 13522 } 13523 13524 synchronized (mPackages) { 13525 if (disabledSystem) { 13526 enableSystemPackageLPw(deletedPackage); 13527 } 13528 13529 // Ensure the installer package name up to date 13530 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13531 13532 // Update permissions for restored package 13533 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13534 13535 mSettings.writeLPr(); 13536 } 13537 13538 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 13539 + " after failed upgrade"); 13540 } 13541 } 13542 13543 /** 13544 * Checks whether the parent or any of the child packages have a change shared 13545 * user. For a package to be a valid update the shred users of the parent and 13546 * the children should match. We may later support changing child shared users. 13547 * @param oldPkg The updated package. 13548 * @param newPkg The update package. 13549 * @return The shared user that change between the versions. 13550 */ 13551 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 13552 PackageParser.Package newPkg) { 13553 // Check parent shared user 13554 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 13555 return newPkg.packageName; 13556 } 13557 // Check child shared users 13558 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13559 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 13560 for (int i = 0; i < newChildCount; i++) { 13561 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 13562 // If this child was present, did it have the same shared user? 13563 for (int j = 0; j < oldChildCount; j++) { 13564 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 13565 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 13566 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 13567 return newChildPkg.packageName; 13568 } 13569 } 13570 } 13571 return null; 13572 } 13573 13574 private void removeNativeBinariesLI(PackageSetting ps) { 13575 // Remove the lib path for the parent package 13576 if (ps != null) { 13577 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 13578 // Remove the lib path for the child packages 13579 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 13580 for (int i = 0; i < childCount; i++) { 13581 PackageSetting childPs = null; 13582 synchronized (mPackages) { 13583 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 13584 } 13585 if (childPs != null) { 13586 NativeLibraryHelper.removeNativeBinariesLI(childPs 13587 .legacyNativeLibraryPathString); 13588 } 13589 } 13590 } 13591 } 13592 13593 private void enableSystemPackageLPw(PackageParser.Package pkg) { 13594 // Enable the parent package 13595 mSettings.enableSystemPackageLPw(pkg.packageName); 13596 // Enable the child packages 13597 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13598 for (int i = 0; i < childCount; i++) { 13599 PackageParser.Package childPkg = pkg.childPackages.get(i); 13600 mSettings.enableSystemPackageLPw(childPkg.packageName); 13601 } 13602 } 13603 13604 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 13605 PackageParser.Package newPkg) { 13606 // Disable the parent package (parent always replaced) 13607 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 13608 // Disable the child packages 13609 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13610 for (int i = 0; i < childCount; i++) { 13611 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 13612 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 13613 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 13614 } 13615 return disabled; 13616 } 13617 13618 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 13619 String installerPackageName) { 13620 // Enable the parent package 13621 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 13622 // Enable the child packages 13623 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13624 for (int i = 0; i < childCount; i++) { 13625 PackageParser.Package childPkg = pkg.childPackages.get(i); 13626 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 13627 } 13628 } 13629 13630 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 13631 // Collect all used permissions in the UID 13632 ArraySet<String> usedPermissions = new ArraySet<>(); 13633 final int packageCount = su.packages.size(); 13634 for (int i = 0; i < packageCount; i++) { 13635 PackageSetting ps = su.packages.valueAt(i); 13636 if (ps.pkg == null) { 13637 continue; 13638 } 13639 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 13640 for (int j = 0; j < requestedPermCount; j++) { 13641 String permission = ps.pkg.requestedPermissions.get(j); 13642 BasePermission bp = mSettings.mPermissions.get(permission); 13643 if (bp != null) { 13644 usedPermissions.add(permission); 13645 } 13646 } 13647 } 13648 13649 PermissionsState permissionsState = su.getPermissionsState(); 13650 // Prune install permissions 13651 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 13652 final int installPermCount = installPermStates.size(); 13653 for (int i = installPermCount - 1; i >= 0; i--) { 13654 PermissionState permissionState = installPermStates.get(i); 13655 if (!usedPermissions.contains(permissionState.getName())) { 13656 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 13657 if (bp != null) { 13658 permissionsState.revokeInstallPermission(bp); 13659 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 13660 PackageManager.MASK_PERMISSION_FLAGS, 0); 13661 } 13662 } 13663 } 13664 13665 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 13666 13667 // Prune runtime permissions 13668 for (int userId : allUserIds) { 13669 List<PermissionState> runtimePermStates = permissionsState 13670 .getRuntimePermissionStates(userId); 13671 final int runtimePermCount = runtimePermStates.size(); 13672 for (int i = runtimePermCount - 1; i >= 0; i--) { 13673 PermissionState permissionState = runtimePermStates.get(i); 13674 if (!usedPermissions.contains(permissionState.getName())) { 13675 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 13676 if (bp != null) { 13677 permissionsState.revokeRuntimePermission(bp, userId); 13678 permissionsState.updatePermissionFlags(bp, userId, 13679 PackageManager.MASK_PERMISSION_FLAGS, 0); 13680 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 13681 runtimePermissionChangedUserIds, userId); 13682 } 13683 } 13684 } 13685 } 13686 13687 return runtimePermissionChangedUserIds; 13688 } 13689 13690 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 13691 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 13692 // Update the parent package setting 13693 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 13694 res, user); 13695 // Update the child packages setting 13696 final int childCount = (newPackage.childPackages != null) 13697 ? newPackage.childPackages.size() : 0; 13698 for (int i = 0; i < childCount; i++) { 13699 PackageParser.Package childPackage = newPackage.childPackages.get(i); 13700 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 13701 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 13702 childRes.origUsers, childRes, user); 13703 } 13704 } 13705 13706 private void updateSettingsInternalLI(PackageParser.Package newPackage, 13707 String installerPackageName, int[] allUsers, int[] installedForUsers, 13708 PackageInstalledInfo res, UserHandle user) { 13709 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 13710 13711 String pkgName = newPackage.packageName; 13712 synchronized (mPackages) { 13713 //write settings. the installStatus will be incomplete at this stage. 13714 //note that the new package setting would have already been 13715 //added to mPackages. It hasn't been persisted yet. 13716 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 13717 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 13718 mSettings.writeLPr(); 13719 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13720 } 13721 13722 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 13723 synchronized (mPackages) { 13724 updatePermissionsLPw(newPackage.packageName, newPackage, 13725 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 13726 ? UPDATE_PERMISSIONS_ALL : 0)); 13727 // For system-bundled packages, we assume that installing an upgraded version 13728 // of the package implies that the user actually wants to run that new code, 13729 // so we enable the package. 13730 PackageSetting ps = mSettings.mPackages.get(pkgName); 13731 final int userId = user.getIdentifier(); 13732 if (ps != null) { 13733 if (isSystemApp(newPackage)) { 13734 if (DEBUG_INSTALL) { 13735 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 13736 } 13737 // Enable system package for requested users 13738 if (res.origUsers != null) { 13739 for (int origUserId : res.origUsers) { 13740 if (userId == UserHandle.USER_ALL || userId == origUserId) { 13741 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 13742 origUserId, installerPackageName); 13743 } 13744 } 13745 } 13746 // Also convey the prior install/uninstall state 13747 if (allUsers != null && installedForUsers != null) { 13748 for (int currentUserId : allUsers) { 13749 final boolean installed = ArrayUtils.contains( 13750 installedForUsers, currentUserId); 13751 if (DEBUG_INSTALL) { 13752 Slog.d(TAG, " user " + currentUserId + " => " + installed); 13753 } 13754 ps.setInstalled(installed, currentUserId); 13755 } 13756 // these install state changes will be persisted in the 13757 // upcoming call to mSettings.writeLPr(). 13758 } 13759 } 13760 // It's implied that when a user requests installation, they want the app to be 13761 // installed and enabled. 13762 if (userId != UserHandle.USER_ALL) { 13763 ps.setInstalled(true, userId); 13764 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 13765 } 13766 } 13767 res.name = pkgName; 13768 res.uid = newPackage.applicationInfo.uid; 13769 res.pkg = newPackage; 13770 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 13771 mSettings.setInstallerPackageName(pkgName, installerPackageName); 13772 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13773 //to update install status 13774 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 13775 mSettings.writeLPr(); 13776 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13777 } 13778 13779 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13780 } 13781 13782 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 13783 try { 13784 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 13785 installPackageLI(args, res); 13786 } finally { 13787 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13788 } 13789 } 13790 13791 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 13792 final int installFlags = args.installFlags; 13793 final String installerPackageName = args.installerPackageName; 13794 final String volumeUuid = args.volumeUuid; 13795 final File tmpPackageFile = new File(args.getCodePath()); 13796 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 13797 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 13798 || (args.volumeUuid != null)); 13799 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 13800 boolean replace = false; 13801 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 13802 if (args.move != null) { 13803 // moving a complete application; perform an initial scan on the new install location 13804 scanFlags |= SCAN_INITIAL; 13805 } 13806 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 13807 scanFlags |= SCAN_DONT_KILL_APP; 13808 } 13809 13810 // Result object to be returned 13811 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13812 13813 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 13814 13815 // Sanity check 13816 if (ephemeral && (forwardLocked || onExternal)) { 13817 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 13818 + " external=" + onExternal); 13819 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13820 return; 13821 } 13822 13823 // Retrieve PackageSettings and parse package 13824 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 13825 | PackageParser.PARSE_ENFORCE_CODE 13826 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 13827 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 13828 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 13829 PackageParser pp = new PackageParser(); 13830 pp.setSeparateProcesses(mSeparateProcesses); 13831 pp.setDisplayMetrics(mMetrics); 13832 13833 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 13834 final PackageParser.Package pkg; 13835 try { 13836 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 13837 } catch (PackageParserException e) { 13838 res.setError("Failed parse during installPackageLI", e); 13839 return; 13840 } finally { 13841 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13842 } 13843 13844 // If we are installing a clustered package add results for the children 13845 if (pkg.childPackages != null) { 13846 synchronized (mPackages) { 13847 final int childCount = pkg.childPackages.size(); 13848 for (int i = 0; i < childCount; i++) { 13849 PackageParser.Package childPkg = pkg.childPackages.get(i); 13850 PackageInstalledInfo childRes = new PackageInstalledInfo(); 13851 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13852 childRes.pkg = childPkg; 13853 childRes.name = childPkg.packageName; 13854 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13855 if (childPs != null) { 13856 childRes.origUsers = childPs.queryInstalledUsers( 13857 sUserManager.getUserIds(), true); 13858 } 13859 if ((mPackages.containsKey(childPkg.packageName))) { 13860 childRes.removedInfo = new PackageRemovedInfo(); 13861 childRes.removedInfo.removedPackage = childPkg.packageName; 13862 } 13863 if (res.addedChildPackages == null) { 13864 res.addedChildPackages = new ArrayMap<>(); 13865 } 13866 res.addedChildPackages.put(childPkg.packageName, childRes); 13867 } 13868 } 13869 } 13870 13871 // If package doesn't declare API override, mark that we have an install 13872 // time CPU ABI override. 13873 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 13874 pkg.cpuAbiOverride = args.abiOverride; 13875 } 13876 13877 String pkgName = res.name = pkg.packageName; 13878 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 13879 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 13880 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 13881 return; 13882 } 13883 } 13884 13885 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 13886 try { 13887 PackageParser.collectCertificates(pkg, parseFlags); 13888 } catch (PackageParserException e) { 13889 res.setError("Failed collect during installPackageLI", e); 13890 return; 13891 } finally { 13892 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13893 } 13894 13895 // Get rid of all references to package scan path via parser. 13896 pp = null; 13897 String oldCodePath = null; 13898 boolean systemApp = false; 13899 synchronized (mPackages) { 13900 // Check if installing already existing package 13901 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 13902 String oldName = mSettings.mRenamedPackages.get(pkgName); 13903 if (pkg.mOriginalPackages != null 13904 && pkg.mOriginalPackages.contains(oldName) 13905 && mPackages.containsKey(oldName)) { 13906 // This package is derived from an original package, 13907 // and this device has been updating from that original 13908 // name. We must continue using the original name, so 13909 // rename the new package here. 13910 pkg.setPackageName(oldName); 13911 pkgName = pkg.packageName; 13912 replace = true; 13913 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 13914 + oldName + " pkgName=" + pkgName); 13915 } else if (mPackages.containsKey(pkgName)) { 13916 // This package, under its official name, already exists 13917 // on the device; we should replace it. 13918 replace = true; 13919 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 13920 } 13921 13922 // Child packages are installed through the parent package 13923 if (pkg.parentPackage != null) { 13924 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 13925 "Package " + pkg.packageName + " is child of package " 13926 + pkg.parentPackage.parentPackage + ". Child packages " 13927 + "can be updated only through the parent package."); 13928 return; 13929 } 13930 13931 if (replace) { 13932 // Prevent apps opting out from runtime permissions 13933 PackageParser.Package oldPackage = mPackages.get(pkgName); 13934 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 13935 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 13936 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 13937 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 13938 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 13939 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 13940 + " doesn't support runtime permissions but the old" 13941 + " target SDK " + oldTargetSdk + " does."); 13942 return; 13943 } 13944 13945 // Prevent installing of child packages 13946 if (oldPackage.parentPackage != null) { 13947 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 13948 "Package " + pkg.packageName + " is child of package " 13949 + oldPackage.parentPackage + ". Child packages " 13950 + "can be updated only through the parent package."); 13951 return; 13952 } 13953 } 13954 } 13955 13956 PackageSetting ps = mSettings.mPackages.get(pkgName); 13957 if (ps != null) { 13958 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 13959 13960 // Quick sanity check that we're signed correctly if updating; 13961 // we'll check this again later when scanning, but we want to 13962 // bail early here before tripping over redefined permissions. 13963 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13964 if (!checkUpgradeKeySetLP(ps, pkg)) { 13965 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 13966 + pkg.packageName + " upgrade keys do not match the " 13967 + "previously installed version"); 13968 return; 13969 } 13970 } else { 13971 try { 13972 verifySignaturesLP(ps, pkg); 13973 } catch (PackageManagerException e) { 13974 res.setError(e.error, e.getMessage()); 13975 return; 13976 } 13977 } 13978 13979 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 13980 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 13981 systemApp = (ps.pkg.applicationInfo.flags & 13982 ApplicationInfo.FLAG_SYSTEM) != 0; 13983 } 13984 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13985 } 13986 13987 // Check whether the newly-scanned package wants to define an already-defined perm 13988 int N = pkg.permissions.size(); 13989 for (int i = N-1; i >= 0; i--) { 13990 PackageParser.Permission perm = pkg.permissions.get(i); 13991 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 13992 if (bp != null) { 13993 // If the defining package is signed with our cert, it's okay. This 13994 // also includes the "updating the same package" case, of course. 13995 // "updating same package" could also involve key-rotation. 13996 final boolean sigsOk; 13997 if (bp.sourcePackage.equals(pkg.packageName) 13998 && (bp.packageSetting instanceof PackageSetting) 13999 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14000 scanFlags))) { 14001 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14002 } else { 14003 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14004 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14005 } 14006 if (!sigsOk) { 14007 // If the owning package is the system itself, we log but allow 14008 // install to proceed; we fail the install on all other permission 14009 // redefinitions. 14010 if (!bp.sourcePackage.equals("android")) { 14011 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14012 + pkg.packageName + " attempting to redeclare permission " 14013 + perm.info.name + " already owned by " + bp.sourcePackage); 14014 res.origPermission = perm.info.name; 14015 res.origPackage = bp.sourcePackage; 14016 return; 14017 } else { 14018 Slog.w(TAG, "Package " + pkg.packageName 14019 + " attempting to redeclare system permission " 14020 + perm.info.name + "; ignoring new declaration"); 14021 pkg.permissions.remove(i); 14022 } 14023 } 14024 } 14025 } 14026 } 14027 14028 if (systemApp) { 14029 if (onExternal) { 14030 // Abort update; system app can't be replaced with app on sdcard 14031 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14032 "Cannot install updates to system apps on sdcard"); 14033 return; 14034 } else if (ephemeral) { 14035 // Abort update; system app can't be replaced with an ephemeral app 14036 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14037 "Cannot update a system app with an ephemeral app"); 14038 return; 14039 } 14040 } 14041 14042 if (args.move != null) { 14043 // We did an in-place move, so dex is ready to roll 14044 scanFlags |= SCAN_NO_DEX; 14045 scanFlags |= SCAN_MOVE; 14046 14047 synchronized (mPackages) { 14048 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14049 if (ps == null) { 14050 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14051 "Missing settings for moved package " + pkgName); 14052 } 14053 14054 // We moved the entire application as-is, so bring over the 14055 // previously derived ABI information. 14056 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14057 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14058 } 14059 14060 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14061 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14062 scanFlags |= SCAN_NO_DEX; 14063 14064 try { 14065 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14066 args.abiOverride : pkg.cpuAbiOverride); 14067 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14068 true /* extract libs */); 14069 } catch (PackageManagerException pme) { 14070 Slog.e(TAG, "Error deriving application ABI", pme); 14071 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14072 return; 14073 } 14074 14075 14076 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14077 // Do not run PackageDexOptimizer through the local performDexOpt 14078 // method because `pkg` is not in `mPackages` yet. 14079 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 14080 false /* checkProfiles */, getCompilerFilterForReason(REASON_INSTALL)); 14081 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14082 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14083 String msg = "Extracking package failed for " + pkgName; 14084 res.setError(INSTALL_FAILED_DEXOPT, msg); 14085 return; 14086 } 14087 } 14088 14089 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14090 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14091 return; 14092 } 14093 14094 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14095 14096 if (replace) { 14097 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14098 installerPackageName, res); 14099 } else { 14100 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14101 args.user, installerPackageName, volumeUuid, res); 14102 } 14103 synchronized (mPackages) { 14104 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14105 if (ps != null) { 14106 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14107 } 14108 14109 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14110 for (int i = 0; i < childCount; i++) { 14111 PackageParser.Package childPkg = pkg.childPackages.get(i); 14112 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14113 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14114 if (childPs != null) { 14115 childRes.newUsers = childPs.queryInstalledUsers( 14116 sUserManager.getUserIds(), true); 14117 } 14118 } 14119 } 14120 } 14121 14122 private void startIntentFilterVerifications(int userId, boolean replacing, 14123 PackageParser.Package pkg) { 14124 if (mIntentFilterVerifierComponent == null) { 14125 Slog.w(TAG, "No IntentFilter verification will not be done as " 14126 + "there is no IntentFilterVerifier available!"); 14127 return; 14128 } 14129 14130 final int verifierUid = getPackageUid( 14131 mIntentFilterVerifierComponent.getPackageName(), 14132 MATCH_DEBUG_TRIAGED_MISSING, 14133 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 14134 14135 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14136 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14137 mHandler.sendMessage(msg); 14138 14139 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14140 for (int i = 0; i < childCount; i++) { 14141 PackageParser.Package childPkg = pkg.childPackages.get(i); 14142 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14143 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 14144 mHandler.sendMessage(msg); 14145 } 14146 } 14147 14148 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 14149 PackageParser.Package pkg) { 14150 int size = pkg.activities.size(); 14151 if (size == 0) { 14152 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14153 "No activity, so no need to verify any IntentFilter!"); 14154 return; 14155 } 14156 14157 final boolean hasDomainURLs = hasDomainURLs(pkg); 14158 if (!hasDomainURLs) { 14159 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14160 "No domain URLs, so no need to verify any IntentFilter!"); 14161 return; 14162 } 14163 14164 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 14165 + " if any IntentFilter from the " + size 14166 + " Activities needs verification ..."); 14167 14168 int count = 0; 14169 final String packageName = pkg.packageName; 14170 14171 synchronized (mPackages) { 14172 // If this is a new install and we see that we've already run verification for this 14173 // package, we have nothing to do: it means the state was restored from backup. 14174 if (!replacing) { 14175 IntentFilterVerificationInfo ivi = 14176 mSettings.getIntentFilterVerificationLPr(packageName); 14177 if (ivi != null) { 14178 if (DEBUG_DOMAIN_VERIFICATION) { 14179 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 14180 + ivi.getStatusString()); 14181 } 14182 return; 14183 } 14184 } 14185 14186 // If any filters need to be verified, then all need to be. 14187 boolean needToVerify = false; 14188 for (PackageParser.Activity a : pkg.activities) { 14189 for (ActivityIntentInfo filter : a.intents) { 14190 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 14191 if (DEBUG_DOMAIN_VERIFICATION) { 14192 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 14193 } 14194 needToVerify = true; 14195 break; 14196 } 14197 } 14198 } 14199 14200 if (needToVerify) { 14201 final int verificationId = mIntentFilterVerificationToken++; 14202 for (PackageParser.Activity a : pkg.activities) { 14203 for (ActivityIntentInfo filter : a.intents) { 14204 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 14205 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14206 "Verification needed for IntentFilter:" + filter.toString()); 14207 mIntentFilterVerifier.addOneIntentFilterVerification( 14208 verifierUid, userId, verificationId, filter, packageName); 14209 count++; 14210 } 14211 } 14212 } 14213 } 14214 } 14215 14216 if (count > 0) { 14217 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 14218 + " IntentFilter verification" + (count > 1 ? "s" : "") 14219 + " for userId:" + userId); 14220 mIntentFilterVerifier.startVerifications(userId); 14221 } else { 14222 if (DEBUG_DOMAIN_VERIFICATION) { 14223 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 14224 } 14225 } 14226 } 14227 14228 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 14229 final ComponentName cn = filter.activity.getComponentName(); 14230 final String packageName = cn.getPackageName(); 14231 14232 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 14233 packageName); 14234 if (ivi == null) { 14235 return true; 14236 } 14237 int status = ivi.getStatus(); 14238 switch (status) { 14239 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 14240 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 14241 return true; 14242 14243 default: 14244 // Nothing to do 14245 return false; 14246 } 14247 } 14248 14249 private static boolean isMultiArch(ApplicationInfo info) { 14250 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 14251 } 14252 14253 private static boolean isExternal(PackageParser.Package pkg) { 14254 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14255 } 14256 14257 private static boolean isExternal(PackageSetting ps) { 14258 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14259 } 14260 14261 private static boolean isEphemeral(PackageParser.Package pkg) { 14262 return pkg.applicationInfo.isEphemeralApp(); 14263 } 14264 14265 private static boolean isEphemeral(PackageSetting ps) { 14266 return ps.pkg != null && isEphemeral(ps.pkg); 14267 } 14268 14269 private static boolean isSystemApp(PackageParser.Package pkg) { 14270 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 14271 } 14272 14273 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 14274 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14275 } 14276 14277 private static boolean hasDomainURLs(PackageParser.Package pkg) { 14278 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 14279 } 14280 14281 private static boolean isSystemApp(PackageSetting ps) { 14282 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 14283 } 14284 14285 private static boolean isUpdatedSystemApp(PackageSetting ps) { 14286 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 14287 } 14288 14289 private int packageFlagsToInstallFlags(PackageSetting ps) { 14290 int installFlags = 0; 14291 if (isEphemeral(ps)) { 14292 installFlags |= PackageManager.INSTALL_EPHEMERAL; 14293 } 14294 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 14295 // This existing package was an external ASEC install when we have 14296 // the external flag without a UUID 14297 installFlags |= PackageManager.INSTALL_EXTERNAL; 14298 } 14299 if (ps.isForwardLocked()) { 14300 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 14301 } 14302 return installFlags; 14303 } 14304 14305 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 14306 if (isExternal(pkg)) { 14307 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14308 return StorageManager.UUID_PRIMARY_PHYSICAL; 14309 } else { 14310 return pkg.volumeUuid; 14311 } 14312 } else { 14313 return StorageManager.UUID_PRIVATE_INTERNAL; 14314 } 14315 } 14316 14317 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 14318 if (isExternal(pkg)) { 14319 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14320 return mSettings.getExternalVersion(); 14321 } else { 14322 return mSettings.findOrCreateVersion(pkg.volumeUuid); 14323 } 14324 } else { 14325 return mSettings.getInternalVersion(); 14326 } 14327 } 14328 14329 private void deleteTempPackageFiles() { 14330 final FilenameFilter filter = new FilenameFilter() { 14331 public boolean accept(File dir, String name) { 14332 return name.startsWith("vmdl") && name.endsWith(".tmp"); 14333 } 14334 }; 14335 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 14336 file.delete(); 14337 } 14338 } 14339 14340 @Override 14341 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 14342 int flags) { 14343 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 14344 flags); 14345 } 14346 14347 @Override 14348 public void deletePackage(final String packageName, 14349 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 14350 mContext.enforceCallingOrSelfPermission( 14351 android.Manifest.permission.DELETE_PACKAGES, null); 14352 Preconditions.checkNotNull(packageName); 14353 Preconditions.checkNotNull(observer); 14354 final int uid = Binder.getCallingUid(); 14355 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 14356 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 14357 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 14358 mContext.enforceCallingOrSelfPermission( 14359 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14360 "deletePackage for user " + userId); 14361 } 14362 14363 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 14364 try { 14365 observer.onPackageDeleted(packageName, 14366 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 14367 } catch (RemoteException re) { 14368 } 14369 return; 14370 } 14371 14372 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 14373 try { 14374 observer.onPackageDeleted(packageName, 14375 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 14376 } catch (RemoteException re) { 14377 } 14378 return; 14379 } 14380 14381 if (DEBUG_REMOVE) { 14382 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 14383 + " deleteAllUsers: " + deleteAllUsers ); 14384 } 14385 // Queue up an async operation since the package deletion may take a little while. 14386 mHandler.post(new Runnable() { 14387 public void run() { 14388 mHandler.removeCallbacks(this); 14389 int returnCode; 14390 if (!deleteAllUsers) { 14391 returnCode = deletePackageX(packageName, userId, flags); 14392 } else { 14393 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 14394 // If nobody is blocking uninstall, proceed with delete for all users 14395 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 14396 returnCode = deletePackageX(packageName, userId, flags); 14397 } else { 14398 // Otherwise uninstall individually for users with blockUninstalls=false 14399 final int userFlags = flags & ~PackageManager.DELETE_ALL_USERS; 14400 for (int userId : users) { 14401 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 14402 returnCode = deletePackageX(packageName, userId, userFlags); 14403 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 14404 Slog.w(TAG, "Package delete failed for user " + userId 14405 + ", returnCode " + returnCode); 14406 } 14407 } 14408 } 14409 // The app has only been marked uninstalled for certain users. 14410 // We still need to report that delete was blocked 14411 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 14412 } 14413 } 14414 try { 14415 observer.onPackageDeleted(packageName, returnCode, null); 14416 } catch (RemoteException e) { 14417 Log.i(TAG, "Observer no longer exists."); 14418 } //end catch 14419 } //end run 14420 }); 14421 } 14422 14423 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 14424 int[] result = EMPTY_INT_ARRAY; 14425 for (int userId : userIds) { 14426 if (getBlockUninstallForUser(packageName, userId)) { 14427 result = ArrayUtils.appendInt(result, userId); 14428 } 14429 } 14430 return result; 14431 } 14432 14433 @Override 14434 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 14435 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 14436 } 14437 14438 private boolean isPackageDeviceAdmin(String packageName, int userId) { 14439 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 14440 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 14441 try { 14442 if (dpm != null) { 14443 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 14444 /* callingUserOnly =*/ false); 14445 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 14446 : deviceOwnerComponentName.getPackageName(); 14447 // Does the package contains the device owner? 14448 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 14449 // this check is probably not needed, since DO should be registered as a device 14450 // admin on some user too. (Original bug for this: b/17657954) 14451 if (packageName.equals(deviceOwnerPackageName)) { 14452 return true; 14453 } 14454 // Does it contain a device admin for any user? 14455 int[] users; 14456 if (userId == UserHandle.USER_ALL) { 14457 users = sUserManager.getUserIds(); 14458 } else { 14459 users = new int[]{userId}; 14460 } 14461 for (int i = 0; i < users.length; ++i) { 14462 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 14463 return true; 14464 } 14465 } 14466 } 14467 } catch (RemoteException e) { 14468 } 14469 return false; 14470 } 14471 14472 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 14473 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 14474 } 14475 14476 /** 14477 * This method is an internal method that could be get invoked either 14478 * to delete an installed package or to clean up a failed installation. 14479 * After deleting an installed package, a broadcast is sent to notify any 14480 * listeners that the package has been installed. For cleaning up a failed 14481 * installation, the broadcast is not necessary since the package's 14482 * installation wouldn't have sent the initial broadcast either 14483 * The key steps in deleting a package are 14484 * deleting the package information in internal structures like mPackages, 14485 * deleting the packages base directories through installd 14486 * updating mSettings to reflect current status 14487 * persisting settings for later use 14488 * sending a broadcast if necessary 14489 */ 14490 private int deletePackageX(String packageName, int userId, int flags) { 14491 final PackageRemovedInfo info = new PackageRemovedInfo(); 14492 final boolean res; 14493 14494 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 14495 ? UserHandle.ALL : new UserHandle(userId); 14496 14497 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 14498 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 14499 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 14500 } 14501 14502 PackageSetting uninstalledPs = null; 14503 14504 // for the uninstall-updates case and restricted profiles, remember the per- 14505 // user handle installed state 14506 int[] allUsers; 14507 synchronized (mPackages) { 14508 uninstalledPs = mSettings.mPackages.get(packageName); 14509 if (uninstalledPs == null) { 14510 Slog.w(TAG, "Not removing non-existent package " + packageName); 14511 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14512 } 14513 allUsers = sUserManager.getUserIds(); 14514 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 14515 } 14516 14517 synchronized (mInstallLock) { 14518 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 14519 res = deletePackageLI(packageName, removeForUser, true, allUsers, 14520 flags | REMOVE_CHATTY, info, true, null); 14521 deleteProfilesLI(packageName, /*destroy*/ true); 14522 synchronized (mPackages) { 14523 if (res) { 14524 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 14525 } 14526 } 14527 } 14528 14529 if (res) { 14530 final boolean killApp = (flags & PackageManager.INSTALL_DONT_KILL_APP) == 0; 14531 info.sendPackageRemovedBroadcasts(killApp); 14532 info.sendSystemPackageUpdatedBroadcasts(); 14533 info.sendSystemPackageAppearedBroadcasts(); 14534 } 14535 // Force a gc here. 14536 Runtime.getRuntime().gc(); 14537 // Delete the resources here after sending the broadcast to let 14538 // other processes clean up before deleting resources. 14539 if (info.args != null) { 14540 synchronized (mInstallLock) { 14541 info.args.doPostDeleteLI(true); 14542 } 14543 } 14544 14545 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14546 } 14547 14548 class PackageRemovedInfo { 14549 String removedPackage; 14550 int uid = -1; 14551 int removedAppId = -1; 14552 int[] origUsers; 14553 int[] removedUsers = null; 14554 boolean isRemovedPackageSystemUpdate = false; 14555 boolean isUpdate; 14556 boolean dataRemoved; 14557 boolean removedForAllUsers; 14558 // Clean up resources deleted packages. 14559 InstallArgs args = null; 14560 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 14561 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 14562 14563 void sendPackageRemovedBroadcasts(boolean killApp) { 14564 sendPackageRemovedBroadcastInternal(killApp); 14565 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 14566 for (int i = 0; i < childCount; i++) { 14567 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 14568 childInfo.sendPackageRemovedBroadcastInternal(killApp); 14569 } 14570 } 14571 14572 void sendSystemPackageUpdatedBroadcasts() { 14573 if (isRemovedPackageSystemUpdate) { 14574 sendSystemPackageUpdatedBroadcastsInternal(); 14575 final int childCount = (removedChildPackages != null) 14576 ? removedChildPackages.size() : 0; 14577 for (int i = 0; i < childCount; i++) { 14578 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 14579 if (childInfo.isRemovedPackageSystemUpdate) { 14580 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 14581 } 14582 } 14583 } 14584 } 14585 14586 void sendSystemPackageAppearedBroadcasts() { 14587 final int packageCount = (appearedChildPackages != null) 14588 ? appearedChildPackages.size() : 0; 14589 for (int i = 0; i < packageCount; i++) { 14590 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 14591 for (int userId : installedInfo.newUsers) { 14592 sendPackageAddedForUser(installedInfo.name, true, 14593 UserHandle.getAppId(installedInfo.uid), userId); 14594 } 14595 } 14596 } 14597 14598 private void sendSystemPackageUpdatedBroadcastsInternal() { 14599 Bundle extras = new Bundle(2); 14600 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 14601 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14602 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 14603 extras, 0, null, null, null); 14604 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 14605 extras, 0, null, null, null); 14606 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 14607 null, 0, removedPackage, null, null); 14608 } 14609 14610 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 14611 Bundle extras = new Bundle(2); 14612 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 14613 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 14614 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 14615 if (isUpdate || isRemovedPackageSystemUpdate) { 14616 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14617 } 14618 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 14619 if (removedPackage != null) { 14620 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 14621 extras, 0, null, null, removedUsers); 14622 if (dataRemoved && !isRemovedPackageSystemUpdate) { 14623 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 14624 removedPackage, extras, 0, null, null, removedUsers); 14625 } 14626 } 14627 if (removedAppId >= 0) { 14628 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 14629 removedUsers); 14630 } 14631 } 14632 } 14633 14634 /* 14635 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 14636 * flag is not set, the data directory is removed as well. 14637 * make sure this flag is set for partially installed apps. If not its meaningless to 14638 * delete a partially installed application. 14639 */ 14640 private void removePackageDataLI(PackageSetting ps, int[] allUserHandles, 14641 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 14642 String packageName = ps.name; 14643 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 14644 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 14645 // Retrieve object to delete permissions for shared user later on 14646 final PackageSetting deletedPs; 14647 // reader 14648 synchronized (mPackages) { 14649 deletedPs = mSettings.mPackages.get(packageName); 14650 if (outInfo != null) { 14651 outInfo.removedPackage = packageName; 14652 outInfo.removedUsers = deletedPs != null 14653 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 14654 : null; 14655 } 14656 } 14657 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 14658 removeDataDirsLI(ps.volumeUuid, packageName); 14659 if (outInfo != null) { 14660 outInfo.dataRemoved = true; 14661 } 14662 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 14663 } 14664 // writer 14665 synchronized (mPackages) { 14666 if (deletedPs != null) { 14667 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 14668 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 14669 clearDefaultBrowserIfNeeded(packageName); 14670 if (outInfo != null) { 14671 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 14672 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 14673 } 14674 updatePermissionsLPw(deletedPs.name, null, 0); 14675 if (deletedPs.sharedUser != null) { 14676 // Remove permissions associated with package. Since runtime 14677 // permissions are per user we have to kill the removed package 14678 // or packages running under the shared user of the removed 14679 // package if revoking the permissions requested only by the removed 14680 // package is successful and this causes a change in gids. 14681 for (int userId : UserManagerService.getInstance().getUserIds()) { 14682 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 14683 userId); 14684 if (userIdToKill == UserHandle.USER_ALL 14685 || userIdToKill >= UserHandle.USER_SYSTEM) { 14686 // If gids changed for this user, kill all affected packages. 14687 mHandler.post(new Runnable() { 14688 @Override 14689 public void run() { 14690 // This has to happen with no lock held. 14691 killApplication(deletedPs.name, deletedPs.appId, 14692 KILL_APP_REASON_GIDS_CHANGED); 14693 } 14694 }); 14695 break; 14696 } 14697 } 14698 } 14699 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 14700 } 14701 // make sure to preserve per-user disabled state if this removal was just 14702 // a downgrade of a system app to the factory package 14703 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 14704 if (DEBUG_REMOVE) { 14705 Slog.d(TAG, "Propagating install state across downgrade"); 14706 } 14707 for (int userId : allUserHandles) { 14708 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 14709 if (DEBUG_REMOVE) { 14710 Slog.d(TAG, " user " + userId + " => " + installed); 14711 } 14712 ps.setInstalled(installed, userId); 14713 } 14714 } 14715 } 14716 // can downgrade to reader 14717 if (writeSettings) { 14718 // Save settings now 14719 mSettings.writeLPr(); 14720 } 14721 } 14722 if (outInfo != null) { 14723 // A user ID was deleted here. Go through all users and remove it 14724 // from KeyStore. 14725 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 14726 } 14727 } 14728 14729 static boolean locationIsPrivileged(File path) { 14730 try { 14731 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 14732 .getCanonicalPath(); 14733 return path.getCanonicalPath().startsWith(privilegedAppDir); 14734 } catch (IOException e) { 14735 Slog.e(TAG, "Unable to access code path " + path); 14736 } 14737 return false; 14738 } 14739 14740 /* 14741 * Tries to delete system package. 14742 */ 14743 private boolean deleteSystemPackageLI(PackageParser.Package deletedPkg, 14744 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 14745 boolean writeSettings) { 14746 if (deletedPs.parentPackageName != null) { 14747 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 14748 return false; 14749 } 14750 14751 final boolean applyUserRestrictions 14752 = (allUserHandles != null) && (outInfo.origUsers != null); 14753 final PackageSetting disabledPs; 14754 // Confirm if the system package has been updated 14755 // An updated system app can be deleted. This will also have to restore 14756 // the system pkg from system partition 14757 // reader 14758 synchronized (mPackages) { 14759 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 14760 } 14761 14762 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 14763 + " disabledPs=" + disabledPs); 14764 14765 if (disabledPs == null) { 14766 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 14767 return false; 14768 } else if (DEBUG_REMOVE) { 14769 Slog.d(TAG, "Deleting system pkg from data partition"); 14770 } 14771 14772 if (DEBUG_REMOVE) { 14773 if (applyUserRestrictions) { 14774 Slog.d(TAG, "Remembering install states:"); 14775 for (int userId : allUserHandles) { 14776 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 14777 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 14778 } 14779 } 14780 } 14781 14782 // Delete the updated package 14783 outInfo.isRemovedPackageSystemUpdate = true; 14784 if (outInfo.removedChildPackages != null) { 14785 final int childCount = (deletedPs.childPackageNames != null) 14786 ? deletedPs.childPackageNames.size() : 0; 14787 for (int i = 0; i < childCount; i++) { 14788 String childPackageName = deletedPs.childPackageNames.get(i); 14789 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 14790 .contains(childPackageName)) { 14791 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 14792 childPackageName); 14793 if (childInfo != null) { 14794 childInfo.isRemovedPackageSystemUpdate = true; 14795 } 14796 } 14797 } 14798 } 14799 14800 if (disabledPs.versionCode < deletedPs.versionCode) { 14801 // Delete data for downgrades 14802 flags &= ~PackageManager.DELETE_KEEP_DATA; 14803 } else { 14804 // Preserve data by setting flag 14805 flags |= PackageManager.DELETE_KEEP_DATA; 14806 } 14807 14808 boolean ret = deleteInstalledPackageLI(deletedPs, true, flags, allUserHandles, 14809 outInfo, writeSettings, disabledPs.pkg); 14810 if (!ret) { 14811 return false; 14812 } 14813 14814 // writer 14815 synchronized (mPackages) { 14816 // Reinstate the old system package 14817 enableSystemPackageLPw(disabledPs.pkg); 14818 // Remove any native libraries from the upgraded package. 14819 removeNativeBinariesLI(deletedPs); 14820 } 14821 14822 // Install the system package 14823 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 14824 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 14825 if (locationIsPrivileged(disabledPs.codePath)) { 14826 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 14827 } 14828 14829 final PackageParser.Package newPkg; 14830 try { 14831 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 14832 } catch (PackageManagerException e) { 14833 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 14834 + e.getMessage()); 14835 return false; 14836 } 14837 14838 prepareAppDataAfterInstall(newPkg); 14839 14840 // writer 14841 synchronized (mPackages) { 14842 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 14843 14844 // Propagate the permissions state as we do not want to drop on the floor 14845 // runtime permissions. The update permissions method below will take 14846 // care of removing obsolete permissions and grant install permissions. 14847 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 14848 updatePermissionsLPw(newPkg.packageName, newPkg, 14849 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 14850 14851 if (applyUserRestrictions) { 14852 if (DEBUG_REMOVE) { 14853 Slog.d(TAG, "Propagating install state across reinstall"); 14854 } 14855 for (int userId : allUserHandles) { 14856 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 14857 if (DEBUG_REMOVE) { 14858 Slog.d(TAG, " user " + userId + " => " + installed); 14859 } 14860 ps.setInstalled(installed, userId); 14861 14862 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 14863 } 14864 // Regardless of writeSettings we need to ensure that this restriction 14865 // state propagation is persisted 14866 mSettings.writeAllUsersPackageRestrictionsLPr(); 14867 } 14868 // can downgrade to reader here 14869 if (writeSettings) { 14870 mSettings.writeLPr(); 14871 } 14872 } 14873 return true; 14874 } 14875 14876 private boolean deleteInstalledPackageLI(PackageSetting ps, 14877 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 14878 PackageRemovedInfo outInfo, boolean writeSettings, 14879 PackageParser.Package replacingPackage) { 14880 synchronized (mPackages) { 14881 if (outInfo != null) { 14882 outInfo.uid = ps.appId; 14883 } 14884 14885 if (outInfo != null && outInfo.removedChildPackages != null) { 14886 final int childCount = (ps.childPackageNames != null) 14887 ? ps.childPackageNames.size() : 0; 14888 for (int i = 0; i < childCount; i++) { 14889 String childPackageName = ps.childPackageNames.get(i); 14890 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 14891 if (childPs == null) { 14892 return false; 14893 } 14894 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 14895 childPackageName); 14896 if (childInfo != null) { 14897 childInfo.uid = childPs.appId; 14898 } 14899 } 14900 } 14901 } 14902 14903 // Delete package data from internal structures and also remove data if flag is set 14904 removePackageDataLI(ps, allUserHandles, outInfo, flags, writeSettings); 14905 14906 // Delete the child packages data 14907 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14908 for (int i = 0; i < childCount; i++) { 14909 PackageSetting childPs; 14910 synchronized (mPackages) { 14911 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14912 } 14913 if (childPs != null) { 14914 PackageRemovedInfo childOutInfo = (outInfo != null 14915 && outInfo.removedChildPackages != null) 14916 ? outInfo.removedChildPackages.get(childPs.name) : null; 14917 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 14918 && (replacingPackage != null 14919 && !replacingPackage.hasChildPackage(childPs.name)) 14920 ? flags & ~DELETE_KEEP_DATA : flags; 14921 removePackageDataLI(childPs, allUserHandles, childOutInfo, 14922 deleteFlags, writeSettings); 14923 } 14924 } 14925 14926 // Delete application code and resources only for parent packages 14927 if (ps.parentPackageName == null) { 14928 if (deleteCodeAndResources && (outInfo != null)) { 14929 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 14930 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 14931 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 14932 } 14933 } 14934 14935 return true; 14936 } 14937 14938 @Override 14939 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 14940 int userId) { 14941 mContext.enforceCallingOrSelfPermission( 14942 android.Manifest.permission.DELETE_PACKAGES, null); 14943 synchronized (mPackages) { 14944 PackageSetting ps = mSettings.mPackages.get(packageName); 14945 if (ps == null) { 14946 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 14947 return false; 14948 } 14949 if (!ps.getInstalled(userId)) { 14950 // Can't block uninstall for an app that is not installed or enabled. 14951 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 14952 return false; 14953 } 14954 ps.setBlockUninstall(blockUninstall, userId); 14955 mSettings.writePackageRestrictionsLPr(userId); 14956 } 14957 return true; 14958 } 14959 14960 @Override 14961 public boolean getBlockUninstallForUser(String packageName, int userId) { 14962 synchronized (mPackages) { 14963 PackageSetting ps = mSettings.mPackages.get(packageName); 14964 if (ps == null) { 14965 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 14966 return false; 14967 } 14968 return ps.getBlockUninstall(userId); 14969 } 14970 } 14971 14972 @Override 14973 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 14974 int callingUid = Binder.getCallingUid(); 14975 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 14976 throw new SecurityException( 14977 "setRequiredForSystemUser can only be run by the system or root"); 14978 } 14979 synchronized (mPackages) { 14980 PackageSetting ps = mSettings.mPackages.get(packageName); 14981 if (ps == null) { 14982 Log.w(TAG, "Package doesn't exist: " + packageName); 14983 return false; 14984 } 14985 if (systemUserApp) { 14986 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 14987 } else { 14988 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 14989 } 14990 mSettings.writeLPr(); 14991 } 14992 return true; 14993 } 14994 14995 /* 14996 * This method handles package deletion in general 14997 */ 14998 private boolean deletePackageLI(String packageName, UserHandle user, 14999 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15000 PackageRemovedInfo outInfo, boolean writeSettings, 15001 PackageParser.Package replacingPackage) { 15002 if (packageName == null) { 15003 Slog.w(TAG, "Attempt to delete null packageName."); 15004 return false; 15005 } 15006 15007 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15008 15009 PackageSetting ps; 15010 15011 synchronized (mPackages) { 15012 ps = mSettings.mPackages.get(packageName); 15013 if (ps == null) { 15014 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15015 return false; 15016 } 15017 15018 if (ps.parentPackageName != null && (!isSystemApp(ps) 15019 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15020 if (DEBUG_REMOVE) { 15021 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15022 + ((user == null) ? UserHandle.USER_ALL : user)); 15023 } 15024 final int removedUserId = (user != null) ? user.getIdentifier() 15025 : UserHandle.USER_ALL; 15026 if (!clearPackageStateForUser(ps, removedUserId, outInfo)) { 15027 return false; 15028 } 15029 markPackageUninstalledForUserLPw(ps, user); 15030 scheduleWritePackageRestrictionsLocked(user); 15031 return true; 15032 } 15033 } 15034 15035 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15036 && user.getIdentifier() != UserHandle.USER_ALL)) { 15037 // The caller is asking that the package only be deleted for a single 15038 // user. To do this, we just mark its uninstalled state and delete 15039 // its data. If this is a system app, we only allow this to happen if 15040 // they have set the special DELETE_SYSTEM_APP which requests different 15041 // semantics than normal for uninstalling system apps. 15042 markPackageUninstalledForUserLPw(ps, user); 15043 15044 if (!isSystemApp(ps)) { 15045 // Do not uninstall the APK if an app should be cached 15046 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15047 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15048 // Other user still have this package installed, so all 15049 // we need to do is clear this user's data and save that 15050 // it is uninstalled. 15051 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15052 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 15053 return false; 15054 } 15055 scheduleWritePackageRestrictionsLocked(user); 15056 return true; 15057 } else { 15058 // We need to set it back to 'installed' so the uninstall 15059 // broadcasts will be sent correctly. 15060 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15061 ps.setInstalled(true, user.getIdentifier()); 15062 } 15063 } else { 15064 // This is a system app, so we assume that the 15065 // other users still have this package installed, so all 15066 // we need to do is clear this user's data and save that 15067 // it is uninstalled. 15068 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15069 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 15070 return false; 15071 } 15072 scheduleWritePackageRestrictionsLocked(user); 15073 return true; 15074 } 15075 } 15076 15077 // If we are deleting a composite package for all users, keep track 15078 // of result for each child. 15079 if (ps.childPackageNames != null && outInfo != null) { 15080 synchronized (mPackages) { 15081 final int childCount = ps.childPackageNames.size(); 15082 outInfo.removedChildPackages = new ArrayMap<>(childCount); 15083 for (int i = 0; i < childCount; i++) { 15084 String childPackageName = ps.childPackageNames.get(i); 15085 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 15086 childInfo.removedPackage = childPackageName; 15087 outInfo.removedChildPackages.put(childPackageName, childInfo); 15088 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15089 if (childPs != null) { 15090 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 15091 } 15092 } 15093 } 15094 } 15095 15096 boolean ret = false; 15097 if (isSystemApp(ps)) { 15098 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 15099 // When an updated system application is deleted we delete the existing resources 15100 // as well and fall back to existing code in system partition 15101 ret = deleteSystemPackageLI(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 15102 } else { 15103 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 15104 // Kill application pre-emptively especially for apps on sd. 15105 final boolean killApp = (flags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15106 if (killApp) { 15107 killApplication(packageName, ps.appId, "uninstall pkg"); 15108 } 15109 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, allUserHandles, 15110 outInfo, writeSettings, replacingPackage); 15111 } 15112 15113 // Take a note whether we deleted the package for all users 15114 if (outInfo != null) { 15115 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15116 if (outInfo.removedChildPackages != null) { 15117 synchronized (mPackages) { 15118 final int childCount = outInfo.removedChildPackages.size(); 15119 for (int i = 0; i < childCount; i++) { 15120 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 15121 if (childInfo != null) { 15122 childInfo.removedForAllUsers = mPackages.get( 15123 childInfo.removedPackage) == null; 15124 } 15125 } 15126 } 15127 } 15128 // If we uninstalled an update to a system app there may be some 15129 // child packages that appeared as they are declared in the system 15130 // app but were not declared in the update. 15131 if (isSystemApp(ps)) { 15132 synchronized (mPackages) { 15133 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 15134 final int childCount = (updatedPs.childPackageNames != null) 15135 ? updatedPs.childPackageNames.size() : 0; 15136 for (int i = 0; i < childCount; i++) { 15137 String childPackageName = updatedPs.childPackageNames.get(i); 15138 if (outInfo.removedChildPackages == null 15139 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 15140 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15141 if (childPs == null) { 15142 continue; 15143 } 15144 PackageInstalledInfo installRes = new PackageInstalledInfo(); 15145 installRes.name = childPackageName; 15146 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 15147 installRes.pkg = mPackages.get(childPackageName); 15148 installRes.uid = childPs.pkg.applicationInfo.uid; 15149 if (outInfo.appearedChildPackages == null) { 15150 outInfo.appearedChildPackages = new ArrayMap<>(); 15151 } 15152 outInfo.appearedChildPackages.put(childPackageName, installRes); 15153 } 15154 } 15155 } 15156 } 15157 } 15158 15159 return ret; 15160 } 15161 15162 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 15163 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 15164 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 15165 for (int nextUserId : userIds) { 15166 if (DEBUG_REMOVE) { 15167 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 15168 } 15169 ps.setUserState(nextUserId, COMPONENT_ENABLED_STATE_DEFAULT, 15170 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 15171 false /*hidden*/, false /*suspended*/, null, null, null, 15172 false /*blockUninstall*/, 15173 ps.readUserState(nextUserId).domainVerificationStatus, 0); 15174 } 15175 } 15176 15177 private boolean clearPackageStateForUser(PackageSetting ps, int userId, 15178 PackageRemovedInfo outInfo) { 15179 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 15180 : new int[] {userId}; 15181 for (int nextUserId : userIds) { 15182 if (DEBUG_REMOVE) { 15183 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 15184 + nextUserId); 15185 } 15186 final int flags = StorageManager.FLAG_STORAGE_CE| StorageManager.FLAG_STORAGE_DE; 15187 try { 15188 mInstaller.destroyAppData(ps.volumeUuid, ps.name, nextUserId, flags); 15189 } catch (InstallerException e) { 15190 Slog.w(TAG, "Couldn't remove cache files for package " + ps.name, e); 15191 return false; 15192 } 15193 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 15194 schedulePackageCleaning(ps.name, nextUserId, false); 15195 synchronized (mPackages) { 15196 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 15197 scheduleWritePackageRestrictionsLocked(nextUserId); 15198 } 15199 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 15200 } 15201 } 15202 15203 if (outInfo != null) { 15204 outInfo.removedPackage = ps.name; 15205 outInfo.removedAppId = ps.appId; 15206 outInfo.removedUsers = userIds; 15207 } 15208 15209 return true; 15210 } 15211 15212 private final class ClearStorageConnection implements ServiceConnection { 15213 IMediaContainerService mContainerService; 15214 15215 @Override 15216 public void onServiceConnected(ComponentName name, IBinder service) { 15217 synchronized (this) { 15218 mContainerService = IMediaContainerService.Stub.asInterface(service); 15219 notifyAll(); 15220 } 15221 } 15222 15223 @Override 15224 public void onServiceDisconnected(ComponentName name) { 15225 } 15226 } 15227 15228 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 15229 final boolean mounted; 15230 if (Environment.isExternalStorageEmulated()) { 15231 mounted = true; 15232 } else { 15233 final String status = Environment.getExternalStorageState(); 15234 15235 mounted = status.equals(Environment.MEDIA_MOUNTED) 15236 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 15237 } 15238 15239 if (!mounted) { 15240 return; 15241 } 15242 15243 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 15244 int[] users; 15245 if (userId == UserHandle.USER_ALL) { 15246 users = sUserManager.getUserIds(); 15247 } else { 15248 users = new int[] { userId }; 15249 } 15250 final ClearStorageConnection conn = new ClearStorageConnection(); 15251 if (mContext.bindServiceAsUser( 15252 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 15253 try { 15254 for (int curUser : users) { 15255 long timeout = SystemClock.uptimeMillis() + 5000; 15256 synchronized (conn) { 15257 long now = SystemClock.uptimeMillis(); 15258 while (conn.mContainerService == null && now < timeout) { 15259 try { 15260 conn.wait(timeout - now); 15261 } catch (InterruptedException e) { 15262 } 15263 } 15264 } 15265 if (conn.mContainerService == null) { 15266 return; 15267 } 15268 15269 final UserEnvironment userEnv = new UserEnvironment(curUser); 15270 clearDirectory(conn.mContainerService, 15271 userEnv.buildExternalStorageAppCacheDirs(packageName)); 15272 if (allData) { 15273 clearDirectory(conn.mContainerService, 15274 userEnv.buildExternalStorageAppDataDirs(packageName)); 15275 clearDirectory(conn.mContainerService, 15276 userEnv.buildExternalStorageAppMediaDirs(packageName)); 15277 } 15278 } 15279 } finally { 15280 mContext.unbindService(conn); 15281 } 15282 } 15283 } 15284 15285 @Override 15286 public void clearApplicationProfileData(String packageName) { 15287 enforceSystemOrRoot("Only the system can clear all profile data"); 15288 try { 15289 mInstaller.clearAppProfiles(packageName); 15290 } catch (InstallerException ex) { 15291 Log.e(TAG, "Could not clear profile data of package " + packageName); 15292 } 15293 } 15294 15295 @Override 15296 public void clearApplicationUserData(final String packageName, 15297 final IPackageDataObserver observer, final int userId) { 15298 mContext.enforceCallingOrSelfPermission( 15299 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 15300 15301 enforceCrossUserPermission(Binder.getCallingUid(), userId, 15302 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 15303 15304 final DevicePolicyManagerInternal dpmi = LocalServices 15305 .getService(DevicePolicyManagerInternal.class); 15306 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 15307 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 15308 } 15309 // Queue up an async operation since the package deletion may take a little while. 15310 mHandler.post(new Runnable() { 15311 public void run() { 15312 mHandler.removeCallbacks(this); 15313 final boolean succeeded; 15314 synchronized (mInstallLock) { 15315 succeeded = clearApplicationUserDataLI(packageName, userId); 15316 } 15317 clearExternalStorageDataSync(packageName, userId, true); 15318 if (succeeded) { 15319 // invoke DeviceStorageMonitor's update method to clear any notifications 15320 DeviceStorageMonitorInternal dsm = LocalServices 15321 .getService(DeviceStorageMonitorInternal.class); 15322 if (dsm != null) { 15323 dsm.checkMemory(); 15324 } 15325 } 15326 if(observer != null) { 15327 try { 15328 observer.onRemoveCompleted(packageName, succeeded); 15329 } catch (RemoteException e) { 15330 Log.i(TAG, "Observer no longer exists."); 15331 } 15332 } //end if observer 15333 } //end run 15334 }); 15335 } 15336 15337 private boolean clearApplicationUserDataLI(String packageName, int userId) { 15338 if (packageName == null) { 15339 Slog.w(TAG, "Attempt to delete null packageName."); 15340 return false; 15341 } 15342 15343 // Try finding details about the requested package 15344 PackageParser.Package pkg; 15345 synchronized (mPackages) { 15346 pkg = mPackages.get(packageName); 15347 if (pkg == null) { 15348 final PackageSetting ps = mSettings.mPackages.get(packageName); 15349 if (ps != null) { 15350 pkg = ps.pkg; 15351 } 15352 } 15353 15354 if (pkg == null) { 15355 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15356 return false; 15357 } 15358 15359 PackageSetting ps = (PackageSetting) pkg.mExtras; 15360 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15361 } 15362 15363 // Always delete data directories for package, even if we found no other 15364 // record of app. This helps users recover from UID mismatches without 15365 // resorting to a full data wipe. 15366 // TODO: triage flags as part of 26466827 15367 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15368 try { 15369 mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags); 15370 } catch (InstallerException e) { 15371 Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e); 15372 return false; 15373 } 15374 15375 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15376 removeKeystoreDataIfNeeded(userId, appId); 15377 15378 // Create a native library symlink only if we have native libraries 15379 // and if the native libraries are 32 bit libraries. We do not provide 15380 // this symlink for 64 bit libraries. 15381 if (pkg.applicationInfo.primaryCpuAbi != null && 15382 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 15383 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 15384 try { 15385 mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 15386 nativeLibPath, userId); 15387 } catch (InstallerException e) { 15388 Slog.w(TAG, "Failed linking native library dir", e); 15389 return false; 15390 } 15391 } 15392 15393 return true; 15394 } 15395 15396 /** 15397 * Reverts user permission state changes (permissions and flags) in 15398 * all packages for a given user. 15399 * 15400 * @param userId The device user for which to do a reset. 15401 */ 15402 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 15403 final int packageCount = mPackages.size(); 15404 for (int i = 0; i < packageCount; i++) { 15405 PackageParser.Package pkg = mPackages.valueAt(i); 15406 PackageSetting ps = (PackageSetting) pkg.mExtras; 15407 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15408 } 15409 } 15410 15411 /** 15412 * Reverts user permission state changes (permissions and flags). 15413 * 15414 * @param ps The package for which to reset. 15415 * @param userId The device user for which to do a reset. 15416 */ 15417 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 15418 final PackageSetting ps, final int userId) { 15419 if (ps.pkg == null) { 15420 return; 15421 } 15422 15423 // These are flags that can change base on user actions. 15424 final int userSettableMask = FLAG_PERMISSION_USER_SET 15425 | FLAG_PERMISSION_USER_FIXED 15426 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 15427 | FLAG_PERMISSION_REVIEW_REQUIRED; 15428 15429 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 15430 | FLAG_PERMISSION_POLICY_FIXED; 15431 15432 boolean writeInstallPermissions = false; 15433 boolean writeRuntimePermissions = false; 15434 15435 final int permissionCount = ps.pkg.requestedPermissions.size(); 15436 for (int i = 0; i < permissionCount; i++) { 15437 String permission = ps.pkg.requestedPermissions.get(i); 15438 15439 BasePermission bp = mSettings.mPermissions.get(permission); 15440 if (bp == null) { 15441 continue; 15442 } 15443 15444 // If shared user we just reset the state to which only this app contributed. 15445 if (ps.sharedUser != null) { 15446 boolean used = false; 15447 final int packageCount = ps.sharedUser.packages.size(); 15448 for (int j = 0; j < packageCount; j++) { 15449 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 15450 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 15451 && pkg.pkg.requestedPermissions.contains(permission)) { 15452 used = true; 15453 break; 15454 } 15455 } 15456 if (used) { 15457 continue; 15458 } 15459 } 15460 15461 PermissionsState permissionsState = ps.getPermissionsState(); 15462 15463 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 15464 15465 // Always clear the user settable flags. 15466 final boolean hasInstallState = permissionsState.getInstallPermissionState( 15467 bp.name) != null; 15468 // If permission review is enabled and this is a legacy app, mark the 15469 // permission as requiring a review as this is the initial state. 15470 int flags = 0; 15471 if (Build.PERMISSIONS_REVIEW_REQUIRED 15472 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 15473 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 15474 } 15475 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 15476 if (hasInstallState) { 15477 writeInstallPermissions = true; 15478 } else { 15479 writeRuntimePermissions = true; 15480 } 15481 } 15482 15483 // Below is only runtime permission handling. 15484 if (!bp.isRuntime()) { 15485 continue; 15486 } 15487 15488 // Never clobber system or policy. 15489 if ((oldFlags & policyOrSystemFlags) != 0) { 15490 continue; 15491 } 15492 15493 // If this permission was granted by default, make sure it is. 15494 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 15495 if (permissionsState.grantRuntimePermission(bp, userId) 15496 != PERMISSION_OPERATION_FAILURE) { 15497 writeRuntimePermissions = true; 15498 } 15499 // If permission review is enabled the permissions for a legacy apps 15500 // are represented as constantly granted runtime ones, so don't revoke. 15501 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 15502 // Otherwise, reset the permission. 15503 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 15504 switch (revokeResult) { 15505 case PERMISSION_OPERATION_SUCCESS: { 15506 writeRuntimePermissions = true; 15507 } break; 15508 15509 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 15510 writeRuntimePermissions = true; 15511 final int appId = ps.appId; 15512 mHandler.post(new Runnable() { 15513 @Override 15514 public void run() { 15515 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 15516 } 15517 }); 15518 } break; 15519 } 15520 } 15521 } 15522 15523 // Synchronously write as we are taking permissions away. 15524 if (writeRuntimePermissions) { 15525 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 15526 } 15527 15528 // Synchronously write as we are taking permissions away. 15529 if (writeInstallPermissions) { 15530 mSettings.writeLPr(); 15531 } 15532 } 15533 15534 /** 15535 * Remove entries from the keystore daemon. Will only remove it if the 15536 * {@code appId} is valid. 15537 */ 15538 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 15539 if (appId < 0) { 15540 return; 15541 } 15542 15543 final KeyStore keyStore = KeyStore.getInstance(); 15544 if (keyStore != null) { 15545 if (userId == UserHandle.USER_ALL) { 15546 for (final int individual : sUserManager.getUserIds()) { 15547 keyStore.clearUid(UserHandle.getUid(individual, appId)); 15548 } 15549 } else { 15550 keyStore.clearUid(UserHandle.getUid(userId, appId)); 15551 } 15552 } else { 15553 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 15554 } 15555 } 15556 15557 @Override 15558 public void deleteApplicationCacheFiles(final String packageName, 15559 final IPackageDataObserver observer) { 15560 mContext.enforceCallingOrSelfPermission( 15561 android.Manifest.permission.DELETE_CACHE_FILES, null); 15562 // Queue up an async operation since the package deletion may take a little while. 15563 final int userId = UserHandle.getCallingUserId(); 15564 mHandler.post(new Runnable() { 15565 public void run() { 15566 mHandler.removeCallbacks(this); 15567 final boolean succeded; 15568 synchronized (mInstallLock) { 15569 succeded = deleteApplicationCacheFilesLI(packageName, userId); 15570 } 15571 clearExternalStorageDataSync(packageName, userId, false); 15572 if (observer != null) { 15573 try { 15574 observer.onRemoveCompleted(packageName, succeded); 15575 } catch (RemoteException e) { 15576 Log.i(TAG, "Observer no longer exists."); 15577 } 15578 } //end if observer 15579 } //end run 15580 }); 15581 } 15582 15583 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 15584 if (packageName == null) { 15585 Slog.w(TAG, "Attempt to delete null packageName."); 15586 return false; 15587 } 15588 PackageParser.Package p; 15589 synchronized (mPackages) { 15590 p = mPackages.get(packageName); 15591 } 15592 if (p == null) { 15593 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 15594 return false; 15595 } 15596 final ApplicationInfo applicationInfo = p.applicationInfo; 15597 if (applicationInfo == null) { 15598 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 15599 return false; 15600 } 15601 // TODO: triage flags as part of 26466827 15602 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15603 try { 15604 mInstaller.clearAppData(p.volumeUuid, packageName, userId, 15605 flags | Installer.FLAG_CLEAR_CACHE_ONLY); 15606 } catch (InstallerException e) { 15607 Slog.w(TAG, "Couldn't remove cache files for package " 15608 + packageName + " u" + userId, e); 15609 return false; 15610 } 15611 return true; 15612 } 15613 15614 @Override 15615 public void getPackageSizeInfo(final String packageName, int userHandle, 15616 final IPackageStatsObserver observer) { 15617 mContext.enforceCallingOrSelfPermission( 15618 android.Manifest.permission.GET_PACKAGE_SIZE, null); 15619 if (packageName == null) { 15620 throw new IllegalArgumentException("Attempt to get size of null packageName"); 15621 } 15622 15623 PackageStats stats = new PackageStats(packageName, userHandle); 15624 15625 /* 15626 * Queue up an async operation since the package measurement may take a 15627 * little while. 15628 */ 15629 Message msg = mHandler.obtainMessage(INIT_COPY); 15630 msg.obj = new MeasureParams(stats, observer); 15631 mHandler.sendMessage(msg); 15632 } 15633 15634 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 15635 PackageStats pStats) { 15636 if (packageName == null) { 15637 Slog.w(TAG, "Attempt to get size of null packageName."); 15638 return false; 15639 } 15640 PackageParser.Package p; 15641 boolean dataOnly = false; 15642 String libDirRoot = null; 15643 String asecPath = null; 15644 PackageSetting ps = null; 15645 synchronized (mPackages) { 15646 p = mPackages.get(packageName); 15647 ps = mSettings.mPackages.get(packageName); 15648 if(p == null) { 15649 dataOnly = true; 15650 if((ps == null) || (ps.pkg == null)) { 15651 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 15652 return false; 15653 } 15654 p = ps.pkg; 15655 } 15656 if (ps != null) { 15657 libDirRoot = ps.legacyNativeLibraryPathString; 15658 } 15659 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 15660 final long token = Binder.clearCallingIdentity(); 15661 try { 15662 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 15663 if (secureContainerId != null) { 15664 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 15665 } 15666 } finally { 15667 Binder.restoreCallingIdentity(token); 15668 } 15669 } 15670 } 15671 String publicSrcDir = null; 15672 if(!dataOnly) { 15673 final ApplicationInfo applicationInfo = p.applicationInfo; 15674 if (applicationInfo == null) { 15675 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 15676 return false; 15677 } 15678 if (p.isForwardLocked()) { 15679 publicSrcDir = applicationInfo.getBaseResourcePath(); 15680 } 15681 } 15682 // TODO: extend to measure size of split APKs 15683 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 15684 // not just the first level. 15685 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 15686 // just the primary. 15687 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 15688 15689 String apkPath; 15690 File packageDir = new File(p.codePath); 15691 15692 if (packageDir.isDirectory() && p.canHaveOatDir()) { 15693 apkPath = packageDir.getAbsolutePath(); 15694 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 15695 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 15696 libDirRoot = null; 15697 } 15698 } else { 15699 apkPath = p.baseCodePath; 15700 } 15701 15702 // TODO: triage flags as part of 26466827 15703 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15704 try { 15705 mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath, 15706 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 15707 } catch (InstallerException e) { 15708 return false; 15709 } 15710 15711 // Fix-up for forward-locked applications in ASEC containers. 15712 if (!isExternal(p)) { 15713 pStats.codeSize += pStats.externalCodeSize; 15714 pStats.externalCodeSize = 0L; 15715 } 15716 15717 return true; 15718 } 15719 15720 private int getUidTargetSdkVersionLockedLPr(int uid) { 15721 Object obj = mSettings.getUserIdLPr(uid); 15722 if (obj instanceof SharedUserSetting) { 15723 final SharedUserSetting sus = (SharedUserSetting) obj; 15724 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 15725 final Iterator<PackageSetting> it = sus.packages.iterator(); 15726 while (it.hasNext()) { 15727 final PackageSetting ps = it.next(); 15728 if (ps.pkg != null) { 15729 int v = ps.pkg.applicationInfo.targetSdkVersion; 15730 if (v < vers) vers = v; 15731 } 15732 } 15733 return vers; 15734 } else if (obj instanceof PackageSetting) { 15735 final PackageSetting ps = (PackageSetting) obj; 15736 if (ps.pkg != null) { 15737 return ps.pkg.applicationInfo.targetSdkVersion; 15738 } 15739 } 15740 return Build.VERSION_CODES.CUR_DEVELOPMENT; 15741 } 15742 15743 @Override 15744 public void addPreferredActivity(IntentFilter filter, int match, 15745 ComponentName[] set, ComponentName activity, int userId) { 15746 addPreferredActivityInternal(filter, match, set, activity, true, userId, 15747 "Adding preferred"); 15748 } 15749 15750 private void addPreferredActivityInternal(IntentFilter filter, int match, 15751 ComponentName[] set, ComponentName activity, boolean always, int userId, 15752 String opname) { 15753 // writer 15754 int callingUid = Binder.getCallingUid(); 15755 enforceCrossUserPermission(callingUid, userId, 15756 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 15757 if (filter.countActions() == 0) { 15758 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 15759 return; 15760 } 15761 synchronized (mPackages) { 15762 if (mContext.checkCallingOrSelfPermission( 15763 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15764 != PackageManager.PERMISSION_GRANTED) { 15765 if (getUidTargetSdkVersionLockedLPr(callingUid) 15766 < Build.VERSION_CODES.FROYO) { 15767 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 15768 + callingUid); 15769 return; 15770 } 15771 mContext.enforceCallingOrSelfPermission( 15772 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15773 } 15774 15775 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 15776 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 15777 + userId + ":"); 15778 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15779 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 15780 scheduleWritePackageRestrictionsLocked(userId); 15781 } 15782 } 15783 15784 @Override 15785 public void replacePreferredActivity(IntentFilter filter, int match, 15786 ComponentName[] set, ComponentName activity, int userId) { 15787 if (filter.countActions() != 1) { 15788 throw new IllegalArgumentException( 15789 "replacePreferredActivity expects filter to have only 1 action."); 15790 } 15791 if (filter.countDataAuthorities() != 0 15792 || filter.countDataPaths() != 0 15793 || filter.countDataSchemes() > 1 15794 || filter.countDataTypes() != 0) { 15795 throw new IllegalArgumentException( 15796 "replacePreferredActivity expects filter to have no data authorities, " + 15797 "paths, or types; and at most one scheme."); 15798 } 15799 15800 final int callingUid = Binder.getCallingUid(); 15801 enforceCrossUserPermission(callingUid, userId, 15802 true /* requireFullPermission */, false /* checkShell */, 15803 "replace preferred activity"); 15804 synchronized (mPackages) { 15805 if (mContext.checkCallingOrSelfPermission( 15806 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15807 != PackageManager.PERMISSION_GRANTED) { 15808 if (getUidTargetSdkVersionLockedLPr(callingUid) 15809 < Build.VERSION_CODES.FROYO) { 15810 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 15811 + Binder.getCallingUid()); 15812 return; 15813 } 15814 mContext.enforceCallingOrSelfPermission( 15815 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15816 } 15817 15818 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 15819 if (pir != null) { 15820 // Get all of the existing entries that exactly match this filter. 15821 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 15822 if (existing != null && existing.size() == 1) { 15823 PreferredActivity cur = existing.get(0); 15824 if (DEBUG_PREFERRED) { 15825 Slog.i(TAG, "Checking replace of preferred:"); 15826 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15827 if (!cur.mPref.mAlways) { 15828 Slog.i(TAG, " -- CUR; not mAlways!"); 15829 } else { 15830 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 15831 Slog.i(TAG, " -- CUR: mSet=" 15832 + Arrays.toString(cur.mPref.mSetComponents)); 15833 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 15834 Slog.i(TAG, " -- NEW: mMatch=" 15835 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 15836 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 15837 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 15838 } 15839 } 15840 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 15841 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 15842 && cur.mPref.sameSet(set)) { 15843 // Setting the preferred activity to what it happens to be already 15844 if (DEBUG_PREFERRED) { 15845 Slog.i(TAG, "Replacing with same preferred activity " 15846 + cur.mPref.mShortComponent + " for user " 15847 + userId + ":"); 15848 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15849 } 15850 return; 15851 } 15852 } 15853 15854 if (existing != null) { 15855 if (DEBUG_PREFERRED) { 15856 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 15857 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15858 } 15859 for (int i = 0; i < existing.size(); i++) { 15860 PreferredActivity pa = existing.get(i); 15861 if (DEBUG_PREFERRED) { 15862 Slog.i(TAG, "Removing existing preferred activity " 15863 + pa.mPref.mComponent + ":"); 15864 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 15865 } 15866 pir.removeFilter(pa); 15867 } 15868 } 15869 } 15870 addPreferredActivityInternal(filter, match, set, activity, true, userId, 15871 "Replacing preferred"); 15872 } 15873 } 15874 15875 @Override 15876 public void clearPackagePreferredActivities(String packageName) { 15877 final int uid = Binder.getCallingUid(); 15878 // writer 15879 synchronized (mPackages) { 15880 PackageParser.Package pkg = mPackages.get(packageName); 15881 if (pkg == null || pkg.applicationInfo.uid != uid) { 15882 if (mContext.checkCallingOrSelfPermission( 15883 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15884 != PackageManager.PERMISSION_GRANTED) { 15885 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 15886 < Build.VERSION_CODES.FROYO) { 15887 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 15888 + Binder.getCallingUid()); 15889 return; 15890 } 15891 mContext.enforceCallingOrSelfPermission( 15892 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15893 } 15894 } 15895 15896 int user = UserHandle.getCallingUserId(); 15897 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 15898 scheduleWritePackageRestrictionsLocked(user); 15899 } 15900 } 15901 } 15902 15903 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15904 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 15905 ArrayList<PreferredActivity> removed = null; 15906 boolean changed = false; 15907 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15908 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 15909 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15910 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 15911 continue; 15912 } 15913 Iterator<PreferredActivity> it = pir.filterIterator(); 15914 while (it.hasNext()) { 15915 PreferredActivity pa = it.next(); 15916 // Mark entry for removal only if it matches the package name 15917 // and the entry is of type "always". 15918 if (packageName == null || 15919 (pa.mPref.mComponent.getPackageName().equals(packageName) 15920 && pa.mPref.mAlways)) { 15921 if (removed == null) { 15922 removed = new ArrayList<PreferredActivity>(); 15923 } 15924 removed.add(pa); 15925 } 15926 } 15927 if (removed != null) { 15928 for (int j=0; j<removed.size(); j++) { 15929 PreferredActivity pa = removed.get(j); 15930 pir.removeFilter(pa); 15931 } 15932 changed = true; 15933 } 15934 } 15935 return changed; 15936 } 15937 15938 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15939 private void clearIntentFilterVerificationsLPw(int userId) { 15940 final int packageCount = mPackages.size(); 15941 for (int i = 0; i < packageCount; i++) { 15942 PackageParser.Package pkg = mPackages.valueAt(i); 15943 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 15944 } 15945 } 15946 15947 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15948 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 15949 if (userId == UserHandle.USER_ALL) { 15950 if (mSettings.removeIntentFilterVerificationLPw(packageName, 15951 sUserManager.getUserIds())) { 15952 for (int oneUserId : sUserManager.getUserIds()) { 15953 scheduleWritePackageRestrictionsLocked(oneUserId); 15954 } 15955 } 15956 } else { 15957 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 15958 scheduleWritePackageRestrictionsLocked(userId); 15959 } 15960 } 15961 } 15962 15963 void clearDefaultBrowserIfNeeded(String packageName) { 15964 for (int oneUserId : sUserManager.getUserIds()) { 15965 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 15966 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 15967 if (packageName.equals(defaultBrowserPackageName)) { 15968 setDefaultBrowserPackageName(null, oneUserId); 15969 } 15970 } 15971 } 15972 15973 @Override 15974 public void resetApplicationPreferences(int userId) { 15975 mContext.enforceCallingOrSelfPermission( 15976 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15977 // writer 15978 synchronized (mPackages) { 15979 final long identity = Binder.clearCallingIdentity(); 15980 try { 15981 clearPackagePreferredActivitiesLPw(null, userId); 15982 mSettings.applyDefaultPreferredAppsLPw(this, userId); 15983 // TODO: We have to reset the default SMS and Phone. This requires 15984 // significant refactoring to keep all default apps in the package 15985 // manager (cleaner but more work) or have the services provide 15986 // callbacks to the package manager to request a default app reset. 15987 applyFactoryDefaultBrowserLPw(userId); 15988 clearIntentFilterVerificationsLPw(userId); 15989 primeDomainVerificationsLPw(userId); 15990 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 15991 scheduleWritePackageRestrictionsLocked(userId); 15992 } finally { 15993 Binder.restoreCallingIdentity(identity); 15994 } 15995 } 15996 } 15997 15998 @Override 15999 public int getPreferredActivities(List<IntentFilter> outFilters, 16000 List<ComponentName> outActivities, String packageName) { 16001 16002 int num = 0; 16003 final int userId = UserHandle.getCallingUserId(); 16004 // reader 16005 synchronized (mPackages) { 16006 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16007 if (pir != null) { 16008 final Iterator<PreferredActivity> it = pir.filterIterator(); 16009 while (it.hasNext()) { 16010 final PreferredActivity pa = it.next(); 16011 if (packageName == null 16012 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16013 && pa.mPref.mAlways)) { 16014 if (outFilters != null) { 16015 outFilters.add(new IntentFilter(pa)); 16016 } 16017 if (outActivities != null) { 16018 outActivities.add(pa.mPref.mComponent); 16019 } 16020 } 16021 } 16022 } 16023 } 16024 16025 return num; 16026 } 16027 16028 @Override 16029 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16030 int userId) { 16031 int callingUid = Binder.getCallingUid(); 16032 if (callingUid != Process.SYSTEM_UID) { 16033 throw new SecurityException( 16034 "addPersistentPreferredActivity can only be run by the system"); 16035 } 16036 if (filter.countActions() == 0) { 16037 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16038 return; 16039 } 16040 synchronized (mPackages) { 16041 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16042 ":"); 16043 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16044 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16045 new PersistentPreferredActivity(filter, activity)); 16046 scheduleWritePackageRestrictionsLocked(userId); 16047 } 16048 } 16049 16050 @Override 16051 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16052 int callingUid = Binder.getCallingUid(); 16053 if (callingUid != Process.SYSTEM_UID) { 16054 throw new SecurityException( 16055 "clearPackagePersistentPreferredActivities can only be run by the system"); 16056 } 16057 ArrayList<PersistentPreferredActivity> removed = null; 16058 boolean changed = false; 16059 synchronized (mPackages) { 16060 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16061 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16062 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16063 .valueAt(i); 16064 if (userId != thisUserId) { 16065 continue; 16066 } 16067 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16068 while (it.hasNext()) { 16069 PersistentPreferredActivity ppa = it.next(); 16070 // Mark entry for removal only if it matches the package name. 16071 if (ppa.mComponent.getPackageName().equals(packageName)) { 16072 if (removed == null) { 16073 removed = new ArrayList<PersistentPreferredActivity>(); 16074 } 16075 removed.add(ppa); 16076 } 16077 } 16078 if (removed != null) { 16079 for (int j=0; j<removed.size(); j++) { 16080 PersistentPreferredActivity ppa = removed.get(j); 16081 ppir.removeFilter(ppa); 16082 } 16083 changed = true; 16084 } 16085 } 16086 16087 if (changed) { 16088 scheduleWritePackageRestrictionsLocked(userId); 16089 } 16090 } 16091 } 16092 16093 /** 16094 * Common machinery for picking apart a restored XML blob and passing 16095 * it to a caller-supplied functor to be applied to the running system. 16096 */ 16097 private void restoreFromXml(XmlPullParser parser, int userId, 16098 String expectedStartTag, BlobXmlRestorer functor) 16099 throws IOException, XmlPullParserException { 16100 int type; 16101 while ((type = parser.next()) != XmlPullParser.START_TAG 16102 && type != XmlPullParser.END_DOCUMENT) { 16103 } 16104 if (type != XmlPullParser.START_TAG) { 16105 // oops didn't find a start tag?! 16106 if (DEBUG_BACKUP) { 16107 Slog.e(TAG, "Didn't find start tag during restore"); 16108 } 16109 return; 16110 } 16111Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16112 // this is supposed to be TAG_PREFERRED_BACKUP 16113 if (!expectedStartTag.equals(parser.getName())) { 16114 if (DEBUG_BACKUP) { 16115 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16116 } 16117 return; 16118 } 16119 16120 // skip interfering stuff, then we're aligned with the backing implementation 16121 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16122Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16123 functor.apply(parser, userId); 16124 } 16125 16126 private interface BlobXmlRestorer { 16127 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16128 } 16129 16130 /** 16131 * Non-Binder method, support for the backup/restore mechanism: write the 16132 * full set of preferred activities in its canonical XML format. Returns the 16133 * XML output as a byte array, or null if there is none. 16134 */ 16135 @Override 16136 public byte[] getPreferredActivityBackup(int userId) { 16137 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16138 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16139 } 16140 16141 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16142 try { 16143 final XmlSerializer serializer = new FastXmlSerializer(); 16144 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16145 serializer.startDocument(null, true); 16146 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16147 16148 synchronized (mPackages) { 16149 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16150 } 16151 16152 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16153 serializer.endDocument(); 16154 serializer.flush(); 16155 } catch (Exception e) { 16156 if (DEBUG_BACKUP) { 16157 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16158 } 16159 return null; 16160 } 16161 16162 return dataStream.toByteArray(); 16163 } 16164 16165 @Override 16166 public void restorePreferredActivities(byte[] backup, int userId) { 16167 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16168 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16169 } 16170 16171 try { 16172 final XmlPullParser parser = Xml.newPullParser(); 16173 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16174 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16175 new BlobXmlRestorer() { 16176 @Override 16177 public void apply(XmlPullParser parser, int userId) 16178 throws XmlPullParserException, IOException { 16179 synchronized (mPackages) { 16180 mSettings.readPreferredActivitiesLPw(parser, userId); 16181 } 16182 } 16183 } ); 16184 } catch (Exception e) { 16185 if (DEBUG_BACKUP) { 16186 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16187 } 16188 } 16189 } 16190 16191 /** 16192 * Non-Binder method, support for the backup/restore mechanism: write the 16193 * default browser (etc) settings in its canonical XML format. Returns the default 16194 * browser XML representation as a byte array, or null if there is none. 16195 */ 16196 @Override 16197 public byte[] getDefaultAppsBackup(int userId) { 16198 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16199 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 16200 } 16201 16202 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16203 try { 16204 final XmlSerializer serializer = new FastXmlSerializer(); 16205 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16206 serializer.startDocument(null, true); 16207 serializer.startTag(null, TAG_DEFAULT_APPS); 16208 16209 synchronized (mPackages) { 16210 mSettings.writeDefaultAppsLPr(serializer, userId); 16211 } 16212 16213 serializer.endTag(null, TAG_DEFAULT_APPS); 16214 serializer.endDocument(); 16215 serializer.flush(); 16216 } catch (Exception e) { 16217 if (DEBUG_BACKUP) { 16218 Slog.e(TAG, "Unable to write default apps for backup", e); 16219 } 16220 return null; 16221 } 16222 16223 return dataStream.toByteArray(); 16224 } 16225 16226 @Override 16227 public void restoreDefaultApps(byte[] backup, int userId) { 16228 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16229 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16230 } 16231 16232 try { 16233 final XmlPullParser parser = Xml.newPullParser(); 16234 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16235 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16236 new BlobXmlRestorer() { 16237 @Override 16238 public void apply(XmlPullParser parser, int userId) 16239 throws XmlPullParserException, IOException { 16240 synchronized (mPackages) { 16241 mSettings.readDefaultAppsLPw(parser, userId); 16242 } 16243 } 16244 } ); 16245 } catch (Exception e) { 16246 if (DEBUG_BACKUP) { 16247 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16248 } 16249 } 16250 } 16251 16252 @Override 16253 public byte[] getIntentFilterVerificationBackup(int userId) { 16254 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16255 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 16256 } 16257 16258 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16259 try { 16260 final XmlSerializer serializer = new FastXmlSerializer(); 16261 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16262 serializer.startDocument(null, true); 16263 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 16264 16265 synchronized (mPackages) { 16266 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 16267 } 16268 16269 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 16270 serializer.endDocument(); 16271 serializer.flush(); 16272 } catch (Exception e) { 16273 if (DEBUG_BACKUP) { 16274 Slog.e(TAG, "Unable to write default apps for backup", e); 16275 } 16276 return null; 16277 } 16278 16279 return dataStream.toByteArray(); 16280 } 16281 16282 @Override 16283 public void restoreIntentFilterVerification(byte[] backup, int userId) { 16284 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16285 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16286 } 16287 16288 try { 16289 final XmlPullParser parser = Xml.newPullParser(); 16290 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16291 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 16292 new BlobXmlRestorer() { 16293 @Override 16294 public void apply(XmlPullParser parser, int userId) 16295 throws XmlPullParserException, IOException { 16296 synchronized (mPackages) { 16297 mSettings.readAllDomainVerificationsLPr(parser, userId); 16298 mSettings.writeLPr(); 16299 } 16300 } 16301 } ); 16302 } catch (Exception e) { 16303 if (DEBUG_BACKUP) { 16304 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16305 } 16306 } 16307 } 16308 16309 @Override 16310 public byte[] getPermissionGrantBackup(int userId) { 16311 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16312 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 16313 } 16314 16315 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16316 try { 16317 final XmlSerializer serializer = new FastXmlSerializer(); 16318 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16319 serializer.startDocument(null, true); 16320 serializer.startTag(null, TAG_PERMISSION_BACKUP); 16321 16322 synchronized (mPackages) { 16323 serializeRuntimePermissionGrantsLPr(serializer, userId); 16324 } 16325 16326 serializer.endTag(null, TAG_PERMISSION_BACKUP); 16327 serializer.endDocument(); 16328 serializer.flush(); 16329 } catch (Exception e) { 16330 if (DEBUG_BACKUP) { 16331 Slog.e(TAG, "Unable to write default apps for backup", e); 16332 } 16333 return null; 16334 } 16335 16336 return dataStream.toByteArray(); 16337 } 16338 16339 @Override 16340 public void restorePermissionGrants(byte[] backup, int userId) { 16341 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16342 throw new SecurityException("Only the system may call restorePermissionGrants()"); 16343 } 16344 16345 try { 16346 final XmlPullParser parser = Xml.newPullParser(); 16347 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16348 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 16349 new BlobXmlRestorer() { 16350 @Override 16351 public void apply(XmlPullParser parser, int userId) 16352 throws XmlPullParserException, IOException { 16353 synchronized (mPackages) { 16354 processRestoredPermissionGrantsLPr(parser, userId); 16355 } 16356 } 16357 } ); 16358 } catch (Exception e) { 16359 if (DEBUG_BACKUP) { 16360 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16361 } 16362 } 16363 } 16364 16365 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 16366 throws IOException { 16367 serializer.startTag(null, TAG_ALL_GRANTS); 16368 16369 final int N = mSettings.mPackages.size(); 16370 for (int i = 0; i < N; i++) { 16371 final PackageSetting ps = mSettings.mPackages.valueAt(i); 16372 boolean pkgGrantsKnown = false; 16373 16374 PermissionsState packagePerms = ps.getPermissionsState(); 16375 16376 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 16377 final int grantFlags = state.getFlags(); 16378 // only look at grants that are not system/policy fixed 16379 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 16380 final boolean isGranted = state.isGranted(); 16381 // And only back up the user-twiddled state bits 16382 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 16383 final String packageName = mSettings.mPackages.keyAt(i); 16384 if (!pkgGrantsKnown) { 16385 serializer.startTag(null, TAG_GRANT); 16386 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 16387 pkgGrantsKnown = true; 16388 } 16389 16390 final boolean userSet = 16391 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 16392 final boolean userFixed = 16393 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 16394 final boolean revoke = 16395 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 16396 16397 serializer.startTag(null, TAG_PERMISSION); 16398 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 16399 if (isGranted) { 16400 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 16401 } 16402 if (userSet) { 16403 serializer.attribute(null, ATTR_USER_SET, "true"); 16404 } 16405 if (userFixed) { 16406 serializer.attribute(null, ATTR_USER_FIXED, "true"); 16407 } 16408 if (revoke) { 16409 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 16410 } 16411 serializer.endTag(null, TAG_PERMISSION); 16412 } 16413 } 16414 } 16415 16416 if (pkgGrantsKnown) { 16417 serializer.endTag(null, TAG_GRANT); 16418 } 16419 } 16420 16421 serializer.endTag(null, TAG_ALL_GRANTS); 16422 } 16423 16424 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 16425 throws XmlPullParserException, IOException { 16426 String pkgName = null; 16427 int outerDepth = parser.getDepth(); 16428 int type; 16429 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 16430 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 16431 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 16432 continue; 16433 } 16434 16435 final String tagName = parser.getName(); 16436 if (tagName.equals(TAG_GRANT)) { 16437 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 16438 if (DEBUG_BACKUP) { 16439 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 16440 } 16441 } else if (tagName.equals(TAG_PERMISSION)) { 16442 16443 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 16444 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 16445 16446 int newFlagSet = 0; 16447 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 16448 newFlagSet |= FLAG_PERMISSION_USER_SET; 16449 } 16450 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 16451 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 16452 } 16453 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 16454 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 16455 } 16456 if (DEBUG_BACKUP) { 16457 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 16458 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 16459 } 16460 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16461 if (ps != null) { 16462 // Already installed so we apply the grant immediately 16463 if (DEBUG_BACKUP) { 16464 Slog.v(TAG, " + already installed; applying"); 16465 } 16466 PermissionsState perms = ps.getPermissionsState(); 16467 BasePermission bp = mSettings.mPermissions.get(permName); 16468 if (bp != null) { 16469 if (isGranted) { 16470 perms.grantRuntimePermission(bp, userId); 16471 } 16472 if (newFlagSet != 0) { 16473 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 16474 } 16475 } 16476 } else { 16477 // Need to wait for post-restore install to apply the grant 16478 if (DEBUG_BACKUP) { 16479 Slog.v(TAG, " - not yet installed; saving for later"); 16480 } 16481 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 16482 isGranted, newFlagSet, userId); 16483 } 16484 } else { 16485 PackageManagerService.reportSettingsProblem(Log.WARN, 16486 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 16487 XmlUtils.skipCurrentTag(parser); 16488 } 16489 } 16490 16491 scheduleWriteSettingsLocked(); 16492 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16493 } 16494 16495 @Override 16496 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 16497 int sourceUserId, int targetUserId, int flags) { 16498 mContext.enforceCallingOrSelfPermission( 16499 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16500 int callingUid = Binder.getCallingUid(); 16501 enforceOwnerRights(ownerPackage, callingUid); 16502 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16503 if (intentFilter.countActions() == 0) { 16504 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 16505 return; 16506 } 16507 synchronized (mPackages) { 16508 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 16509 ownerPackage, targetUserId, flags); 16510 CrossProfileIntentResolver resolver = 16511 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16512 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 16513 // We have all those whose filter is equal. Now checking if the rest is equal as well. 16514 if (existing != null) { 16515 int size = existing.size(); 16516 for (int i = 0; i < size; i++) { 16517 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 16518 return; 16519 } 16520 } 16521 } 16522 resolver.addFilter(newFilter); 16523 scheduleWritePackageRestrictionsLocked(sourceUserId); 16524 } 16525 } 16526 16527 @Override 16528 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 16529 mContext.enforceCallingOrSelfPermission( 16530 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16531 int callingUid = Binder.getCallingUid(); 16532 enforceOwnerRights(ownerPackage, callingUid); 16533 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16534 synchronized (mPackages) { 16535 CrossProfileIntentResolver resolver = 16536 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16537 ArraySet<CrossProfileIntentFilter> set = 16538 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 16539 for (CrossProfileIntentFilter filter : set) { 16540 if (filter.getOwnerPackage().equals(ownerPackage)) { 16541 resolver.removeFilter(filter); 16542 } 16543 } 16544 scheduleWritePackageRestrictionsLocked(sourceUserId); 16545 } 16546 } 16547 16548 // Enforcing that callingUid is owning pkg on userId 16549 private void enforceOwnerRights(String pkg, int callingUid) { 16550 // The system owns everything. 16551 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 16552 return; 16553 } 16554 int callingUserId = UserHandle.getUserId(callingUid); 16555 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 16556 if (pi == null) { 16557 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 16558 + callingUserId); 16559 } 16560 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 16561 throw new SecurityException("Calling uid " + callingUid 16562 + " does not own package " + pkg); 16563 } 16564 } 16565 16566 @Override 16567 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 16568 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 16569 } 16570 16571 private Intent getHomeIntent() { 16572 Intent intent = new Intent(Intent.ACTION_MAIN); 16573 intent.addCategory(Intent.CATEGORY_HOME); 16574 return intent; 16575 } 16576 16577 private IntentFilter getHomeFilter() { 16578 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 16579 filter.addCategory(Intent.CATEGORY_HOME); 16580 filter.addCategory(Intent.CATEGORY_DEFAULT); 16581 return filter; 16582 } 16583 16584 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 16585 int userId) { 16586 Intent intent = getHomeIntent(); 16587 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 16588 PackageManager.GET_META_DATA, userId); 16589 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 16590 true, false, false, userId); 16591 16592 allHomeCandidates.clear(); 16593 if (list != null) { 16594 for (ResolveInfo ri : list) { 16595 allHomeCandidates.add(ri); 16596 } 16597 } 16598 return (preferred == null || preferred.activityInfo == null) 16599 ? null 16600 : new ComponentName(preferred.activityInfo.packageName, 16601 preferred.activityInfo.name); 16602 } 16603 16604 @Override 16605 public void setHomeActivity(ComponentName comp, int userId) { 16606 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 16607 getHomeActivitiesAsUser(homeActivities, userId); 16608 16609 boolean found = false; 16610 16611 final int size = homeActivities.size(); 16612 final ComponentName[] set = new ComponentName[size]; 16613 for (int i = 0; i < size; i++) { 16614 final ResolveInfo candidate = homeActivities.get(i); 16615 final ActivityInfo info = candidate.activityInfo; 16616 final ComponentName activityName = new ComponentName(info.packageName, info.name); 16617 set[i] = activityName; 16618 if (!found && activityName.equals(comp)) { 16619 found = true; 16620 } 16621 } 16622 if (!found) { 16623 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 16624 + userId); 16625 } 16626 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 16627 set, comp, userId); 16628 } 16629 16630 @Override 16631 public void setApplicationEnabledSetting(String appPackageName, 16632 int newState, int flags, int userId, String callingPackage) { 16633 if (!sUserManager.exists(userId)) return; 16634 if (callingPackage == null) { 16635 callingPackage = Integer.toString(Binder.getCallingUid()); 16636 } 16637 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 16638 } 16639 16640 @Override 16641 public void setComponentEnabledSetting(ComponentName componentName, 16642 int newState, int flags, int userId) { 16643 if (!sUserManager.exists(userId)) return; 16644 setEnabledSetting(componentName.getPackageName(), 16645 componentName.getClassName(), newState, flags, userId, null); 16646 } 16647 16648 private void setEnabledSetting(final String packageName, String className, int newState, 16649 final int flags, int userId, String callingPackage) { 16650 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 16651 || newState == COMPONENT_ENABLED_STATE_ENABLED 16652 || newState == COMPONENT_ENABLED_STATE_DISABLED 16653 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 16654 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 16655 throw new IllegalArgumentException("Invalid new component state: " 16656 + newState); 16657 } 16658 PackageSetting pkgSetting; 16659 final int uid = Binder.getCallingUid(); 16660 final int permission = mContext.checkCallingOrSelfPermission( 16661 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 16662 enforceCrossUserPermission(uid, userId, 16663 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 16664 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 16665 boolean sendNow = false; 16666 boolean isApp = (className == null); 16667 String componentName = isApp ? packageName : className; 16668 int packageUid = -1; 16669 ArrayList<String> components; 16670 16671 // writer 16672 synchronized (mPackages) { 16673 pkgSetting = mSettings.mPackages.get(packageName); 16674 if (pkgSetting == null) { 16675 if (className == null) { 16676 throw new IllegalArgumentException("Unknown package: " + packageName); 16677 } 16678 throw new IllegalArgumentException( 16679 "Unknown component: " + packageName + "/" + className); 16680 } 16681 // Allow root and verify that userId is not being specified by a different user 16682 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 16683 throw new SecurityException( 16684 "Permission Denial: attempt to change component state from pid=" 16685 + Binder.getCallingPid() 16686 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 16687 } 16688 if (className == null) { 16689 // We're dealing with an application/package level state change 16690 if (pkgSetting.getEnabled(userId) == newState) { 16691 // Nothing to do 16692 return; 16693 } 16694 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 16695 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 16696 // Don't care about who enables an app. 16697 callingPackage = null; 16698 } 16699 pkgSetting.setEnabled(newState, userId, callingPackage); 16700 // pkgSetting.pkg.mSetEnabled = newState; 16701 } else { 16702 // We're dealing with a component level state change 16703 // First, verify that this is a valid class name. 16704 PackageParser.Package pkg = pkgSetting.pkg; 16705 if (pkg == null || !pkg.hasComponentClassName(className)) { 16706 if (pkg != null && 16707 pkg.applicationInfo.targetSdkVersion >= 16708 Build.VERSION_CODES.JELLY_BEAN) { 16709 throw new IllegalArgumentException("Component class " + className 16710 + " does not exist in " + packageName); 16711 } else { 16712 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 16713 + className + " does not exist in " + packageName); 16714 } 16715 } 16716 switch (newState) { 16717 case COMPONENT_ENABLED_STATE_ENABLED: 16718 if (!pkgSetting.enableComponentLPw(className, userId)) { 16719 return; 16720 } 16721 break; 16722 case COMPONENT_ENABLED_STATE_DISABLED: 16723 if (!pkgSetting.disableComponentLPw(className, userId)) { 16724 return; 16725 } 16726 break; 16727 case COMPONENT_ENABLED_STATE_DEFAULT: 16728 if (!pkgSetting.restoreComponentLPw(className, userId)) { 16729 return; 16730 } 16731 break; 16732 default: 16733 Slog.e(TAG, "Invalid new component state: " + newState); 16734 return; 16735 } 16736 } 16737 scheduleWritePackageRestrictionsLocked(userId); 16738 components = mPendingBroadcasts.get(userId, packageName); 16739 final boolean newPackage = components == null; 16740 if (newPackage) { 16741 components = new ArrayList<String>(); 16742 } 16743 if (!components.contains(componentName)) { 16744 components.add(componentName); 16745 } 16746 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 16747 sendNow = true; 16748 // Purge entry from pending broadcast list if another one exists already 16749 // since we are sending one right away. 16750 mPendingBroadcasts.remove(userId, packageName); 16751 } else { 16752 if (newPackage) { 16753 mPendingBroadcasts.put(userId, packageName, components); 16754 } 16755 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 16756 // Schedule a message 16757 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 16758 } 16759 } 16760 } 16761 16762 long callingId = Binder.clearCallingIdentity(); 16763 try { 16764 if (sendNow) { 16765 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 16766 sendPackageChangedBroadcast(packageName, 16767 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 16768 } 16769 } finally { 16770 Binder.restoreCallingIdentity(callingId); 16771 } 16772 } 16773 16774 @Override 16775 public void flushPackageRestrictionsAsUser(int userId) { 16776 if (!sUserManager.exists(userId)) { 16777 return; 16778 } 16779 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 16780 false /* checkShell */, "flushPackageRestrictions"); 16781 synchronized (mPackages) { 16782 mSettings.writePackageRestrictionsLPr(userId); 16783 mDirtyUsers.remove(userId); 16784 if (mDirtyUsers.isEmpty()) { 16785 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 16786 } 16787 } 16788 } 16789 16790 private void sendPackageChangedBroadcast(String packageName, 16791 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 16792 if (DEBUG_INSTALL) 16793 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 16794 + componentNames); 16795 Bundle extras = new Bundle(4); 16796 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 16797 String nameList[] = new String[componentNames.size()]; 16798 componentNames.toArray(nameList); 16799 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 16800 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 16801 extras.putInt(Intent.EXTRA_UID, packageUid); 16802 // If this is not reporting a change of the overall package, then only send it 16803 // to registered receivers. We don't want to launch a swath of apps for every 16804 // little component state change. 16805 final int flags = !componentNames.contains(packageName) 16806 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 16807 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 16808 new int[] {UserHandle.getUserId(packageUid)}); 16809 } 16810 16811 @Override 16812 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 16813 if (!sUserManager.exists(userId)) return; 16814 final int uid = Binder.getCallingUid(); 16815 final int permission = mContext.checkCallingOrSelfPermission( 16816 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 16817 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 16818 enforceCrossUserPermission(uid, userId, 16819 true /* requireFullPermission */, true /* checkShell */, "stop package"); 16820 // writer 16821 synchronized (mPackages) { 16822 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 16823 allowedByPermission, uid, userId)) { 16824 scheduleWritePackageRestrictionsLocked(userId); 16825 } 16826 } 16827 } 16828 16829 @Override 16830 public String getInstallerPackageName(String packageName) { 16831 // reader 16832 synchronized (mPackages) { 16833 return mSettings.getInstallerPackageNameLPr(packageName); 16834 } 16835 } 16836 16837 @Override 16838 public int getApplicationEnabledSetting(String packageName, int userId) { 16839 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 16840 int uid = Binder.getCallingUid(); 16841 enforceCrossUserPermission(uid, userId, 16842 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 16843 // reader 16844 synchronized (mPackages) { 16845 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 16846 } 16847 } 16848 16849 @Override 16850 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 16851 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 16852 int uid = Binder.getCallingUid(); 16853 enforceCrossUserPermission(uid, userId, 16854 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 16855 // reader 16856 synchronized (mPackages) { 16857 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 16858 } 16859 } 16860 16861 @Override 16862 public void enterSafeMode() { 16863 enforceSystemOrRoot("Only the system can request entering safe mode"); 16864 16865 if (!mSystemReady) { 16866 mSafeMode = true; 16867 } 16868 } 16869 16870 @Override 16871 public void systemReady() { 16872 mSystemReady = true; 16873 16874 // Read the compatibilty setting when the system is ready. 16875 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 16876 mContext.getContentResolver(), 16877 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 16878 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 16879 if (DEBUG_SETTINGS) { 16880 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 16881 } 16882 16883 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 16884 16885 synchronized (mPackages) { 16886 // Verify that all of the preferred activity components actually 16887 // exist. It is possible for applications to be updated and at 16888 // that point remove a previously declared activity component that 16889 // had been set as a preferred activity. We try to clean this up 16890 // the next time we encounter that preferred activity, but it is 16891 // possible for the user flow to never be able to return to that 16892 // situation so here we do a sanity check to make sure we haven't 16893 // left any junk around. 16894 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 16895 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16896 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16897 removed.clear(); 16898 for (PreferredActivity pa : pir.filterSet()) { 16899 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 16900 removed.add(pa); 16901 } 16902 } 16903 if (removed.size() > 0) { 16904 for (int r=0; r<removed.size(); r++) { 16905 PreferredActivity pa = removed.get(r); 16906 Slog.w(TAG, "Removing dangling preferred activity: " 16907 + pa.mPref.mComponent); 16908 pir.removeFilter(pa); 16909 } 16910 mSettings.writePackageRestrictionsLPr( 16911 mSettings.mPreferredActivities.keyAt(i)); 16912 } 16913 } 16914 16915 for (int userId : UserManagerService.getInstance().getUserIds()) { 16916 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 16917 grantPermissionsUserIds = ArrayUtils.appendInt( 16918 grantPermissionsUserIds, userId); 16919 } 16920 } 16921 } 16922 sUserManager.systemReady(); 16923 16924 // If we upgraded grant all default permissions before kicking off. 16925 for (int userId : grantPermissionsUserIds) { 16926 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 16927 } 16928 16929 // Kick off any messages waiting for system ready 16930 if (mPostSystemReadyMessages != null) { 16931 for (Message msg : mPostSystemReadyMessages) { 16932 msg.sendToTarget(); 16933 } 16934 mPostSystemReadyMessages = null; 16935 } 16936 16937 // Watch for external volumes that come and go over time 16938 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16939 storage.registerListener(mStorageListener); 16940 16941 mInstallerService.systemReady(); 16942 mPackageDexOptimizer.systemReady(); 16943 16944 MountServiceInternal mountServiceInternal = LocalServices.getService( 16945 MountServiceInternal.class); 16946 mountServiceInternal.addExternalStoragePolicy( 16947 new MountServiceInternal.ExternalStorageMountPolicy() { 16948 @Override 16949 public int getMountMode(int uid, String packageName) { 16950 if (Process.isIsolated(uid)) { 16951 return Zygote.MOUNT_EXTERNAL_NONE; 16952 } 16953 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 16954 return Zygote.MOUNT_EXTERNAL_DEFAULT; 16955 } 16956 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 16957 return Zygote.MOUNT_EXTERNAL_DEFAULT; 16958 } 16959 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 16960 return Zygote.MOUNT_EXTERNAL_READ; 16961 } 16962 return Zygote.MOUNT_EXTERNAL_WRITE; 16963 } 16964 16965 @Override 16966 public boolean hasExternalStorage(int uid, String packageName) { 16967 return true; 16968 } 16969 }); 16970 } 16971 16972 @Override 16973 public boolean isSafeMode() { 16974 return mSafeMode; 16975 } 16976 16977 @Override 16978 public boolean hasSystemUidErrors() { 16979 return mHasSystemUidErrors; 16980 } 16981 16982 static String arrayToString(int[] array) { 16983 StringBuffer buf = new StringBuffer(128); 16984 buf.append('['); 16985 if (array != null) { 16986 for (int i=0; i<array.length; i++) { 16987 if (i > 0) buf.append(", "); 16988 buf.append(array[i]); 16989 } 16990 } 16991 buf.append(']'); 16992 return buf.toString(); 16993 } 16994 16995 static class DumpState { 16996 public static final int DUMP_LIBS = 1 << 0; 16997 public static final int DUMP_FEATURES = 1 << 1; 16998 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 16999 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17000 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17001 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17002 public static final int DUMP_PERMISSIONS = 1 << 6; 17003 public static final int DUMP_PACKAGES = 1 << 7; 17004 public static final int DUMP_SHARED_USERS = 1 << 8; 17005 public static final int DUMP_MESSAGES = 1 << 9; 17006 public static final int DUMP_PROVIDERS = 1 << 10; 17007 public static final int DUMP_VERIFIERS = 1 << 11; 17008 public static final int DUMP_PREFERRED = 1 << 12; 17009 public static final int DUMP_PREFERRED_XML = 1 << 13; 17010 public static final int DUMP_KEYSETS = 1 << 14; 17011 public static final int DUMP_VERSION = 1 << 15; 17012 public static final int DUMP_INSTALLS = 1 << 16; 17013 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17014 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17015 17016 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17017 17018 private int mTypes; 17019 17020 private int mOptions; 17021 17022 private boolean mTitlePrinted; 17023 17024 private SharedUserSetting mSharedUser; 17025 17026 public boolean isDumping(int type) { 17027 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17028 return true; 17029 } 17030 17031 return (mTypes & type) != 0; 17032 } 17033 17034 public void setDump(int type) { 17035 mTypes |= type; 17036 } 17037 17038 public boolean isOptionEnabled(int option) { 17039 return (mOptions & option) != 0; 17040 } 17041 17042 public void setOptionEnabled(int option) { 17043 mOptions |= option; 17044 } 17045 17046 public boolean onTitlePrinted() { 17047 final boolean printed = mTitlePrinted; 17048 mTitlePrinted = true; 17049 return printed; 17050 } 17051 17052 public boolean getTitlePrinted() { 17053 return mTitlePrinted; 17054 } 17055 17056 public void setTitlePrinted(boolean enabled) { 17057 mTitlePrinted = enabled; 17058 } 17059 17060 public SharedUserSetting getSharedUser() { 17061 return mSharedUser; 17062 } 17063 17064 public void setSharedUser(SharedUserSetting user) { 17065 mSharedUser = user; 17066 } 17067 } 17068 17069 @Override 17070 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17071 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17072 (new PackageManagerShellCommand(this)).exec( 17073 this, in, out, err, args, resultReceiver); 17074 } 17075 17076 @Override 17077 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17078 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17079 != PackageManager.PERMISSION_GRANTED) { 17080 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17081 + Binder.getCallingPid() 17082 + ", uid=" + Binder.getCallingUid() 17083 + " without permission " 17084 + android.Manifest.permission.DUMP); 17085 return; 17086 } 17087 17088 DumpState dumpState = new DumpState(); 17089 boolean fullPreferred = false; 17090 boolean checkin = false; 17091 17092 String packageName = null; 17093 ArraySet<String> permissionNames = null; 17094 17095 int opti = 0; 17096 while (opti < args.length) { 17097 String opt = args[opti]; 17098 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 17099 break; 17100 } 17101 opti++; 17102 17103 if ("-a".equals(opt)) { 17104 // Right now we only know how to print all. 17105 } else if ("-h".equals(opt)) { 17106 pw.println("Package manager dump options:"); 17107 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 17108 pw.println(" --checkin: dump for a checkin"); 17109 pw.println(" -f: print details of intent filters"); 17110 pw.println(" -h: print this help"); 17111 pw.println(" cmd may be one of:"); 17112 pw.println(" l[ibraries]: list known shared libraries"); 17113 pw.println(" f[eatures]: list device features"); 17114 pw.println(" k[eysets]: print known keysets"); 17115 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 17116 pw.println(" perm[issions]: dump permissions"); 17117 pw.println(" permission [name ...]: dump declaration and use of given permission"); 17118 pw.println(" pref[erred]: print preferred package settings"); 17119 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 17120 pw.println(" prov[iders]: dump content providers"); 17121 pw.println(" p[ackages]: dump installed packages"); 17122 pw.println(" s[hared-users]: dump shared user IDs"); 17123 pw.println(" m[essages]: print collected runtime messages"); 17124 pw.println(" v[erifiers]: print package verifier info"); 17125 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 17126 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 17127 pw.println(" version: print database version info"); 17128 pw.println(" write: write current settings now"); 17129 pw.println(" installs: details about install sessions"); 17130 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 17131 pw.println(" <package.name>: info about given package"); 17132 return; 17133 } else if ("--checkin".equals(opt)) { 17134 checkin = true; 17135 } else if ("-f".equals(opt)) { 17136 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17137 } else { 17138 pw.println("Unknown argument: " + opt + "; use -h for help"); 17139 } 17140 } 17141 17142 // Is the caller requesting to dump a particular piece of data? 17143 if (opti < args.length) { 17144 String cmd = args[opti]; 17145 opti++; 17146 // Is this a package name? 17147 if ("android".equals(cmd) || cmd.contains(".")) { 17148 packageName = cmd; 17149 // When dumping a single package, we always dump all of its 17150 // filter information since the amount of data will be reasonable. 17151 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17152 } else if ("check-permission".equals(cmd)) { 17153 if (opti >= args.length) { 17154 pw.println("Error: check-permission missing permission argument"); 17155 return; 17156 } 17157 String perm = args[opti]; 17158 opti++; 17159 if (opti >= args.length) { 17160 pw.println("Error: check-permission missing package argument"); 17161 return; 17162 } 17163 String pkg = args[opti]; 17164 opti++; 17165 int user = UserHandle.getUserId(Binder.getCallingUid()); 17166 if (opti < args.length) { 17167 try { 17168 user = Integer.parseInt(args[opti]); 17169 } catch (NumberFormatException e) { 17170 pw.println("Error: check-permission user argument is not a number: " 17171 + args[opti]); 17172 return; 17173 } 17174 } 17175 pw.println(checkPermission(perm, pkg, user)); 17176 return; 17177 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 17178 dumpState.setDump(DumpState.DUMP_LIBS); 17179 } else if ("f".equals(cmd) || "features".equals(cmd)) { 17180 dumpState.setDump(DumpState.DUMP_FEATURES); 17181 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 17182 if (opti >= args.length) { 17183 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 17184 | DumpState.DUMP_SERVICE_RESOLVERS 17185 | DumpState.DUMP_RECEIVER_RESOLVERS 17186 | DumpState.DUMP_CONTENT_RESOLVERS); 17187 } else { 17188 while (opti < args.length) { 17189 String name = args[opti]; 17190 if ("a".equals(name) || "activity".equals(name)) { 17191 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 17192 } else if ("s".equals(name) || "service".equals(name)) { 17193 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 17194 } else if ("r".equals(name) || "receiver".equals(name)) { 17195 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 17196 } else if ("c".equals(name) || "content".equals(name)) { 17197 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 17198 } else { 17199 pw.println("Error: unknown resolver table type: " + name); 17200 return; 17201 } 17202 opti++; 17203 } 17204 } 17205 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 17206 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 17207 } else if ("permission".equals(cmd)) { 17208 if (opti >= args.length) { 17209 pw.println("Error: permission requires permission name"); 17210 return; 17211 } 17212 permissionNames = new ArraySet<>(); 17213 while (opti < args.length) { 17214 permissionNames.add(args[opti]); 17215 opti++; 17216 } 17217 dumpState.setDump(DumpState.DUMP_PERMISSIONS 17218 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 17219 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 17220 dumpState.setDump(DumpState.DUMP_PREFERRED); 17221 } else if ("preferred-xml".equals(cmd)) { 17222 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 17223 if (opti < args.length && "--full".equals(args[opti])) { 17224 fullPreferred = true; 17225 opti++; 17226 } 17227 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 17228 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 17229 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 17230 dumpState.setDump(DumpState.DUMP_PACKAGES); 17231 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 17232 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 17233 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 17234 dumpState.setDump(DumpState.DUMP_PROVIDERS); 17235 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 17236 dumpState.setDump(DumpState.DUMP_MESSAGES); 17237 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 17238 dumpState.setDump(DumpState.DUMP_VERIFIERS); 17239 } else if ("i".equals(cmd) || "ifv".equals(cmd) 17240 || "intent-filter-verifiers".equals(cmd)) { 17241 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 17242 } else if ("version".equals(cmd)) { 17243 dumpState.setDump(DumpState.DUMP_VERSION); 17244 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 17245 dumpState.setDump(DumpState.DUMP_KEYSETS); 17246 } else if ("installs".equals(cmd)) { 17247 dumpState.setDump(DumpState.DUMP_INSTALLS); 17248 } else if ("write".equals(cmd)) { 17249 synchronized (mPackages) { 17250 mSettings.writeLPr(); 17251 pw.println("Settings written."); 17252 return; 17253 } 17254 } 17255 } 17256 17257 if (checkin) { 17258 pw.println("vers,1"); 17259 } 17260 17261 // reader 17262 synchronized (mPackages) { 17263 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 17264 if (!checkin) { 17265 if (dumpState.onTitlePrinted()) 17266 pw.println(); 17267 pw.println("Database versions:"); 17268 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 17269 } 17270 } 17271 17272 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 17273 if (!checkin) { 17274 if (dumpState.onTitlePrinted()) 17275 pw.println(); 17276 pw.println("Verifiers:"); 17277 pw.print(" Required: "); 17278 pw.print(mRequiredVerifierPackage); 17279 pw.print(" (uid="); 17280 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17281 UserHandle.USER_SYSTEM)); 17282 pw.println(")"); 17283 } else if (mRequiredVerifierPackage != null) { 17284 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 17285 pw.print(","); 17286 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17287 UserHandle.USER_SYSTEM)); 17288 } 17289 } 17290 17291 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 17292 packageName == null) { 17293 if (mIntentFilterVerifierComponent != null) { 17294 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 17295 if (!checkin) { 17296 if (dumpState.onTitlePrinted()) 17297 pw.println(); 17298 pw.println("Intent Filter Verifier:"); 17299 pw.print(" Using: "); 17300 pw.print(verifierPackageName); 17301 pw.print(" (uid="); 17302 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17303 UserHandle.USER_SYSTEM)); 17304 pw.println(")"); 17305 } else if (verifierPackageName != null) { 17306 pw.print("ifv,"); pw.print(verifierPackageName); 17307 pw.print(","); 17308 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17309 UserHandle.USER_SYSTEM)); 17310 } 17311 } else { 17312 pw.println(); 17313 pw.println("No Intent Filter Verifier available!"); 17314 } 17315 } 17316 17317 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 17318 boolean printedHeader = false; 17319 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 17320 while (it.hasNext()) { 17321 String name = it.next(); 17322 SharedLibraryEntry ent = mSharedLibraries.get(name); 17323 if (!checkin) { 17324 if (!printedHeader) { 17325 if (dumpState.onTitlePrinted()) 17326 pw.println(); 17327 pw.println("Libraries:"); 17328 printedHeader = true; 17329 } 17330 pw.print(" "); 17331 } else { 17332 pw.print("lib,"); 17333 } 17334 pw.print(name); 17335 if (!checkin) { 17336 pw.print(" -> "); 17337 } 17338 if (ent.path != null) { 17339 if (!checkin) { 17340 pw.print("(jar) "); 17341 pw.print(ent.path); 17342 } else { 17343 pw.print(",jar,"); 17344 pw.print(ent.path); 17345 } 17346 } else { 17347 if (!checkin) { 17348 pw.print("(apk) "); 17349 pw.print(ent.apk); 17350 } else { 17351 pw.print(",apk,"); 17352 pw.print(ent.apk); 17353 } 17354 } 17355 pw.println(); 17356 } 17357 } 17358 17359 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 17360 if (dumpState.onTitlePrinted()) 17361 pw.println(); 17362 if (!checkin) { 17363 pw.println("Features:"); 17364 } 17365 17366 for (FeatureInfo feat : mAvailableFeatures.values()) { 17367 if (checkin) { 17368 pw.print("feat,"); 17369 pw.print(feat.name); 17370 pw.print(","); 17371 pw.println(feat.version); 17372 } else { 17373 pw.print(" "); 17374 pw.print(feat.name); 17375 if (feat.version > 0) { 17376 pw.print(" version="); 17377 pw.print(feat.version); 17378 } 17379 pw.println(); 17380 } 17381 } 17382 } 17383 17384 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 17385 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 17386 : "Activity Resolver Table:", " ", packageName, 17387 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17388 dumpState.setTitlePrinted(true); 17389 } 17390 } 17391 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 17392 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 17393 : "Receiver Resolver Table:", " ", packageName, 17394 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17395 dumpState.setTitlePrinted(true); 17396 } 17397 } 17398 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 17399 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 17400 : "Service Resolver Table:", " ", packageName, 17401 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17402 dumpState.setTitlePrinted(true); 17403 } 17404 } 17405 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 17406 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 17407 : "Provider Resolver Table:", " ", packageName, 17408 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17409 dumpState.setTitlePrinted(true); 17410 } 17411 } 17412 17413 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 17414 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17415 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17416 int user = mSettings.mPreferredActivities.keyAt(i); 17417 if (pir.dump(pw, 17418 dumpState.getTitlePrinted() 17419 ? "\nPreferred Activities User " + user + ":" 17420 : "Preferred Activities User " + user + ":", " ", 17421 packageName, true, false)) { 17422 dumpState.setTitlePrinted(true); 17423 } 17424 } 17425 } 17426 17427 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 17428 pw.flush(); 17429 FileOutputStream fout = new FileOutputStream(fd); 17430 BufferedOutputStream str = new BufferedOutputStream(fout); 17431 XmlSerializer serializer = new FastXmlSerializer(); 17432 try { 17433 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 17434 serializer.startDocument(null, true); 17435 serializer.setFeature( 17436 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 17437 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 17438 serializer.endDocument(); 17439 serializer.flush(); 17440 } catch (IllegalArgumentException e) { 17441 pw.println("Failed writing: " + e); 17442 } catch (IllegalStateException e) { 17443 pw.println("Failed writing: " + e); 17444 } catch (IOException e) { 17445 pw.println("Failed writing: " + e); 17446 } 17447 } 17448 17449 if (!checkin 17450 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 17451 && packageName == null) { 17452 pw.println(); 17453 int count = mSettings.mPackages.size(); 17454 if (count == 0) { 17455 pw.println("No applications!"); 17456 pw.println(); 17457 } else { 17458 final String prefix = " "; 17459 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 17460 if (allPackageSettings.size() == 0) { 17461 pw.println("No domain preferred apps!"); 17462 pw.println(); 17463 } else { 17464 pw.println("App verification status:"); 17465 pw.println(); 17466 count = 0; 17467 for (PackageSetting ps : allPackageSettings) { 17468 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 17469 if (ivi == null || ivi.getPackageName() == null) continue; 17470 pw.println(prefix + "Package: " + ivi.getPackageName()); 17471 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 17472 pw.println(prefix + "Status: " + ivi.getStatusString()); 17473 pw.println(); 17474 count++; 17475 } 17476 if (count == 0) { 17477 pw.println(prefix + "No app verification established."); 17478 pw.println(); 17479 } 17480 for (int userId : sUserManager.getUserIds()) { 17481 pw.println("App linkages for user " + userId + ":"); 17482 pw.println(); 17483 count = 0; 17484 for (PackageSetting ps : allPackageSettings) { 17485 final long status = ps.getDomainVerificationStatusForUser(userId); 17486 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 17487 continue; 17488 } 17489 pw.println(prefix + "Package: " + ps.name); 17490 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 17491 String statusStr = IntentFilterVerificationInfo. 17492 getStatusStringFromValue(status); 17493 pw.println(prefix + "Status: " + statusStr); 17494 pw.println(); 17495 count++; 17496 } 17497 if (count == 0) { 17498 pw.println(prefix + "No configured app linkages."); 17499 pw.println(); 17500 } 17501 } 17502 } 17503 } 17504 } 17505 17506 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 17507 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 17508 if (packageName == null && permissionNames == null) { 17509 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 17510 if (iperm == 0) { 17511 if (dumpState.onTitlePrinted()) 17512 pw.println(); 17513 pw.println("AppOp Permissions:"); 17514 } 17515 pw.print(" AppOp Permission "); 17516 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 17517 pw.println(":"); 17518 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 17519 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 17520 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 17521 } 17522 } 17523 } 17524 } 17525 17526 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 17527 boolean printedSomething = false; 17528 for (PackageParser.Provider p : mProviders.mProviders.values()) { 17529 if (packageName != null && !packageName.equals(p.info.packageName)) { 17530 continue; 17531 } 17532 if (!printedSomething) { 17533 if (dumpState.onTitlePrinted()) 17534 pw.println(); 17535 pw.println("Registered ContentProviders:"); 17536 printedSomething = true; 17537 } 17538 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 17539 pw.print(" "); pw.println(p.toString()); 17540 } 17541 printedSomething = false; 17542 for (Map.Entry<String, PackageParser.Provider> entry : 17543 mProvidersByAuthority.entrySet()) { 17544 PackageParser.Provider p = entry.getValue(); 17545 if (packageName != null && !packageName.equals(p.info.packageName)) { 17546 continue; 17547 } 17548 if (!printedSomething) { 17549 if (dumpState.onTitlePrinted()) 17550 pw.println(); 17551 pw.println("ContentProvider Authorities:"); 17552 printedSomething = true; 17553 } 17554 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 17555 pw.print(" "); pw.println(p.toString()); 17556 if (p.info != null && p.info.applicationInfo != null) { 17557 final String appInfo = p.info.applicationInfo.toString(); 17558 pw.print(" applicationInfo="); pw.println(appInfo); 17559 } 17560 } 17561 } 17562 17563 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 17564 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 17565 } 17566 17567 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 17568 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 17569 } 17570 17571 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 17572 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 17573 } 17574 17575 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 17576 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 17577 } 17578 17579 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 17580 // XXX should handle packageName != null by dumping only install data that 17581 // the given package is involved with. 17582 if (dumpState.onTitlePrinted()) pw.println(); 17583 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 17584 } 17585 17586 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 17587 if (dumpState.onTitlePrinted()) pw.println(); 17588 mSettings.dumpReadMessagesLPr(pw, dumpState); 17589 17590 pw.println(); 17591 pw.println("Package warning messages:"); 17592 BufferedReader in = null; 17593 String line = null; 17594 try { 17595 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 17596 while ((line = in.readLine()) != null) { 17597 if (line.contains("ignored: updated version")) continue; 17598 pw.println(line); 17599 } 17600 } catch (IOException ignored) { 17601 } finally { 17602 IoUtils.closeQuietly(in); 17603 } 17604 } 17605 17606 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 17607 BufferedReader in = null; 17608 String line = null; 17609 try { 17610 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 17611 while ((line = in.readLine()) != null) { 17612 if (line.contains("ignored: updated version")) continue; 17613 pw.print("msg,"); 17614 pw.println(line); 17615 } 17616 } catch (IOException ignored) { 17617 } finally { 17618 IoUtils.closeQuietly(in); 17619 } 17620 } 17621 } 17622 } 17623 17624 private String dumpDomainString(String packageName) { 17625 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 17626 .getList(); 17627 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 17628 17629 ArraySet<String> result = new ArraySet<>(); 17630 if (iviList.size() > 0) { 17631 for (IntentFilterVerificationInfo ivi : iviList) { 17632 for (String host : ivi.getDomains()) { 17633 result.add(host); 17634 } 17635 } 17636 } 17637 if (filters != null && filters.size() > 0) { 17638 for (IntentFilter filter : filters) { 17639 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 17640 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 17641 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 17642 result.addAll(filter.getHostsList()); 17643 } 17644 } 17645 } 17646 17647 StringBuilder sb = new StringBuilder(result.size() * 16); 17648 for (String domain : result) { 17649 if (sb.length() > 0) sb.append(" "); 17650 sb.append(domain); 17651 } 17652 return sb.toString(); 17653 } 17654 17655 // ------- apps on sdcard specific code ------- 17656 static final boolean DEBUG_SD_INSTALL = false; 17657 17658 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 17659 17660 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 17661 17662 private boolean mMediaMounted = false; 17663 17664 static String getEncryptKey() { 17665 try { 17666 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 17667 SD_ENCRYPTION_KEYSTORE_NAME); 17668 if (sdEncKey == null) { 17669 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 17670 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 17671 if (sdEncKey == null) { 17672 Slog.e(TAG, "Failed to create encryption keys"); 17673 return null; 17674 } 17675 } 17676 return sdEncKey; 17677 } catch (NoSuchAlgorithmException nsae) { 17678 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 17679 return null; 17680 } catch (IOException ioe) { 17681 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 17682 return null; 17683 } 17684 } 17685 17686 /* 17687 * Update media status on PackageManager. 17688 */ 17689 @Override 17690 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 17691 int callingUid = Binder.getCallingUid(); 17692 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 17693 throw new SecurityException("Media status can only be updated by the system"); 17694 } 17695 // reader; this apparently protects mMediaMounted, but should probably 17696 // be a different lock in that case. 17697 synchronized (mPackages) { 17698 Log.i(TAG, "Updating external media status from " 17699 + (mMediaMounted ? "mounted" : "unmounted") + " to " 17700 + (mediaStatus ? "mounted" : "unmounted")); 17701 if (DEBUG_SD_INSTALL) 17702 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 17703 + ", mMediaMounted=" + mMediaMounted); 17704 if (mediaStatus == mMediaMounted) { 17705 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 17706 : 0, -1); 17707 mHandler.sendMessage(msg); 17708 return; 17709 } 17710 mMediaMounted = mediaStatus; 17711 } 17712 // Queue up an async operation since the package installation may take a 17713 // little while. 17714 mHandler.post(new Runnable() { 17715 public void run() { 17716 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 17717 } 17718 }); 17719 } 17720 17721 /** 17722 * Called by MountService when the initial ASECs to scan are available. 17723 * Should block until all the ASEC containers are finished being scanned. 17724 */ 17725 public void scanAvailableAsecs() { 17726 updateExternalMediaStatusInner(true, false, false); 17727 } 17728 17729 /* 17730 * Collect information of applications on external media, map them against 17731 * existing containers and update information based on current mount status. 17732 * Please note that we always have to report status if reportStatus has been 17733 * set to true especially when unloading packages. 17734 */ 17735 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 17736 boolean externalStorage) { 17737 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 17738 int[] uidArr = EmptyArray.INT; 17739 17740 final String[] list = PackageHelper.getSecureContainerList(); 17741 if (ArrayUtils.isEmpty(list)) { 17742 Log.i(TAG, "No secure containers found"); 17743 } else { 17744 // Process list of secure containers and categorize them 17745 // as active or stale based on their package internal state. 17746 17747 // reader 17748 synchronized (mPackages) { 17749 for (String cid : list) { 17750 // Leave stages untouched for now; installer service owns them 17751 if (PackageInstallerService.isStageName(cid)) continue; 17752 17753 if (DEBUG_SD_INSTALL) 17754 Log.i(TAG, "Processing container " + cid); 17755 String pkgName = getAsecPackageName(cid); 17756 if (pkgName == null) { 17757 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 17758 continue; 17759 } 17760 if (DEBUG_SD_INSTALL) 17761 Log.i(TAG, "Looking for pkg : " + pkgName); 17762 17763 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17764 if (ps == null) { 17765 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 17766 continue; 17767 } 17768 17769 /* 17770 * Skip packages that are not external if we're unmounting 17771 * external storage. 17772 */ 17773 if (externalStorage && !isMounted && !isExternal(ps)) { 17774 continue; 17775 } 17776 17777 final AsecInstallArgs args = new AsecInstallArgs(cid, 17778 getAppDexInstructionSets(ps), ps.isForwardLocked()); 17779 // The package status is changed only if the code path 17780 // matches between settings and the container id. 17781 if (ps.codePathString != null 17782 && ps.codePathString.startsWith(args.getCodePath())) { 17783 if (DEBUG_SD_INSTALL) { 17784 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 17785 + " at code path: " + ps.codePathString); 17786 } 17787 17788 // We do have a valid package installed on sdcard 17789 processCids.put(args, ps.codePathString); 17790 final int uid = ps.appId; 17791 if (uid != -1) { 17792 uidArr = ArrayUtils.appendInt(uidArr, uid); 17793 } 17794 } else { 17795 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 17796 + ps.codePathString); 17797 } 17798 } 17799 } 17800 17801 Arrays.sort(uidArr); 17802 } 17803 17804 // Process packages with valid entries. 17805 if (isMounted) { 17806 if (DEBUG_SD_INSTALL) 17807 Log.i(TAG, "Loading packages"); 17808 loadMediaPackages(processCids, uidArr, externalStorage); 17809 startCleaningPackages(); 17810 mInstallerService.onSecureContainersAvailable(); 17811 } else { 17812 if (DEBUG_SD_INSTALL) 17813 Log.i(TAG, "Unloading packages"); 17814 unloadMediaPackages(processCids, uidArr, reportStatus); 17815 } 17816 } 17817 17818 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17819 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 17820 final int size = infos.size(); 17821 final String[] packageNames = new String[size]; 17822 final int[] packageUids = new int[size]; 17823 for (int i = 0; i < size; i++) { 17824 final ApplicationInfo info = infos.get(i); 17825 packageNames[i] = info.packageName; 17826 packageUids[i] = info.uid; 17827 } 17828 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 17829 finishedReceiver); 17830 } 17831 17832 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17833 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 17834 sendResourcesChangedBroadcast(mediaStatus, replacing, 17835 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 17836 } 17837 17838 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17839 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 17840 int size = pkgList.length; 17841 if (size > 0) { 17842 // Send broadcasts here 17843 Bundle extras = new Bundle(); 17844 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 17845 if (uidArr != null) { 17846 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 17847 } 17848 if (replacing) { 17849 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 17850 } 17851 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 17852 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 17853 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 17854 } 17855 } 17856 17857 /* 17858 * Look at potentially valid container ids from processCids If package 17859 * information doesn't match the one on record or package scanning fails, 17860 * the cid is added to list of removeCids. We currently don't delete stale 17861 * containers. 17862 */ 17863 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 17864 boolean externalStorage) { 17865 ArrayList<String> pkgList = new ArrayList<String>(); 17866 Set<AsecInstallArgs> keys = processCids.keySet(); 17867 17868 for (AsecInstallArgs args : keys) { 17869 String codePath = processCids.get(args); 17870 if (DEBUG_SD_INSTALL) 17871 Log.i(TAG, "Loading container : " + args.cid); 17872 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 17873 try { 17874 // Make sure there are no container errors first. 17875 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 17876 Slog.e(TAG, "Failed to mount cid : " + args.cid 17877 + " when installing from sdcard"); 17878 continue; 17879 } 17880 // Check code path here. 17881 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 17882 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 17883 + " does not match one in settings " + codePath); 17884 continue; 17885 } 17886 // Parse package 17887 int parseFlags = mDefParseFlags; 17888 if (args.isExternalAsec()) { 17889 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 17890 } 17891 if (args.isFwdLocked()) { 17892 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 17893 } 17894 17895 synchronized (mInstallLock) { 17896 PackageParser.Package pkg = null; 17897 try { 17898 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 17899 } catch (PackageManagerException e) { 17900 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 17901 } 17902 // Scan the package 17903 if (pkg != null) { 17904 /* 17905 * TODO why is the lock being held? doPostInstall is 17906 * called in other places without the lock. This needs 17907 * to be straightened out. 17908 */ 17909 // writer 17910 synchronized (mPackages) { 17911 retCode = PackageManager.INSTALL_SUCCEEDED; 17912 pkgList.add(pkg.packageName); 17913 // Post process args 17914 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 17915 pkg.applicationInfo.uid); 17916 } 17917 } else { 17918 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 17919 } 17920 } 17921 17922 } finally { 17923 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 17924 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 17925 } 17926 } 17927 } 17928 // writer 17929 synchronized (mPackages) { 17930 // If the platform SDK has changed since the last time we booted, 17931 // we need to re-grant app permission to catch any new ones that 17932 // appear. This is really a hack, and means that apps can in some 17933 // cases get permissions that the user didn't initially explicitly 17934 // allow... it would be nice to have some better way to handle 17935 // this situation. 17936 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 17937 : mSettings.getInternalVersion(); 17938 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 17939 : StorageManager.UUID_PRIVATE_INTERNAL; 17940 17941 int updateFlags = UPDATE_PERMISSIONS_ALL; 17942 if (ver.sdkVersion != mSdkVersion) { 17943 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 17944 + mSdkVersion + "; regranting permissions for external"); 17945 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 17946 } 17947 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 17948 17949 // Yay, everything is now upgraded 17950 ver.forceCurrent(); 17951 17952 // can downgrade to reader 17953 // Persist settings 17954 mSettings.writeLPr(); 17955 } 17956 // Send a broadcast to let everyone know we are done processing 17957 if (pkgList.size() > 0) { 17958 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 17959 } 17960 } 17961 17962 /* 17963 * Utility method to unload a list of specified containers 17964 */ 17965 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 17966 // Just unmount all valid containers. 17967 for (AsecInstallArgs arg : cidArgs) { 17968 synchronized (mInstallLock) { 17969 arg.doPostDeleteLI(false); 17970 } 17971 } 17972 } 17973 17974 /* 17975 * Unload packages mounted on external media. This involves deleting package 17976 * data from internal structures, sending broadcasts about disabled packages, 17977 * gc'ing to free up references, unmounting all secure containers 17978 * corresponding to packages on external media, and posting a 17979 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 17980 * that we always have to post this message if status has been requested no 17981 * matter what. 17982 */ 17983 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 17984 final boolean reportStatus) { 17985 if (DEBUG_SD_INSTALL) 17986 Log.i(TAG, "unloading media packages"); 17987 ArrayList<String> pkgList = new ArrayList<String>(); 17988 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 17989 final Set<AsecInstallArgs> keys = processCids.keySet(); 17990 for (AsecInstallArgs args : keys) { 17991 String pkgName = args.getPackageName(); 17992 if (DEBUG_SD_INSTALL) 17993 Log.i(TAG, "Trying to unload pkg : " + pkgName); 17994 // Delete package internally 17995 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 17996 synchronized (mInstallLock) { 17997 boolean res = deletePackageLI(pkgName, null, false, null, 17998 PackageManager.DELETE_KEEP_DATA, outInfo, false, null); 17999 if (res) { 18000 pkgList.add(pkgName); 18001 } else { 18002 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18003 failedList.add(args); 18004 } 18005 } 18006 } 18007 18008 // reader 18009 synchronized (mPackages) { 18010 // We didn't update the settings after removing each package; 18011 // write them now for all packages. 18012 mSettings.writeLPr(); 18013 } 18014 18015 // We have to absolutely send UPDATED_MEDIA_STATUS only 18016 // after confirming that all the receivers processed the ordered 18017 // broadcast when packages get disabled, force a gc to clean things up. 18018 // and unload all the containers. 18019 if (pkgList.size() > 0) { 18020 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18021 new IIntentReceiver.Stub() { 18022 public void performReceive(Intent intent, int resultCode, String data, 18023 Bundle extras, boolean ordered, boolean sticky, 18024 int sendingUser) throws RemoteException { 18025 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18026 reportStatus ? 1 : 0, 1, keys); 18027 mHandler.sendMessage(msg); 18028 } 18029 }); 18030 } else { 18031 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 18032 keys); 18033 mHandler.sendMessage(msg); 18034 } 18035 } 18036 18037 private void loadPrivatePackages(final VolumeInfo vol) { 18038 mHandler.post(new Runnable() { 18039 @Override 18040 public void run() { 18041 loadPrivatePackagesInner(vol); 18042 } 18043 }); 18044 } 18045 18046 private void loadPrivatePackagesInner(VolumeInfo vol) { 18047 final String volumeUuid = vol.fsUuid; 18048 if (TextUtils.isEmpty(volumeUuid)) { 18049 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 18050 return; 18051 } 18052 18053 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 18054 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 18055 18056 final VersionInfo ver; 18057 final List<PackageSetting> packages; 18058 synchronized (mPackages) { 18059 ver = mSettings.findOrCreateVersion(volumeUuid); 18060 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18061 } 18062 18063 // TODO: introduce a new concept similar to "frozen" to prevent these 18064 // apps from being launched until after data has been fully reconciled 18065 for (PackageSetting ps : packages) { 18066 synchronized (mInstallLock) { 18067 final PackageParser.Package pkg; 18068 try { 18069 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 18070 loaded.add(pkg.applicationInfo); 18071 18072 } catch (PackageManagerException e) { 18073 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 18074 } 18075 18076 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 18077 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 18078 } 18079 } 18080 } 18081 18082 // Reconcile app data for all started/unlocked users 18083 final StorageManager sm = mContext.getSystemService(StorageManager.class); 18084 final UserManager um = mContext.getSystemService(UserManager.class); 18085 for (UserInfo user : um.getUsers()) { 18086 final int flags; 18087 if (um.isUserUnlocked(user.id)) { 18088 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18089 } else if (um.isUserRunning(user.id)) { 18090 flags = StorageManager.FLAG_STORAGE_DE; 18091 } else { 18092 continue; 18093 } 18094 18095 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 18096 reconcileAppsData(volumeUuid, user.id, flags); 18097 } 18098 18099 synchronized (mPackages) { 18100 int updateFlags = UPDATE_PERMISSIONS_ALL; 18101 if (ver.sdkVersion != mSdkVersion) { 18102 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18103 + mSdkVersion + "; regranting permissions for " + volumeUuid); 18104 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18105 } 18106 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18107 18108 // Yay, everything is now upgraded 18109 ver.forceCurrent(); 18110 18111 mSettings.writeLPr(); 18112 } 18113 18114 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 18115 sendResourcesChangedBroadcast(true, false, loaded, null); 18116 } 18117 18118 private void unloadPrivatePackages(final VolumeInfo vol) { 18119 mHandler.post(new Runnable() { 18120 @Override 18121 public void run() { 18122 unloadPrivatePackagesInner(vol); 18123 } 18124 }); 18125 } 18126 18127 private void unloadPrivatePackagesInner(VolumeInfo vol) { 18128 final String volumeUuid = vol.fsUuid; 18129 if (TextUtils.isEmpty(volumeUuid)) { 18130 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 18131 return; 18132 } 18133 18134 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 18135 synchronized (mInstallLock) { 18136 synchronized (mPackages) { 18137 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 18138 for (PackageSetting ps : packages) { 18139 if (ps.pkg == null) continue; 18140 18141 final ApplicationInfo info = ps.pkg.applicationInfo; 18142 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18143 if (deletePackageLI(ps.name, null, false, null, 18144 PackageManager.DELETE_KEEP_DATA, outInfo, false, null)) { 18145 unloaded.add(info); 18146 } else { 18147 Slog.w(TAG, "Failed to unload " + ps.codePath); 18148 } 18149 } 18150 18151 mSettings.writeLPr(); 18152 } 18153 } 18154 18155 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 18156 sendResourcesChangedBroadcast(false, false, unloaded, null); 18157 } 18158 18159 /** 18160 * Examine all users present on given mounted volume, and destroy data 18161 * belonging to users that are no longer valid, or whose user ID has been 18162 * recycled. 18163 */ 18164 private void reconcileUsers(String volumeUuid) { 18165 // TODO: also reconcile DE directories 18166 final File[] files = FileUtils 18167 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)); 18168 for (File file : files) { 18169 if (!file.isDirectory()) continue; 18170 18171 final int userId; 18172 final UserInfo info; 18173 try { 18174 userId = Integer.parseInt(file.getName()); 18175 info = sUserManager.getUserInfo(userId); 18176 } catch (NumberFormatException e) { 18177 Slog.w(TAG, "Invalid user directory " + file); 18178 continue; 18179 } 18180 18181 boolean destroyUser = false; 18182 if (info == null) { 18183 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18184 + " because no matching user was found"); 18185 destroyUser = true; 18186 } else { 18187 try { 18188 UserManagerService.enforceSerialNumber(file, info.serialNumber); 18189 } catch (IOException e) { 18190 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18191 + " because we failed to enforce serial number: " + e); 18192 destroyUser = true; 18193 } 18194 } 18195 18196 if (destroyUser) { 18197 synchronized (mInstallLock) { 18198 try { 18199 mInstaller.removeUserDataDirs(volumeUuid, userId); 18200 } catch (InstallerException e) { 18201 Slog.w(TAG, "Failed to clean up user dirs", e); 18202 } 18203 } 18204 } 18205 } 18206 } 18207 18208 private void assertPackageKnown(String volumeUuid, String packageName) 18209 throws PackageManagerException { 18210 synchronized (mPackages) { 18211 final PackageSetting ps = mSettings.mPackages.get(packageName); 18212 if (ps == null) { 18213 throw new PackageManagerException("Package " + packageName + " is unknown"); 18214 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18215 throw new PackageManagerException( 18216 "Package " + packageName + " found on unknown volume " + volumeUuid 18217 + "; expected volume " + ps.volumeUuid); 18218 } 18219 } 18220 } 18221 18222 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 18223 throws PackageManagerException { 18224 synchronized (mPackages) { 18225 final PackageSetting ps = mSettings.mPackages.get(packageName); 18226 if (ps == null) { 18227 throw new PackageManagerException("Package " + packageName + " is unknown"); 18228 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18229 throw new PackageManagerException( 18230 "Package " + packageName + " found on unknown volume " + volumeUuid 18231 + "; expected volume " + ps.volumeUuid); 18232 } else if (!ps.getInstalled(userId)) { 18233 throw new PackageManagerException( 18234 "Package " + packageName + " not installed for user " + userId); 18235 } 18236 } 18237 } 18238 18239 /** 18240 * Examine all apps present on given mounted volume, and destroy apps that 18241 * aren't expected, either due to uninstallation or reinstallation on 18242 * another volume. 18243 */ 18244 private void reconcileApps(String volumeUuid) { 18245 final File[] files = FileUtils 18246 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 18247 for (File file : files) { 18248 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 18249 && !PackageInstallerService.isStageName(file.getName()); 18250 if (!isPackage) { 18251 // Ignore entries which are not packages 18252 continue; 18253 } 18254 18255 try { 18256 final PackageLite pkg = PackageParser.parsePackageLite(file, 18257 PackageParser.PARSE_MUST_BE_APK); 18258 assertPackageKnown(volumeUuid, pkg.packageName); 18259 18260 } catch (PackageParserException | PackageManagerException e) { 18261 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18262 synchronized (mInstallLock) { 18263 removeCodePathLI(file); 18264 } 18265 } 18266 } 18267 } 18268 18269 /** 18270 * Reconcile all app data for the given user. 18271 * <p> 18272 * Verifies that directories exist and that ownership and labeling is 18273 * correct for all installed apps on all mounted volumes. 18274 */ 18275 void reconcileAppsData(int userId, int flags) { 18276 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18277 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18278 final String volumeUuid = vol.getFsUuid(); 18279 reconcileAppsData(volumeUuid, userId, flags); 18280 } 18281 } 18282 18283 /** 18284 * Reconcile all app data on given mounted volume. 18285 * <p> 18286 * Destroys app data that isn't expected, either due to uninstallation or 18287 * reinstallation on another volume. 18288 * <p> 18289 * Verifies that directories exist and that ownership and labeling is 18290 * correct for all installed apps. 18291 */ 18292 private void reconcileAppsData(String volumeUuid, int userId, int flags) { 18293 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 18294 + Integer.toHexString(flags)); 18295 18296 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 18297 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 18298 18299 boolean restoreconNeeded = false; 18300 18301 // First look for stale data that doesn't belong, and check if things 18302 // have changed since we did our last restorecon 18303 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18304 if (!isUserKeyUnlocked(userId)) { 18305 throw new RuntimeException( 18306 "Yikes, someone asked us to reconcile CE storage while " + userId 18307 + " was still locked; this would have caused massive data loss!"); 18308 } 18309 18310 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 18311 18312 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 18313 for (File file : files) { 18314 final String packageName = file.getName(); 18315 try { 18316 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18317 } catch (PackageManagerException e) { 18318 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18319 synchronized (mInstallLock) { 18320 destroyAppDataLI(volumeUuid, packageName, userId, 18321 StorageManager.FLAG_STORAGE_CE); 18322 } 18323 } 18324 } 18325 } 18326 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18327 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 18328 18329 final File[] files = FileUtils.listFilesOrEmpty(deDir); 18330 for (File file : files) { 18331 final String packageName = file.getName(); 18332 try { 18333 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18334 } catch (PackageManagerException e) { 18335 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18336 synchronized (mInstallLock) { 18337 destroyAppDataLI(volumeUuid, packageName, userId, 18338 StorageManager.FLAG_STORAGE_DE); 18339 } 18340 } 18341 } 18342 } 18343 18344 // Ensure that data directories are ready to roll for all packages 18345 // installed for this volume and user 18346 final List<PackageSetting> packages; 18347 synchronized (mPackages) { 18348 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18349 } 18350 int preparedCount = 0; 18351 for (PackageSetting ps : packages) { 18352 final String packageName = ps.name; 18353 if (ps.pkg == null) { 18354 Slog.w(TAG, "Odd, missing scanned package " + packageName); 18355 // TODO: might be due to legacy ASEC apps; we should circle back 18356 // and reconcile again once they're scanned 18357 continue; 18358 } 18359 18360 if (ps.getInstalled(userId)) { 18361 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 18362 18363 if (maybeMigrateAppData(volumeUuid, userId, ps.pkg)) { 18364 // We may have just shuffled around app data directories, so 18365 // prepare them one more time 18366 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 18367 } 18368 18369 preparedCount++; 18370 } 18371 } 18372 18373 if (restoreconNeeded) { 18374 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18375 SELinuxMMAC.setRestoreconDone(ceDir); 18376 } 18377 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18378 SELinuxMMAC.setRestoreconDone(deDir); 18379 } 18380 } 18381 18382 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 18383 + " packages; restoreconNeeded was " + restoreconNeeded); 18384 } 18385 18386 /** 18387 * Prepare app data for the given app just after it was installed or 18388 * upgraded. This method carefully only touches users that it's installed 18389 * for, and it forces a restorecon to handle any seinfo changes. 18390 * <p> 18391 * Verifies that directories exist and that ownership and labeling is 18392 * correct for all installed apps. If there is an ownership mismatch, it 18393 * will try recovering system apps by wiping data; third-party app data is 18394 * left intact. 18395 * <p> 18396 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 18397 */ 18398 private void prepareAppDataAfterInstall(PackageParser.Package pkg) { 18399 prepareAppDataAfterInstallInternal(pkg); 18400 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 18401 for (int i = 0; i < childCount; i++) { 18402 PackageParser.Package childPackage = pkg.childPackages.get(i); 18403 prepareAppDataAfterInstallInternal(childPackage); 18404 } 18405 } 18406 18407 private void prepareAppDataAfterInstallInternal(PackageParser.Package pkg) { 18408 final PackageSetting ps; 18409 synchronized (mPackages) { 18410 ps = mSettings.mPackages.get(pkg.packageName); 18411 mSettings.writeKernelMappingLPr(ps); 18412 } 18413 18414 final UserManager um = mContext.getSystemService(UserManager.class); 18415 for (UserInfo user : um.getUsers()) { 18416 final int flags; 18417 if (um.isUserUnlocked(user.id)) { 18418 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18419 } else if (um.isUserRunning(user.id)) { 18420 flags = StorageManager.FLAG_STORAGE_DE; 18421 } else { 18422 continue; 18423 } 18424 18425 if (ps.getInstalled(user.id)) { 18426 // Whenever an app changes, force a restorecon of its data 18427 // TODO: when user data is locked, mark that we're still dirty 18428 prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true); 18429 } 18430 } 18431 } 18432 18433 /** 18434 * Prepare app data for the given app. 18435 * <p> 18436 * Verifies that directories exist and that ownership and labeling is 18437 * correct for all installed apps. If there is an ownership mismatch, this 18438 * will try recovering system apps by wiping data; third-party app data is 18439 * left intact. 18440 */ 18441 private void prepareAppData(String volumeUuid, int userId, int flags, 18442 PackageParser.Package pkg, boolean restoreconNeeded) { 18443 if (DEBUG_APP_DATA) { 18444 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 18445 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 18446 } 18447 18448 final String packageName = pkg.packageName; 18449 final ApplicationInfo app = pkg.applicationInfo; 18450 final int appId = UserHandle.getAppId(app.uid); 18451 18452 Preconditions.checkNotNull(app.seinfo); 18453 18454 synchronized (mInstallLock) { 18455 try { 18456 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18457 appId, app.seinfo, app.targetSdkVersion); 18458 } catch (InstallerException e) { 18459 if (app.isSystemApp()) { 18460 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 18461 + ", but trying to recover: " + e); 18462 destroyAppDataLI(volumeUuid, packageName, userId, flags); 18463 try { 18464 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18465 appId, app.seinfo, app.targetSdkVersion); 18466 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 18467 } catch (InstallerException e2) { 18468 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 18469 } 18470 } else { 18471 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 18472 } 18473 } 18474 18475 if (restoreconNeeded) { 18476 restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo); 18477 } 18478 18479 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18480 // Create a native library symlink only if we have native libraries 18481 // and if the native libraries are 32 bit libraries. We do not provide 18482 // this symlink for 64 bit libraries. 18483 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 18484 final String nativeLibPath = app.nativeLibraryDir; 18485 try { 18486 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 18487 nativeLibPath, userId); 18488 } catch (InstallerException e) { 18489 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 18490 } 18491 } 18492 } 18493 } 18494 } 18495 18496 /** 18497 * For system apps on non-FBE devices, this method migrates any existing 18498 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 18499 * requested by the app. 18500 */ 18501 private boolean maybeMigrateAppData(String volumeUuid, int userId, PackageParser.Package pkg) { 18502 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 18503 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 18504 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 18505 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 18506 synchronized (mInstallLock) { 18507 try { 18508 mInstaller.migrateAppData(volumeUuid, pkg.packageName, userId, storageTarget); 18509 } catch (InstallerException e) { 18510 logCriticalInfo(Log.WARN, 18511 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 18512 } 18513 } 18514 return true; 18515 } else { 18516 return false; 18517 } 18518 } 18519 18520 private void unfreezePackage(String packageName) { 18521 synchronized (mPackages) { 18522 final PackageSetting ps = mSettings.mPackages.get(packageName); 18523 if (ps != null) { 18524 ps.frozen = false; 18525 } 18526 } 18527 } 18528 18529 @Override 18530 public int movePackage(final String packageName, final String volumeUuid) { 18531 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 18532 18533 final int moveId = mNextMoveId.getAndIncrement(); 18534 mHandler.post(new Runnable() { 18535 @Override 18536 public void run() { 18537 try { 18538 movePackageInternal(packageName, volumeUuid, moveId); 18539 } catch (PackageManagerException e) { 18540 Slog.w(TAG, "Failed to move " + packageName, e); 18541 mMoveCallbacks.notifyStatusChanged(moveId, 18542 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 18543 } 18544 } 18545 }); 18546 return moveId; 18547 } 18548 18549 private void movePackageInternal(final String packageName, final String volumeUuid, 18550 final int moveId) throws PackageManagerException { 18551 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 18552 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18553 final PackageManager pm = mContext.getPackageManager(); 18554 18555 final boolean currentAsec; 18556 final String currentVolumeUuid; 18557 final File codeFile; 18558 final String installerPackageName; 18559 final String packageAbiOverride; 18560 final int appId; 18561 final String seinfo; 18562 final String label; 18563 final int targetSdkVersion; 18564 18565 // reader 18566 synchronized (mPackages) { 18567 final PackageParser.Package pkg = mPackages.get(packageName); 18568 final PackageSetting ps = mSettings.mPackages.get(packageName); 18569 if (pkg == null || ps == null) { 18570 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 18571 } 18572 18573 if (pkg.applicationInfo.isSystemApp()) { 18574 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 18575 "Cannot move system application"); 18576 } 18577 18578 if (pkg.applicationInfo.isExternalAsec()) { 18579 currentAsec = true; 18580 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 18581 } else if (pkg.applicationInfo.isForwardLocked()) { 18582 currentAsec = true; 18583 currentVolumeUuid = "forward_locked"; 18584 } else { 18585 currentAsec = false; 18586 currentVolumeUuid = ps.volumeUuid; 18587 18588 final File probe = new File(pkg.codePath); 18589 final File probeOat = new File(probe, "oat"); 18590 if (!probe.isDirectory() || !probeOat.isDirectory()) { 18591 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18592 "Move only supported for modern cluster style installs"); 18593 } 18594 } 18595 18596 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 18597 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18598 "Package already moved to " + volumeUuid); 18599 } 18600 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 18601 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 18602 "Device admin cannot be moved"); 18603 } 18604 18605 if (ps.frozen) { 18606 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 18607 "Failed to move already frozen package"); 18608 } 18609 ps.frozen = true; 18610 18611 codeFile = new File(pkg.codePath); 18612 installerPackageName = ps.installerPackageName; 18613 packageAbiOverride = ps.cpuAbiOverrideString; 18614 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18615 seinfo = pkg.applicationInfo.seinfo; 18616 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 18617 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 18618 } 18619 18620 // Now that we're guarded by frozen state, kill app during move 18621 final long token = Binder.clearCallingIdentity(); 18622 try { 18623 killApplication(packageName, appId, "move pkg"); 18624 } finally { 18625 Binder.restoreCallingIdentity(token); 18626 } 18627 18628 final Bundle extras = new Bundle(); 18629 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 18630 extras.putString(Intent.EXTRA_TITLE, label); 18631 mMoveCallbacks.notifyCreated(moveId, extras); 18632 18633 int installFlags; 18634 final boolean moveCompleteApp; 18635 final File measurePath; 18636 18637 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 18638 installFlags = INSTALL_INTERNAL; 18639 moveCompleteApp = !currentAsec; 18640 measurePath = Environment.getDataAppDirectory(volumeUuid); 18641 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 18642 installFlags = INSTALL_EXTERNAL; 18643 moveCompleteApp = false; 18644 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 18645 } else { 18646 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 18647 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 18648 || !volume.isMountedWritable()) { 18649 unfreezePackage(packageName); 18650 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18651 "Move location not mounted private volume"); 18652 } 18653 18654 Preconditions.checkState(!currentAsec); 18655 18656 installFlags = INSTALL_INTERNAL; 18657 moveCompleteApp = true; 18658 measurePath = Environment.getDataAppDirectory(volumeUuid); 18659 } 18660 18661 final PackageStats stats = new PackageStats(null, -1); 18662 synchronized (mInstaller) { 18663 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 18664 unfreezePackage(packageName); 18665 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18666 "Failed to measure package size"); 18667 } 18668 } 18669 18670 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 18671 + stats.dataSize); 18672 18673 final long startFreeBytes = measurePath.getFreeSpace(); 18674 final long sizeBytes; 18675 if (moveCompleteApp) { 18676 sizeBytes = stats.codeSize + stats.dataSize; 18677 } else { 18678 sizeBytes = stats.codeSize; 18679 } 18680 18681 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 18682 unfreezePackage(packageName); 18683 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18684 "Not enough free space to move"); 18685 } 18686 18687 mMoveCallbacks.notifyStatusChanged(moveId, 10); 18688 18689 final CountDownLatch installedLatch = new CountDownLatch(1); 18690 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 18691 @Override 18692 public void onUserActionRequired(Intent intent) throws RemoteException { 18693 throw new IllegalStateException(); 18694 } 18695 18696 @Override 18697 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 18698 Bundle extras) throws RemoteException { 18699 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 18700 + PackageManager.installStatusToString(returnCode, msg)); 18701 18702 installedLatch.countDown(); 18703 18704 // Regardless of success or failure of the move operation, 18705 // always unfreeze the package 18706 unfreezePackage(packageName); 18707 18708 final int status = PackageManager.installStatusToPublicStatus(returnCode); 18709 switch (status) { 18710 case PackageInstaller.STATUS_SUCCESS: 18711 mMoveCallbacks.notifyStatusChanged(moveId, 18712 PackageManager.MOVE_SUCCEEDED); 18713 break; 18714 case PackageInstaller.STATUS_FAILURE_STORAGE: 18715 mMoveCallbacks.notifyStatusChanged(moveId, 18716 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 18717 break; 18718 default: 18719 mMoveCallbacks.notifyStatusChanged(moveId, 18720 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 18721 break; 18722 } 18723 } 18724 }; 18725 18726 final MoveInfo move; 18727 if (moveCompleteApp) { 18728 // Kick off a thread to report progress estimates 18729 new Thread() { 18730 @Override 18731 public void run() { 18732 while (true) { 18733 try { 18734 if (installedLatch.await(1, TimeUnit.SECONDS)) { 18735 break; 18736 } 18737 } catch (InterruptedException ignored) { 18738 } 18739 18740 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 18741 final int progress = 10 + (int) MathUtils.constrain( 18742 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 18743 mMoveCallbacks.notifyStatusChanged(moveId, progress); 18744 } 18745 } 18746 }.start(); 18747 18748 final String dataAppName = codeFile.getName(); 18749 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 18750 dataAppName, appId, seinfo, targetSdkVersion); 18751 } else { 18752 move = null; 18753 } 18754 18755 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 18756 18757 final Message msg = mHandler.obtainMessage(INIT_COPY); 18758 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 18759 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 18760 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 18761 packageAbiOverride, null); 18762 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 18763 msg.obj = params; 18764 18765 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 18766 System.identityHashCode(msg.obj)); 18767 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 18768 System.identityHashCode(msg.obj)); 18769 18770 mHandler.sendMessage(msg); 18771 } 18772 18773 @Override 18774 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 18775 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 18776 18777 final int realMoveId = mNextMoveId.getAndIncrement(); 18778 final Bundle extras = new Bundle(); 18779 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 18780 mMoveCallbacks.notifyCreated(realMoveId, extras); 18781 18782 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 18783 @Override 18784 public void onCreated(int moveId, Bundle extras) { 18785 // Ignored 18786 } 18787 18788 @Override 18789 public void onStatusChanged(int moveId, int status, long estMillis) { 18790 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 18791 } 18792 }; 18793 18794 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18795 storage.setPrimaryStorageUuid(volumeUuid, callback); 18796 return realMoveId; 18797 } 18798 18799 @Override 18800 public int getMoveStatus(int moveId) { 18801 mContext.enforceCallingOrSelfPermission( 18802 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18803 return mMoveCallbacks.mLastStatus.get(moveId); 18804 } 18805 18806 @Override 18807 public void registerMoveCallback(IPackageMoveObserver callback) { 18808 mContext.enforceCallingOrSelfPermission( 18809 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18810 mMoveCallbacks.register(callback); 18811 } 18812 18813 @Override 18814 public void unregisterMoveCallback(IPackageMoveObserver callback) { 18815 mContext.enforceCallingOrSelfPermission( 18816 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18817 mMoveCallbacks.unregister(callback); 18818 } 18819 18820 @Override 18821 public boolean setInstallLocation(int loc) { 18822 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 18823 null); 18824 if (getInstallLocation() == loc) { 18825 return true; 18826 } 18827 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 18828 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 18829 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 18830 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 18831 return true; 18832 } 18833 return false; 18834 } 18835 18836 @Override 18837 public int getInstallLocation() { 18838 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 18839 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 18840 PackageHelper.APP_INSTALL_AUTO); 18841 } 18842 18843 /** Called by UserManagerService */ 18844 void cleanUpUser(UserManagerService userManager, int userHandle) { 18845 synchronized (mPackages) { 18846 mDirtyUsers.remove(userHandle); 18847 mUserNeedsBadging.delete(userHandle); 18848 mSettings.removeUserLPw(userHandle); 18849 mPendingBroadcasts.remove(userHandle); 18850 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 18851 } 18852 synchronized (mInstallLock) { 18853 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18854 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18855 final String volumeUuid = vol.getFsUuid(); 18856 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 18857 try { 18858 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 18859 } catch (InstallerException e) { 18860 Slog.w(TAG, "Failed to remove user data", e); 18861 } 18862 } 18863 synchronized (mPackages) { 18864 removeUnusedPackagesLILPw(userManager, userHandle); 18865 } 18866 } 18867 } 18868 18869 /** 18870 * We're removing userHandle and would like to remove any downloaded packages 18871 * that are no longer in use by any other user. 18872 * @param userHandle the user being removed 18873 */ 18874 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 18875 final boolean DEBUG_CLEAN_APKS = false; 18876 int [] users = userManager.getUserIds(); 18877 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 18878 while (psit.hasNext()) { 18879 PackageSetting ps = psit.next(); 18880 if (ps.pkg == null) { 18881 continue; 18882 } 18883 final String packageName = ps.pkg.packageName; 18884 // Skip over if system app 18885 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 18886 continue; 18887 } 18888 if (DEBUG_CLEAN_APKS) { 18889 Slog.i(TAG, "Checking package " + packageName); 18890 } 18891 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 18892 if (keep) { 18893 if (DEBUG_CLEAN_APKS) { 18894 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 18895 } 18896 } else { 18897 for (int i = 0; i < users.length; i++) { 18898 if (users[i] != userHandle && ps.getInstalled(users[i])) { 18899 keep = true; 18900 if (DEBUG_CLEAN_APKS) { 18901 Slog.i(TAG, " Keeping package " + packageName + " for user " 18902 + users[i]); 18903 } 18904 break; 18905 } 18906 } 18907 } 18908 if (!keep) { 18909 if (DEBUG_CLEAN_APKS) { 18910 Slog.i(TAG, " Removing package " + packageName); 18911 } 18912 mHandler.post(new Runnable() { 18913 public void run() { 18914 deletePackageX(packageName, userHandle, 0); 18915 } //end run 18916 }); 18917 } 18918 } 18919 } 18920 18921 /** Called by UserManagerService */ 18922 void createNewUser(int userHandle) { 18923 synchronized (mInstallLock) { 18924 try { 18925 mInstaller.createUserConfig(userHandle); 18926 } catch (InstallerException e) { 18927 Slog.w(TAG, "Failed to create user config", e); 18928 } 18929 mSettings.createNewUserLI(this, mInstaller, userHandle); 18930 } 18931 synchronized (mPackages) { 18932 applyFactoryDefaultBrowserLPw(userHandle); 18933 primeDomainVerificationsLPw(userHandle); 18934 } 18935 } 18936 18937 void newUserCreated(final int userHandle) { 18938 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 18939 // If permission review for legacy apps is required, we represent 18940 // dagerous permissions for such apps as always granted runtime 18941 // permissions to keep per user flag state whether review is needed. 18942 // Hence, if a new user is added we have to propagate dangerous 18943 // permission grants for these legacy apps. 18944 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 18945 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 18946 | UPDATE_PERMISSIONS_REPLACE_ALL); 18947 } 18948 } 18949 18950 @Override 18951 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 18952 mContext.enforceCallingOrSelfPermission( 18953 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 18954 "Only package verification agents can read the verifier device identity"); 18955 18956 synchronized (mPackages) { 18957 return mSettings.getVerifierDeviceIdentityLPw(); 18958 } 18959 } 18960 18961 @Override 18962 public void setPermissionEnforced(String permission, boolean enforced) { 18963 // TODO: Now that we no longer change GID for storage, this should to away. 18964 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 18965 "setPermissionEnforced"); 18966 if (READ_EXTERNAL_STORAGE.equals(permission)) { 18967 synchronized (mPackages) { 18968 if (mSettings.mReadExternalStorageEnforced == null 18969 || mSettings.mReadExternalStorageEnforced != enforced) { 18970 mSettings.mReadExternalStorageEnforced = enforced; 18971 mSettings.writeLPr(); 18972 } 18973 } 18974 // kill any non-foreground processes so we restart them and 18975 // grant/revoke the GID. 18976 final IActivityManager am = ActivityManagerNative.getDefault(); 18977 if (am != null) { 18978 final long token = Binder.clearCallingIdentity(); 18979 try { 18980 am.killProcessesBelowForeground("setPermissionEnforcement"); 18981 } catch (RemoteException e) { 18982 } finally { 18983 Binder.restoreCallingIdentity(token); 18984 } 18985 } 18986 } else { 18987 throw new IllegalArgumentException("No selective enforcement for " + permission); 18988 } 18989 } 18990 18991 @Override 18992 @Deprecated 18993 public boolean isPermissionEnforced(String permission) { 18994 return true; 18995 } 18996 18997 @Override 18998 public boolean isStorageLow() { 18999 final long token = Binder.clearCallingIdentity(); 19000 try { 19001 final DeviceStorageMonitorInternal 19002 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 19003 if (dsm != null) { 19004 return dsm.isMemoryLow(); 19005 } else { 19006 return false; 19007 } 19008 } finally { 19009 Binder.restoreCallingIdentity(token); 19010 } 19011 } 19012 19013 @Override 19014 public IPackageInstaller getPackageInstaller() { 19015 return mInstallerService; 19016 } 19017 19018 private boolean userNeedsBadging(int userId) { 19019 int index = mUserNeedsBadging.indexOfKey(userId); 19020 if (index < 0) { 19021 final UserInfo userInfo; 19022 final long token = Binder.clearCallingIdentity(); 19023 try { 19024 userInfo = sUserManager.getUserInfo(userId); 19025 } finally { 19026 Binder.restoreCallingIdentity(token); 19027 } 19028 final boolean b; 19029 if (userInfo != null && userInfo.isManagedProfile()) { 19030 b = true; 19031 } else { 19032 b = false; 19033 } 19034 mUserNeedsBadging.put(userId, b); 19035 return b; 19036 } 19037 return mUserNeedsBadging.valueAt(index); 19038 } 19039 19040 @Override 19041 public KeySet getKeySetByAlias(String packageName, String alias) { 19042 if (packageName == null || alias == null) { 19043 return null; 19044 } 19045 synchronized(mPackages) { 19046 final PackageParser.Package pkg = mPackages.get(packageName); 19047 if (pkg == null) { 19048 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19049 throw new IllegalArgumentException("Unknown package: " + packageName); 19050 } 19051 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19052 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 19053 } 19054 } 19055 19056 @Override 19057 public KeySet getSigningKeySet(String packageName) { 19058 if (packageName == null) { 19059 return null; 19060 } 19061 synchronized(mPackages) { 19062 final PackageParser.Package pkg = mPackages.get(packageName); 19063 if (pkg == null) { 19064 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19065 throw new IllegalArgumentException("Unknown package: " + packageName); 19066 } 19067 if (pkg.applicationInfo.uid != Binder.getCallingUid() 19068 && Process.SYSTEM_UID != Binder.getCallingUid()) { 19069 throw new SecurityException("May not access signing KeySet of other apps."); 19070 } 19071 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19072 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 19073 } 19074 } 19075 19076 @Override 19077 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 19078 if (packageName == null || ks == null) { 19079 return false; 19080 } 19081 synchronized(mPackages) { 19082 final PackageParser.Package pkg = mPackages.get(packageName); 19083 if (pkg == null) { 19084 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19085 throw new IllegalArgumentException("Unknown package: " + packageName); 19086 } 19087 IBinder ksh = ks.getToken(); 19088 if (ksh instanceof KeySetHandle) { 19089 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19090 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 19091 } 19092 return false; 19093 } 19094 } 19095 19096 @Override 19097 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 19098 if (packageName == null || ks == null) { 19099 return false; 19100 } 19101 synchronized(mPackages) { 19102 final PackageParser.Package pkg = mPackages.get(packageName); 19103 if (pkg == null) { 19104 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19105 throw new IllegalArgumentException("Unknown package: " + packageName); 19106 } 19107 IBinder ksh = ks.getToken(); 19108 if (ksh instanceof KeySetHandle) { 19109 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19110 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 19111 } 19112 return false; 19113 } 19114 } 19115 19116 private void deletePackageIfUnusedLPr(final String packageName) { 19117 PackageSetting ps = mSettings.mPackages.get(packageName); 19118 if (ps == null) { 19119 return; 19120 } 19121 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 19122 // TODO Implement atomic delete if package is unused 19123 // It is currently possible that the package will be deleted even if it is installed 19124 // after this method returns. 19125 mHandler.post(new Runnable() { 19126 public void run() { 19127 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 19128 } 19129 }); 19130 } 19131 } 19132 19133 /** 19134 * Check and throw if the given before/after packages would be considered a 19135 * downgrade. 19136 */ 19137 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 19138 throws PackageManagerException { 19139 if (after.versionCode < before.mVersionCode) { 19140 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19141 "Update version code " + after.versionCode + " is older than current " 19142 + before.mVersionCode); 19143 } else if (after.versionCode == before.mVersionCode) { 19144 if (after.baseRevisionCode < before.baseRevisionCode) { 19145 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19146 "Update base revision code " + after.baseRevisionCode 19147 + " is older than current " + before.baseRevisionCode); 19148 } 19149 19150 if (!ArrayUtils.isEmpty(after.splitNames)) { 19151 for (int i = 0; i < after.splitNames.length; i++) { 19152 final String splitName = after.splitNames[i]; 19153 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 19154 if (j != -1) { 19155 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 19156 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19157 "Update split " + splitName + " revision code " 19158 + after.splitRevisionCodes[i] + " is older than current " 19159 + before.splitRevisionCodes[j]); 19160 } 19161 } 19162 } 19163 } 19164 } 19165 } 19166 19167 private static class MoveCallbacks extends Handler { 19168 private static final int MSG_CREATED = 1; 19169 private static final int MSG_STATUS_CHANGED = 2; 19170 19171 private final RemoteCallbackList<IPackageMoveObserver> 19172 mCallbacks = new RemoteCallbackList<>(); 19173 19174 private final SparseIntArray mLastStatus = new SparseIntArray(); 19175 19176 public MoveCallbacks(Looper looper) { 19177 super(looper); 19178 } 19179 19180 public void register(IPackageMoveObserver callback) { 19181 mCallbacks.register(callback); 19182 } 19183 19184 public void unregister(IPackageMoveObserver callback) { 19185 mCallbacks.unregister(callback); 19186 } 19187 19188 @Override 19189 public void handleMessage(Message msg) { 19190 final SomeArgs args = (SomeArgs) msg.obj; 19191 final int n = mCallbacks.beginBroadcast(); 19192 for (int i = 0; i < n; i++) { 19193 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 19194 try { 19195 invokeCallback(callback, msg.what, args); 19196 } catch (RemoteException ignored) { 19197 } 19198 } 19199 mCallbacks.finishBroadcast(); 19200 args.recycle(); 19201 } 19202 19203 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 19204 throws RemoteException { 19205 switch (what) { 19206 case MSG_CREATED: { 19207 callback.onCreated(args.argi1, (Bundle) args.arg2); 19208 break; 19209 } 19210 case MSG_STATUS_CHANGED: { 19211 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 19212 break; 19213 } 19214 } 19215 } 19216 19217 private void notifyCreated(int moveId, Bundle extras) { 19218 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 19219 19220 final SomeArgs args = SomeArgs.obtain(); 19221 args.argi1 = moveId; 19222 args.arg2 = extras; 19223 obtainMessage(MSG_CREATED, args).sendToTarget(); 19224 } 19225 19226 private void notifyStatusChanged(int moveId, int status) { 19227 notifyStatusChanged(moveId, status, -1); 19228 } 19229 19230 private void notifyStatusChanged(int moveId, int status, long estMillis) { 19231 Slog.v(TAG, "Move " + moveId + " status " + status); 19232 19233 final SomeArgs args = SomeArgs.obtain(); 19234 args.argi1 = moveId; 19235 args.argi2 = status; 19236 args.arg3 = estMillis; 19237 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 19238 19239 synchronized (mLastStatus) { 19240 mLastStatus.put(moveId, status); 19241 } 19242 } 19243 } 19244 19245 private final static class OnPermissionChangeListeners extends Handler { 19246 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 19247 19248 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 19249 new RemoteCallbackList<>(); 19250 19251 public OnPermissionChangeListeners(Looper looper) { 19252 super(looper); 19253 } 19254 19255 @Override 19256 public void handleMessage(Message msg) { 19257 switch (msg.what) { 19258 case MSG_ON_PERMISSIONS_CHANGED: { 19259 final int uid = msg.arg1; 19260 handleOnPermissionsChanged(uid); 19261 } break; 19262 } 19263 } 19264 19265 public void addListenerLocked(IOnPermissionsChangeListener listener) { 19266 mPermissionListeners.register(listener); 19267 19268 } 19269 19270 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 19271 mPermissionListeners.unregister(listener); 19272 } 19273 19274 public void onPermissionsChanged(int uid) { 19275 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 19276 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 19277 } 19278 } 19279 19280 private void handleOnPermissionsChanged(int uid) { 19281 final int count = mPermissionListeners.beginBroadcast(); 19282 try { 19283 for (int i = 0; i < count; i++) { 19284 IOnPermissionsChangeListener callback = mPermissionListeners 19285 .getBroadcastItem(i); 19286 try { 19287 callback.onPermissionsChanged(uid); 19288 } catch (RemoteException e) { 19289 Log.e(TAG, "Permission listener is dead", e); 19290 } 19291 } 19292 } finally { 19293 mPermissionListeners.finishBroadcast(); 19294 } 19295 } 19296 } 19297 19298 private class PackageManagerInternalImpl extends PackageManagerInternal { 19299 @Override 19300 public void setLocationPackagesProvider(PackagesProvider provider) { 19301 synchronized (mPackages) { 19302 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 19303 } 19304 } 19305 19306 @Override 19307 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 19308 synchronized (mPackages) { 19309 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 19310 } 19311 } 19312 19313 @Override 19314 public void setSmsAppPackagesProvider(PackagesProvider provider) { 19315 synchronized (mPackages) { 19316 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 19317 } 19318 } 19319 19320 @Override 19321 public void setDialerAppPackagesProvider(PackagesProvider provider) { 19322 synchronized (mPackages) { 19323 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 19324 } 19325 } 19326 19327 @Override 19328 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 19329 synchronized (mPackages) { 19330 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 19331 } 19332 } 19333 19334 @Override 19335 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 19336 synchronized (mPackages) { 19337 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 19338 } 19339 } 19340 19341 @Override 19342 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 19343 synchronized (mPackages) { 19344 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 19345 packageName, userId); 19346 } 19347 } 19348 19349 @Override 19350 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 19351 synchronized (mPackages) { 19352 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 19353 packageName, userId); 19354 } 19355 } 19356 19357 @Override 19358 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 19359 synchronized (mPackages) { 19360 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 19361 packageName, userId); 19362 } 19363 } 19364 19365 @Override 19366 public void setKeepUninstalledPackages(final List<String> packageList) { 19367 Preconditions.checkNotNull(packageList); 19368 List<String> removedFromList = null; 19369 synchronized (mPackages) { 19370 if (mKeepUninstalledPackages != null) { 19371 final int packagesCount = mKeepUninstalledPackages.size(); 19372 for (int i = 0; i < packagesCount; i++) { 19373 String oldPackage = mKeepUninstalledPackages.get(i); 19374 if (packageList != null && packageList.contains(oldPackage)) { 19375 continue; 19376 } 19377 if (removedFromList == null) { 19378 removedFromList = new ArrayList<>(); 19379 } 19380 removedFromList.add(oldPackage); 19381 } 19382 } 19383 mKeepUninstalledPackages = new ArrayList<>(packageList); 19384 if (removedFromList != null) { 19385 final int removedCount = removedFromList.size(); 19386 for (int i = 0; i < removedCount; i++) { 19387 deletePackageIfUnusedLPr(removedFromList.get(i)); 19388 } 19389 } 19390 } 19391 } 19392 19393 @Override 19394 public boolean isPermissionsReviewRequired(String packageName, int userId) { 19395 synchronized (mPackages) { 19396 // If we do not support permission review, done. 19397 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 19398 return false; 19399 } 19400 19401 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 19402 if (packageSetting == null) { 19403 return false; 19404 } 19405 19406 // Permission review applies only to apps not supporting the new permission model. 19407 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 19408 return false; 19409 } 19410 19411 // Legacy apps have the permission and get user consent on launch. 19412 PermissionsState permissionsState = packageSetting.getPermissionsState(); 19413 return permissionsState.isPermissionReviewRequired(userId); 19414 } 19415 } 19416 19417 @Override 19418 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 19419 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 19420 } 19421 19422 @Override 19423 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 19424 int userId) { 19425 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 19426 } 19427 } 19428 19429 @Override 19430 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 19431 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 19432 synchronized (mPackages) { 19433 final long identity = Binder.clearCallingIdentity(); 19434 try { 19435 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 19436 packageNames, userId); 19437 } finally { 19438 Binder.restoreCallingIdentity(identity); 19439 } 19440 } 19441 } 19442 19443 private static void enforceSystemOrPhoneCaller(String tag) { 19444 int callingUid = Binder.getCallingUid(); 19445 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 19446 throw new SecurityException( 19447 "Cannot call " + tag + " from UID " + callingUid); 19448 } 19449 } 19450 19451 boolean isHistoricalPackageUsageAvailable() { 19452 return mPackageUsage.isHistoricalPackageUsageAvailable(); 19453 } 19454 19455 /** 19456 * Return a <b>copy</b> of the collection of packages known to the package manager. 19457 * @return A copy of the values of mPackages. 19458 */ 19459 Collection<PackageParser.Package> getPackages() { 19460 synchronized (mPackages) { 19461 return new ArrayList<>(mPackages.values()); 19462 } 19463 } 19464} 19465