PackageManagerService.java revision 0436b1d5a21a2f42d77992a4429f01601676d3e8
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 35import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 55import static android.content.pm.PackageManager.INSTALL_INTERNAL; 56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 62import static android.content.pm.PackageManager.MATCH_ALL; 63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 67import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 68import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 69import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 70import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 71import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 72import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 73import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 74import static android.content.pm.PackageManager.PERMISSION_DENIED; 75import static android.content.pm.PackageManager.PERMISSION_GRANTED; 76import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 77import static android.content.pm.PackageParser.isApkFile; 78import static android.os.Process.PACKAGE_INFO_GID; 79import static android.os.Process.SYSTEM_UID; 80import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 81import static android.system.OsConstants.O_CREAT; 82import static android.system.OsConstants.O_RDWR; 83 84import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 86import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 87import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 88import static com.android.internal.util.ArrayUtils.appendInt; 89import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 90import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 91import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 93import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 94import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 95import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 97import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 100 101import android.Manifest; 102import android.annotation.NonNull; 103import android.annotation.Nullable; 104import android.app.ActivityManager; 105import android.app.ActivityManagerNative; 106import android.app.IActivityManager; 107import android.app.admin.DevicePolicyManagerInternal; 108import android.app.admin.IDevicePolicyManager; 109import android.app.admin.SecurityLog; 110import android.app.backup.IBackupManager; 111import android.content.BroadcastReceiver; 112import android.content.ComponentName; 113import android.content.Context; 114import android.content.IIntentReceiver; 115import android.content.Intent; 116import android.content.IntentFilter; 117import android.content.IntentSender; 118import android.content.IntentSender.SendIntentException; 119import android.content.ServiceConnection; 120import android.content.pm.ActivityInfo; 121import android.content.pm.ApplicationInfo; 122import android.content.pm.AppsQueryHelper; 123import android.content.pm.ComponentInfo; 124import android.content.pm.EphemeralApplicationInfo; 125import android.content.pm.EphemeralResolveInfo; 126import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 127import android.content.pm.FeatureInfo; 128import android.content.pm.IOnPermissionsChangeListener; 129import android.content.pm.IPackageDataObserver; 130import android.content.pm.IPackageDeleteObserver; 131import android.content.pm.IPackageDeleteObserver2; 132import android.content.pm.IPackageInstallObserver2; 133import android.content.pm.IPackageInstaller; 134import android.content.pm.IPackageManager; 135import android.content.pm.IPackageMoveObserver; 136import android.content.pm.IPackageStatsObserver; 137import android.content.pm.InstrumentationInfo; 138import android.content.pm.IntentFilterVerificationInfo; 139import android.content.pm.KeySet; 140import android.content.pm.PackageCleanItem; 141import android.content.pm.PackageInfo; 142import android.content.pm.PackageInfoLite; 143import android.content.pm.PackageInstaller; 144import android.content.pm.PackageManager; 145import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 146import android.content.pm.PackageManagerInternal; 147import android.content.pm.PackageParser; 148import android.content.pm.PackageParser.ActivityIntentInfo; 149import android.content.pm.PackageParser.PackageLite; 150import android.content.pm.PackageParser.PackageParserException; 151import android.content.pm.PackageStats; 152import android.content.pm.PackageUserState; 153import android.content.pm.ParceledListSlice; 154import android.content.pm.PermissionGroupInfo; 155import android.content.pm.PermissionInfo; 156import android.content.pm.ProviderInfo; 157import android.content.pm.ResolveInfo; 158import android.content.pm.ServiceInfo; 159import android.content.pm.Signature; 160import android.content.pm.UserInfo; 161import android.content.pm.VerifierDeviceIdentity; 162import android.content.pm.VerifierInfo; 163import android.content.res.Resources; 164import android.graphics.Bitmap; 165import android.hardware.display.DisplayManager; 166import android.net.Uri; 167import android.os.Binder; 168import android.os.Build; 169import android.os.Bundle; 170import android.os.Debug; 171import android.os.Environment; 172import android.os.Environment.UserEnvironment; 173import android.os.FileUtils; 174import android.os.Handler; 175import android.os.IBinder; 176import android.os.Looper; 177import android.os.Message; 178import android.os.Parcel; 179import android.os.ParcelFileDescriptor; 180import android.os.Process; 181import android.os.RemoteCallbackList; 182import android.os.RemoteException; 183import android.os.ResultReceiver; 184import android.os.SELinux; 185import android.os.ServiceManager; 186import android.os.SystemClock; 187import android.os.SystemProperties; 188import android.os.Trace; 189import android.os.UserHandle; 190import android.os.UserManager; 191import android.os.storage.IMountService; 192import android.os.storage.MountServiceInternal; 193import android.os.storage.StorageEventListener; 194import android.os.storage.StorageManager; 195import android.os.storage.VolumeInfo; 196import android.os.storage.VolumeRecord; 197import android.security.KeyStore; 198import android.security.SystemKeyStore; 199import android.system.ErrnoException; 200import android.system.Os; 201import android.text.TextUtils; 202import android.text.format.DateUtils; 203import android.util.ArrayMap; 204import android.util.ArraySet; 205import android.util.AtomicFile; 206import android.util.DisplayMetrics; 207import android.util.EventLog; 208import android.util.ExceptionUtils; 209import android.util.Log; 210import android.util.LogPrinter; 211import android.util.MathUtils; 212import android.util.PrintStreamPrinter; 213import android.util.Slog; 214import android.util.SparseArray; 215import android.util.SparseBooleanArray; 216import android.util.SparseIntArray; 217import android.util.Xml; 218import android.view.Display; 219 220import com.android.internal.R; 221import com.android.internal.annotations.GuardedBy; 222import com.android.internal.app.IMediaContainerService; 223import com.android.internal.app.ResolverActivity; 224import com.android.internal.content.NativeLibraryHelper; 225import com.android.internal.content.PackageHelper; 226import com.android.internal.os.IParcelFileDescriptorFactory; 227import com.android.internal.os.InstallerConnection.InstallerException; 228import com.android.internal.os.SomeArgs; 229import com.android.internal.os.Zygote; 230import com.android.internal.util.ArrayUtils; 231import com.android.internal.util.FastPrintWriter; 232import com.android.internal.util.FastXmlSerializer; 233import com.android.internal.util.IndentingPrintWriter; 234import com.android.internal.util.Preconditions; 235import com.android.internal.util.XmlUtils; 236import com.android.server.EventLogTags; 237import com.android.server.FgThread; 238import com.android.server.IntentResolver; 239import com.android.server.LocalServices; 240import com.android.server.ServiceThread; 241import com.android.server.SystemConfig; 242import com.android.server.Watchdog; 243import com.android.server.pm.PermissionsState.PermissionState; 244import com.android.server.pm.Settings.DatabaseVersion; 245import com.android.server.pm.Settings.VersionInfo; 246import com.android.server.storage.DeviceStorageMonitorInternal; 247 248import dalvik.system.DexFile; 249import dalvik.system.VMRuntime; 250 251import libcore.io.IoUtils; 252import libcore.util.EmptyArray; 253 254import org.xmlpull.v1.XmlPullParser; 255import org.xmlpull.v1.XmlPullParserException; 256import org.xmlpull.v1.XmlSerializer; 257 258import java.io.BufferedInputStream; 259import java.io.BufferedOutputStream; 260import java.io.BufferedReader; 261import java.io.ByteArrayInputStream; 262import java.io.ByteArrayOutputStream; 263import java.io.File; 264import java.io.FileDescriptor; 265import java.io.FileNotFoundException; 266import java.io.FileOutputStream; 267import java.io.FileReader; 268import java.io.FilenameFilter; 269import java.io.IOException; 270import java.io.InputStream; 271import java.io.PrintWriter; 272import java.nio.charset.StandardCharsets; 273import java.security.MessageDigest; 274import java.security.NoSuchAlgorithmException; 275import java.security.PublicKey; 276import java.security.cert.CertificateEncodingException; 277import java.security.cert.CertificateException; 278import java.text.SimpleDateFormat; 279import java.util.ArrayList; 280import java.util.Arrays; 281import java.util.Collection; 282import java.util.Collections; 283import java.util.Comparator; 284import java.util.Date; 285import java.util.HashSet; 286import java.util.Iterator; 287import java.util.List; 288import java.util.Map; 289import java.util.Objects; 290import java.util.Set; 291import java.util.concurrent.CountDownLatch; 292import java.util.concurrent.TimeUnit; 293import java.util.concurrent.atomic.AtomicBoolean; 294import java.util.concurrent.atomic.AtomicInteger; 295import java.util.concurrent.atomic.AtomicLong; 296 297/** 298 * Keep track of all those .apks everywhere. 299 * 300 * This is very central to the platform's security; please run the unit 301 * tests whenever making modifications here: 302 * 303runtest -c android.content.pm.PackageManagerTests frameworks-core 304 * 305 * {@hide} 306 */ 307public class PackageManagerService extends IPackageManager.Stub { 308 static final String TAG = "PackageManager"; 309 static final boolean DEBUG_SETTINGS = false; 310 static final boolean DEBUG_PREFERRED = false; 311 static final boolean DEBUG_UPGRADE = false; 312 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 313 private static final boolean DEBUG_BACKUP = false; 314 private static final boolean DEBUG_INSTALL = false; 315 private static final boolean DEBUG_REMOVE = false; 316 private static final boolean DEBUG_BROADCASTS = false; 317 private static final boolean DEBUG_SHOW_INFO = false; 318 private static final boolean DEBUG_PACKAGE_INFO = false; 319 private static final boolean DEBUG_INTENT_MATCHING = false; 320 private static final boolean DEBUG_PACKAGE_SCANNING = false; 321 private static final boolean DEBUG_VERIFY = false; 322 323 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 324 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 325 // user, but by default initialize to this. 326 static final boolean DEBUG_DEXOPT = false; 327 328 private static final boolean DEBUG_ABI_SELECTION = false; 329 private static final boolean DEBUG_EPHEMERAL = false; 330 private static final boolean DEBUG_TRIAGED_MISSING = false; 331 private static final boolean DEBUG_APP_DATA = false; 332 333 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 334 335 private static final boolean DISABLE_EPHEMERAL_APPS = true; 336 337 private static final int RADIO_UID = Process.PHONE_UID; 338 private static final int LOG_UID = Process.LOG_UID; 339 private static final int NFC_UID = Process.NFC_UID; 340 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 341 private static final int SHELL_UID = Process.SHELL_UID; 342 343 // Cap the size of permission trees that 3rd party apps can define 344 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 345 346 // Suffix used during package installation when copying/moving 347 // package apks to install directory. 348 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 349 350 static final int SCAN_NO_DEX = 1<<1; 351 static final int SCAN_FORCE_DEX = 1<<2; 352 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 353 static final int SCAN_NEW_INSTALL = 1<<4; 354 static final int SCAN_NO_PATHS = 1<<5; 355 static final int SCAN_UPDATE_TIME = 1<<6; 356 static final int SCAN_DEFER_DEX = 1<<7; 357 static final int SCAN_BOOTING = 1<<8; 358 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 359 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 360 static final int SCAN_REPLACING = 1<<11; 361 static final int SCAN_REQUIRE_KNOWN = 1<<12; 362 static final int SCAN_MOVE = 1<<13; 363 static final int SCAN_INITIAL = 1<<14; 364 static final int SCAN_CHECK_ONLY = 1<<15; 365 static final int SCAN_DONT_KILL_APP = 1<<17; 366 367 static final int REMOVE_CHATTY = 1<<16; 368 369 private static final int[] EMPTY_INT_ARRAY = new int[0]; 370 371 /** 372 * Timeout (in milliseconds) after which the watchdog should declare that 373 * our handler thread is wedged. The usual default for such things is one 374 * minute but we sometimes do very lengthy I/O operations on this thread, 375 * such as installing multi-gigabyte applications, so ours needs to be longer. 376 */ 377 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 378 379 /** 380 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 381 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 382 * settings entry if available, otherwise we use the hardcoded default. If it's been 383 * more than this long since the last fstrim, we force one during the boot sequence. 384 * 385 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 386 * one gets run at the next available charging+idle time. This final mandatory 387 * no-fstrim check kicks in only of the other scheduling criteria is never met. 388 */ 389 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 390 391 /** 392 * Whether verification is enabled by default. 393 */ 394 private static final boolean DEFAULT_VERIFY_ENABLE = true; 395 396 /** 397 * The default maximum time to wait for the verification agent to return in 398 * milliseconds. 399 */ 400 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 401 402 /** 403 * The default response for package verification timeout. 404 * 405 * This can be either PackageManager.VERIFICATION_ALLOW or 406 * PackageManager.VERIFICATION_REJECT. 407 */ 408 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 409 410 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 411 412 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 413 DEFAULT_CONTAINER_PACKAGE, 414 "com.android.defcontainer.DefaultContainerService"); 415 416 private static final String KILL_APP_REASON_GIDS_CHANGED = 417 "permission grant or revoke changed gids"; 418 419 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 420 "permissions revoked"; 421 422 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 423 424 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 425 426 /** Permission grant: not grant the permission. */ 427 private static final int GRANT_DENIED = 1; 428 429 /** Permission grant: grant the permission as an install permission. */ 430 private static final int GRANT_INSTALL = 2; 431 432 /** Permission grant: grant the permission as a runtime one. */ 433 private static final int GRANT_RUNTIME = 3; 434 435 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 436 private static final int GRANT_UPGRADE = 4; 437 438 /** Canonical intent used to identify what counts as a "web browser" app */ 439 private static final Intent sBrowserIntent; 440 static { 441 sBrowserIntent = new Intent(); 442 sBrowserIntent.setAction(Intent.ACTION_VIEW); 443 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 444 sBrowserIntent.setData(Uri.parse("http:")); 445 } 446 447 // Compilation reasons. 448 public static final int REASON_FIRST_BOOT = 0; 449 public static final int REASON_BOOT = 1; 450 public static final int REASON_INSTALL = 2; 451 public static final int REASON_BACKGROUND_DEXOPT = 3; 452 public static final int REASON_AB_OTA = 4; 453 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 454 public static final int REASON_SHARED_APK = 6; 455 public static final int REASON_FORCED_DEXOPT = 7; 456 457 public static final int REASON_LAST = REASON_FORCED_DEXOPT; 458 459 final ServiceThread mHandlerThread; 460 461 final PackageHandler mHandler; 462 463 private final ProcessLoggingHandler mProcessLoggingHandler; 464 465 /** 466 * Messages for {@link #mHandler} that need to wait for system ready before 467 * being dispatched. 468 */ 469 private ArrayList<Message> mPostSystemReadyMessages; 470 471 final int mSdkVersion = Build.VERSION.SDK_INT; 472 473 final Context mContext; 474 final boolean mFactoryTest; 475 final boolean mOnlyCore; 476 final DisplayMetrics mMetrics; 477 final int mDefParseFlags; 478 final String[] mSeparateProcesses; 479 final boolean mIsUpgrade; 480 final boolean mIsPreNUpgrade; 481 482 /** The location for ASEC container files on internal storage. */ 483 final String mAsecInternalPath; 484 485 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 486 // LOCK HELD. Can be called with mInstallLock held. 487 @GuardedBy("mInstallLock") 488 final Installer mInstaller; 489 490 /** Directory where installed third-party apps stored */ 491 final File mAppInstallDir; 492 final File mEphemeralInstallDir; 493 494 /** 495 * Directory to which applications installed internally have their 496 * 32 bit native libraries copied. 497 */ 498 private File mAppLib32InstallDir; 499 500 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 501 // apps. 502 final File mDrmAppPrivateInstallDir; 503 504 // ---------------------------------------------------------------- 505 506 // Lock for state used when installing and doing other long running 507 // operations. Methods that must be called with this lock held have 508 // the suffix "LI". 509 final Object mInstallLock = new Object(); 510 511 // ---------------------------------------------------------------- 512 513 // Keys are String (package name), values are Package. This also serves 514 // as the lock for the global state. Methods that must be called with 515 // this lock held have the prefix "LP". 516 @GuardedBy("mPackages") 517 final ArrayMap<String, PackageParser.Package> mPackages = 518 new ArrayMap<String, PackageParser.Package>(); 519 520 final ArrayMap<String, Set<String>> mKnownCodebase = 521 new ArrayMap<String, Set<String>>(); 522 523 // Tracks available target package names -> overlay package paths. 524 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 525 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 526 527 /** 528 * Tracks new system packages [received in an OTA] that we expect to 529 * find updated user-installed versions. Keys are package name, values 530 * are package location. 531 */ 532 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 533 534 /** 535 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 536 */ 537 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 538 /** 539 * Whether or not system app permissions should be promoted from install to runtime. 540 */ 541 boolean mPromoteSystemApps; 542 543 final Settings mSettings; 544 boolean mRestoredSettings; 545 546 // System configuration read by SystemConfig. 547 final int[] mGlobalGids; 548 final SparseArray<ArraySet<String>> mSystemPermissions; 549 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 550 551 // If mac_permissions.xml was found for seinfo labeling. 552 boolean mFoundPolicyFile; 553 554 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 555 556 public static final class SharedLibraryEntry { 557 public final String path; 558 public final String apk; 559 560 SharedLibraryEntry(String _path, String _apk) { 561 path = _path; 562 apk = _apk; 563 } 564 } 565 566 // Currently known shared libraries. 567 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 568 new ArrayMap<String, SharedLibraryEntry>(); 569 570 // All available activities, for your resolving pleasure. 571 final ActivityIntentResolver mActivities = 572 new ActivityIntentResolver(); 573 574 // All available receivers, for your resolving pleasure. 575 final ActivityIntentResolver mReceivers = 576 new ActivityIntentResolver(); 577 578 // All available services, for your resolving pleasure. 579 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 580 581 // All available providers, for your resolving pleasure. 582 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 583 584 // Mapping from provider base names (first directory in content URI codePath) 585 // to the provider information. 586 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 587 new ArrayMap<String, PackageParser.Provider>(); 588 589 // Mapping from instrumentation class names to info about them. 590 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 591 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 592 593 // Mapping from permission names to info about them. 594 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 595 new ArrayMap<String, PackageParser.PermissionGroup>(); 596 597 // Packages whose data we have transfered into another package, thus 598 // should no longer exist. 599 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 600 601 // Broadcast actions that are only available to the system. 602 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 603 604 /** List of packages waiting for verification. */ 605 final SparseArray<PackageVerificationState> mPendingVerification 606 = new SparseArray<PackageVerificationState>(); 607 608 /** Set of packages associated with each app op permission. */ 609 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 610 611 final PackageInstallerService mInstallerService; 612 613 private final PackageDexOptimizer mPackageDexOptimizer; 614 615 private AtomicInteger mNextMoveId = new AtomicInteger(); 616 private final MoveCallbacks mMoveCallbacks; 617 618 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 619 620 // Cache of users who need badging. 621 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 622 623 /** Token for keys in mPendingVerification. */ 624 private int mPendingVerificationToken = 0; 625 626 volatile boolean mSystemReady; 627 volatile boolean mSafeMode; 628 volatile boolean mHasSystemUidErrors; 629 630 ApplicationInfo mAndroidApplication; 631 final ActivityInfo mResolveActivity = new ActivityInfo(); 632 final ResolveInfo mResolveInfo = new ResolveInfo(); 633 ComponentName mResolveComponentName; 634 PackageParser.Package mPlatformPackage; 635 ComponentName mCustomResolverComponentName; 636 637 boolean mResolverReplaced = false; 638 639 private final @Nullable ComponentName mIntentFilterVerifierComponent; 640 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 641 642 private int mIntentFilterVerificationToken = 0; 643 644 /** Component that knows whether or not an ephemeral application exists */ 645 final ComponentName mEphemeralResolverComponent; 646 /** The service connection to the ephemeral resolver */ 647 final EphemeralResolverConnection mEphemeralResolverConnection; 648 649 /** Component used to install ephemeral applications */ 650 final ComponentName mEphemeralInstallerComponent; 651 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 652 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 653 654 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 655 = new SparseArray<IntentFilterVerificationState>(); 656 657 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 658 new DefaultPermissionGrantPolicy(this); 659 660 // List of packages names to keep cached, even if they are uninstalled for all users 661 private List<String> mKeepUninstalledPackages; 662 663 private static class IFVerificationParams { 664 PackageParser.Package pkg; 665 boolean replacing; 666 int userId; 667 int verifierUid; 668 669 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 670 int _userId, int _verifierUid) { 671 pkg = _pkg; 672 replacing = _replacing; 673 userId = _userId; 674 replacing = _replacing; 675 verifierUid = _verifierUid; 676 } 677 } 678 679 private interface IntentFilterVerifier<T extends IntentFilter> { 680 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 681 T filter, String packageName); 682 void startVerifications(int userId); 683 void receiveVerificationResponse(int verificationId); 684 } 685 686 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 687 private Context mContext; 688 private ComponentName mIntentFilterVerifierComponent; 689 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 690 691 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 692 mContext = context; 693 mIntentFilterVerifierComponent = verifierComponent; 694 } 695 696 private String getDefaultScheme() { 697 return IntentFilter.SCHEME_HTTPS; 698 } 699 700 @Override 701 public void startVerifications(int userId) { 702 // Launch verifications requests 703 int count = mCurrentIntentFilterVerifications.size(); 704 for (int n=0; n<count; n++) { 705 int verificationId = mCurrentIntentFilterVerifications.get(n); 706 final IntentFilterVerificationState ivs = 707 mIntentFilterVerificationStates.get(verificationId); 708 709 String packageName = ivs.getPackageName(); 710 711 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 712 final int filterCount = filters.size(); 713 ArraySet<String> domainsSet = new ArraySet<>(); 714 for (int m=0; m<filterCount; m++) { 715 PackageParser.ActivityIntentInfo filter = filters.get(m); 716 domainsSet.addAll(filter.getHostsList()); 717 } 718 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 719 synchronized (mPackages) { 720 if (mSettings.createIntentFilterVerificationIfNeededLPw( 721 packageName, domainsList) != null) { 722 scheduleWriteSettingsLocked(); 723 } 724 } 725 sendVerificationRequest(userId, verificationId, ivs); 726 } 727 mCurrentIntentFilterVerifications.clear(); 728 } 729 730 private void sendVerificationRequest(int userId, int verificationId, 731 IntentFilterVerificationState ivs) { 732 733 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 734 verificationIntent.putExtra( 735 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 736 verificationId); 737 verificationIntent.putExtra( 738 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 739 getDefaultScheme()); 740 verificationIntent.putExtra( 741 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 742 ivs.getHostsString()); 743 verificationIntent.putExtra( 744 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 745 ivs.getPackageName()); 746 verificationIntent.setComponent(mIntentFilterVerifierComponent); 747 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 748 749 UserHandle user = new UserHandle(userId); 750 mContext.sendBroadcastAsUser(verificationIntent, user); 751 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 752 "Sending IntentFilter verification broadcast"); 753 } 754 755 public void receiveVerificationResponse(int verificationId) { 756 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 757 758 final boolean verified = ivs.isVerified(); 759 760 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 761 final int count = filters.size(); 762 if (DEBUG_DOMAIN_VERIFICATION) { 763 Slog.i(TAG, "Received verification response " + verificationId 764 + " for " + count + " filters, verified=" + verified); 765 } 766 for (int n=0; n<count; n++) { 767 PackageParser.ActivityIntentInfo filter = filters.get(n); 768 filter.setVerified(verified); 769 770 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 771 + " verified with result:" + verified + " and hosts:" 772 + ivs.getHostsString()); 773 } 774 775 mIntentFilterVerificationStates.remove(verificationId); 776 777 final String packageName = ivs.getPackageName(); 778 IntentFilterVerificationInfo ivi = null; 779 780 synchronized (mPackages) { 781 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 782 } 783 if (ivi == null) { 784 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 785 + verificationId + " packageName:" + packageName); 786 return; 787 } 788 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 789 "Updating IntentFilterVerificationInfo for package " + packageName 790 +" verificationId:" + verificationId); 791 792 synchronized (mPackages) { 793 if (verified) { 794 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 795 } else { 796 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 797 } 798 scheduleWriteSettingsLocked(); 799 800 final int userId = ivs.getUserId(); 801 if (userId != UserHandle.USER_ALL) { 802 final int userStatus = 803 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 804 805 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 806 boolean needUpdate = false; 807 808 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 809 // already been set by the User thru the Disambiguation dialog 810 switch (userStatus) { 811 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 812 if (verified) { 813 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 814 } else { 815 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 816 } 817 needUpdate = true; 818 break; 819 820 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 821 if (verified) { 822 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 823 needUpdate = true; 824 } 825 break; 826 827 default: 828 // Nothing to do 829 } 830 831 if (needUpdate) { 832 mSettings.updateIntentFilterVerificationStatusLPw( 833 packageName, updatedStatus, userId); 834 scheduleWritePackageRestrictionsLocked(userId); 835 } 836 } 837 } 838 } 839 840 @Override 841 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 842 ActivityIntentInfo filter, String packageName) { 843 if (!hasValidDomains(filter)) { 844 return false; 845 } 846 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 847 if (ivs == null) { 848 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 849 packageName); 850 } 851 if (DEBUG_DOMAIN_VERIFICATION) { 852 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 853 } 854 ivs.addFilter(filter); 855 return true; 856 } 857 858 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 859 int userId, int verificationId, String packageName) { 860 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 861 verifierUid, userId, packageName); 862 ivs.setPendingState(); 863 synchronized (mPackages) { 864 mIntentFilterVerificationStates.append(verificationId, ivs); 865 mCurrentIntentFilterVerifications.add(verificationId); 866 } 867 return ivs; 868 } 869 } 870 871 private static boolean hasValidDomains(ActivityIntentInfo filter) { 872 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 873 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 874 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 875 } 876 877 // Set of pending broadcasts for aggregating enable/disable of components. 878 static class PendingPackageBroadcasts { 879 // for each user id, a map of <package name -> components within that package> 880 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 881 882 public PendingPackageBroadcasts() { 883 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 884 } 885 886 public ArrayList<String> get(int userId, String packageName) { 887 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 888 return packages.get(packageName); 889 } 890 891 public void put(int userId, String packageName, ArrayList<String> components) { 892 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 893 packages.put(packageName, components); 894 } 895 896 public void remove(int userId, String packageName) { 897 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 898 if (packages != null) { 899 packages.remove(packageName); 900 } 901 } 902 903 public void remove(int userId) { 904 mUidMap.remove(userId); 905 } 906 907 public int userIdCount() { 908 return mUidMap.size(); 909 } 910 911 public int userIdAt(int n) { 912 return mUidMap.keyAt(n); 913 } 914 915 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 916 return mUidMap.get(userId); 917 } 918 919 public int size() { 920 // total number of pending broadcast entries across all userIds 921 int num = 0; 922 for (int i = 0; i< mUidMap.size(); i++) { 923 num += mUidMap.valueAt(i).size(); 924 } 925 return num; 926 } 927 928 public void clear() { 929 mUidMap.clear(); 930 } 931 932 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 933 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 934 if (map == null) { 935 map = new ArrayMap<String, ArrayList<String>>(); 936 mUidMap.put(userId, map); 937 } 938 return map; 939 } 940 } 941 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 942 943 // Service Connection to remote media container service to copy 944 // package uri's from external media onto secure containers 945 // or internal storage. 946 private IMediaContainerService mContainerService = null; 947 948 static final int SEND_PENDING_BROADCAST = 1; 949 static final int MCS_BOUND = 3; 950 static final int END_COPY = 4; 951 static final int INIT_COPY = 5; 952 static final int MCS_UNBIND = 6; 953 static final int START_CLEANING_PACKAGE = 7; 954 static final int FIND_INSTALL_LOC = 8; 955 static final int POST_INSTALL = 9; 956 static final int MCS_RECONNECT = 10; 957 static final int MCS_GIVE_UP = 11; 958 static final int UPDATED_MEDIA_STATUS = 12; 959 static final int WRITE_SETTINGS = 13; 960 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 961 static final int PACKAGE_VERIFIED = 15; 962 static final int CHECK_PENDING_VERIFICATION = 16; 963 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 964 static final int INTENT_FILTER_VERIFIED = 18; 965 966 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 967 968 // Delay time in millisecs 969 static final int BROADCAST_DELAY = 10 * 1000; 970 971 static UserManagerService sUserManager; 972 973 // Stores a list of users whose package restrictions file needs to be updated 974 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 975 976 final private DefaultContainerConnection mDefContainerConn = 977 new DefaultContainerConnection(); 978 class DefaultContainerConnection implements ServiceConnection { 979 public void onServiceConnected(ComponentName name, IBinder service) { 980 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 981 IMediaContainerService imcs = 982 IMediaContainerService.Stub.asInterface(service); 983 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 984 } 985 986 public void onServiceDisconnected(ComponentName name) { 987 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 988 } 989 } 990 991 // Recordkeeping of restore-after-install operations that are currently in flight 992 // between the Package Manager and the Backup Manager 993 static class PostInstallData { 994 public InstallArgs args; 995 public PackageInstalledInfo res; 996 997 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 998 args = _a; 999 res = _r; 1000 } 1001 } 1002 1003 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1004 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1005 1006 // XML tags for backup/restore of various bits of state 1007 private static final String TAG_PREFERRED_BACKUP = "pa"; 1008 private static final String TAG_DEFAULT_APPS = "da"; 1009 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1010 1011 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1012 private static final String TAG_ALL_GRANTS = "rt-grants"; 1013 private static final String TAG_GRANT = "grant"; 1014 private static final String ATTR_PACKAGE_NAME = "pkg"; 1015 1016 private static final String TAG_PERMISSION = "perm"; 1017 private static final String ATTR_PERMISSION_NAME = "name"; 1018 private static final String ATTR_IS_GRANTED = "g"; 1019 private static final String ATTR_USER_SET = "set"; 1020 private static final String ATTR_USER_FIXED = "fixed"; 1021 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1022 1023 // System/policy permission grants are not backed up 1024 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1025 FLAG_PERMISSION_POLICY_FIXED 1026 | FLAG_PERMISSION_SYSTEM_FIXED 1027 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1028 1029 // And we back up these user-adjusted states 1030 private static final int USER_RUNTIME_GRANT_MASK = 1031 FLAG_PERMISSION_USER_SET 1032 | FLAG_PERMISSION_USER_FIXED 1033 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1034 1035 final @Nullable String mRequiredVerifierPackage; 1036 final @Nullable String mRequiredInstallerPackage; 1037 1038 private final PackageUsage mPackageUsage = new PackageUsage(); 1039 1040 private class PackageUsage { 1041 private static final int WRITE_INTERVAL 1042 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1043 1044 private final Object mFileLock = new Object(); 1045 private final AtomicLong mLastWritten = new AtomicLong(0); 1046 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1047 1048 private boolean mIsHistoricalPackageUsageAvailable = true; 1049 1050 boolean isHistoricalPackageUsageAvailable() { 1051 return mIsHistoricalPackageUsageAvailable; 1052 } 1053 1054 void write(boolean force) { 1055 if (force) { 1056 writeInternal(); 1057 return; 1058 } 1059 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1060 && !DEBUG_DEXOPT) { 1061 return; 1062 } 1063 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1064 new Thread("PackageUsage_DiskWriter") { 1065 @Override 1066 public void run() { 1067 try { 1068 writeInternal(); 1069 } finally { 1070 mBackgroundWriteRunning.set(false); 1071 } 1072 } 1073 }.start(); 1074 } 1075 } 1076 1077 private void writeInternal() { 1078 synchronized (mPackages) { 1079 synchronized (mFileLock) { 1080 AtomicFile file = getFile(); 1081 FileOutputStream f = null; 1082 try { 1083 f = file.startWrite(); 1084 BufferedOutputStream out = new BufferedOutputStream(f); 1085 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1086 StringBuilder sb = new StringBuilder(); 1087 for (PackageParser.Package pkg : mPackages.values()) { 1088 if (pkg.mLastPackageUsageTimeInMills == 0) { 1089 continue; 1090 } 1091 sb.setLength(0); 1092 sb.append(pkg.packageName); 1093 sb.append(' '); 1094 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1095 sb.append('\n'); 1096 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1097 } 1098 out.flush(); 1099 file.finishWrite(f); 1100 } catch (IOException e) { 1101 if (f != null) { 1102 file.failWrite(f); 1103 } 1104 Log.e(TAG, "Failed to write package usage times", e); 1105 } 1106 } 1107 } 1108 mLastWritten.set(SystemClock.elapsedRealtime()); 1109 } 1110 1111 void readLP() { 1112 synchronized (mFileLock) { 1113 AtomicFile file = getFile(); 1114 BufferedInputStream in = null; 1115 try { 1116 in = new BufferedInputStream(file.openRead()); 1117 StringBuffer sb = new StringBuffer(); 1118 while (true) { 1119 String packageName = readToken(in, sb, ' '); 1120 if (packageName == null) { 1121 break; 1122 } 1123 String timeInMillisString = readToken(in, sb, '\n'); 1124 if (timeInMillisString == null) { 1125 throw new IOException("Failed to find last usage time for package " 1126 + packageName); 1127 } 1128 PackageParser.Package pkg = mPackages.get(packageName); 1129 if (pkg == null) { 1130 continue; 1131 } 1132 long timeInMillis; 1133 try { 1134 timeInMillis = Long.parseLong(timeInMillisString); 1135 } catch (NumberFormatException e) { 1136 throw new IOException("Failed to parse " + timeInMillisString 1137 + " as a long.", e); 1138 } 1139 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1140 } 1141 } catch (FileNotFoundException expected) { 1142 mIsHistoricalPackageUsageAvailable = false; 1143 } catch (IOException e) { 1144 Log.w(TAG, "Failed to read package usage times", e); 1145 } finally { 1146 IoUtils.closeQuietly(in); 1147 } 1148 } 1149 mLastWritten.set(SystemClock.elapsedRealtime()); 1150 } 1151 1152 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1153 throws IOException { 1154 sb.setLength(0); 1155 while (true) { 1156 int ch = in.read(); 1157 if (ch == -1) { 1158 if (sb.length() == 0) { 1159 return null; 1160 } 1161 throw new IOException("Unexpected EOF"); 1162 } 1163 if (ch == endOfToken) { 1164 return sb.toString(); 1165 } 1166 sb.append((char)ch); 1167 } 1168 } 1169 1170 private AtomicFile getFile() { 1171 File dataDir = Environment.getDataDirectory(); 1172 File systemDir = new File(dataDir, "system"); 1173 File fname = new File(systemDir, "package-usage.list"); 1174 return new AtomicFile(fname); 1175 } 1176 } 1177 1178 class PackageHandler extends Handler { 1179 private boolean mBound = false; 1180 final ArrayList<HandlerParams> mPendingInstalls = 1181 new ArrayList<HandlerParams>(); 1182 1183 private boolean connectToService() { 1184 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1185 " DefaultContainerService"); 1186 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1187 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1188 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1189 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1190 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1191 mBound = true; 1192 return true; 1193 } 1194 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1195 return false; 1196 } 1197 1198 private void disconnectService() { 1199 mContainerService = null; 1200 mBound = false; 1201 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1202 mContext.unbindService(mDefContainerConn); 1203 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1204 } 1205 1206 PackageHandler(Looper looper) { 1207 super(looper); 1208 } 1209 1210 public void handleMessage(Message msg) { 1211 try { 1212 doHandleMessage(msg); 1213 } finally { 1214 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1215 } 1216 } 1217 1218 void doHandleMessage(Message msg) { 1219 switch (msg.what) { 1220 case INIT_COPY: { 1221 HandlerParams params = (HandlerParams) msg.obj; 1222 int idx = mPendingInstalls.size(); 1223 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1224 // If a bind was already initiated we dont really 1225 // need to do anything. The pending install 1226 // will be processed later on. 1227 if (!mBound) { 1228 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1229 System.identityHashCode(mHandler)); 1230 // If this is the only one pending we might 1231 // have to bind to the service again. 1232 if (!connectToService()) { 1233 Slog.e(TAG, "Failed to bind to media container service"); 1234 params.serviceError(); 1235 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1236 System.identityHashCode(mHandler)); 1237 if (params.traceMethod != null) { 1238 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1239 params.traceCookie); 1240 } 1241 return; 1242 } else { 1243 // Once we bind to the service, the first 1244 // pending request will be processed. 1245 mPendingInstalls.add(idx, params); 1246 } 1247 } else { 1248 mPendingInstalls.add(idx, params); 1249 // Already bound to the service. Just make 1250 // sure we trigger off processing the first request. 1251 if (idx == 0) { 1252 mHandler.sendEmptyMessage(MCS_BOUND); 1253 } 1254 } 1255 break; 1256 } 1257 case MCS_BOUND: { 1258 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1259 if (msg.obj != null) { 1260 mContainerService = (IMediaContainerService) msg.obj; 1261 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1262 System.identityHashCode(mHandler)); 1263 } 1264 if (mContainerService == null) { 1265 if (!mBound) { 1266 // Something seriously wrong since we are not bound and we are not 1267 // waiting for connection. Bail out. 1268 Slog.e(TAG, "Cannot bind to media container service"); 1269 for (HandlerParams params : mPendingInstalls) { 1270 // Indicate service bind error 1271 params.serviceError(); 1272 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1273 System.identityHashCode(params)); 1274 if (params.traceMethod != null) { 1275 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1276 params.traceMethod, params.traceCookie); 1277 } 1278 return; 1279 } 1280 mPendingInstalls.clear(); 1281 } else { 1282 Slog.w(TAG, "Waiting to connect to media container service"); 1283 } 1284 } else if (mPendingInstalls.size() > 0) { 1285 HandlerParams params = mPendingInstalls.get(0); 1286 if (params != null) { 1287 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1288 System.identityHashCode(params)); 1289 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1290 if (params.startCopy()) { 1291 // We are done... look for more work or to 1292 // go idle. 1293 if (DEBUG_SD_INSTALL) Log.i(TAG, 1294 "Checking for more work or unbind..."); 1295 // Delete pending install 1296 if (mPendingInstalls.size() > 0) { 1297 mPendingInstalls.remove(0); 1298 } 1299 if (mPendingInstalls.size() == 0) { 1300 if (mBound) { 1301 if (DEBUG_SD_INSTALL) Log.i(TAG, 1302 "Posting delayed MCS_UNBIND"); 1303 removeMessages(MCS_UNBIND); 1304 Message ubmsg = obtainMessage(MCS_UNBIND); 1305 // Unbind after a little delay, to avoid 1306 // continual thrashing. 1307 sendMessageDelayed(ubmsg, 10000); 1308 } 1309 } else { 1310 // There are more pending requests in queue. 1311 // Just post MCS_BOUND message to trigger processing 1312 // of next pending install. 1313 if (DEBUG_SD_INSTALL) Log.i(TAG, 1314 "Posting MCS_BOUND for next work"); 1315 mHandler.sendEmptyMessage(MCS_BOUND); 1316 } 1317 } 1318 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1319 } 1320 } else { 1321 // Should never happen ideally. 1322 Slog.w(TAG, "Empty queue"); 1323 } 1324 break; 1325 } 1326 case MCS_RECONNECT: { 1327 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1328 if (mPendingInstalls.size() > 0) { 1329 if (mBound) { 1330 disconnectService(); 1331 } 1332 if (!connectToService()) { 1333 Slog.e(TAG, "Failed to bind to media container service"); 1334 for (HandlerParams params : mPendingInstalls) { 1335 // Indicate service bind error 1336 params.serviceError(); 1337 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1338 System.identityHashCode(params)); 1339 } 1340 mPendingInstalls.clear(); 1341 } 1342 } 1343 break; 1344 } 1345 case MCS_UNBIND: { 1346 // If there is no actual work left, then time to unbind. 1347 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1348 1349 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1350 if (mBound) { 1351 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1352 1353 disconnectService(); 1354 } 1355 } else if (mPendingInstalls.size() > 0) { 1356 // There are more pending requests in queue. 1357 // Just post MCS_BOUND message to trigger processing 1358 // of next pending install. 1359 mHandler.sendEmptyMessage(MCS_BOUND); 1360 } 1361 1362 break; 1363 } 1364 case MCS_GIVE_UP: { 1365 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1366 HandlerParams params = mPendingInstalls.remove(0); 1367 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1368 System.identityHashCode(params)); 1369 break; 1370 } 1371 case SEND_PENDING_BROADCAST: { 1372 String packages[]; 1373 ArrayList<String> components[]; 1374 int size = 0; 1375 int uids[]; 1376 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1377 synchronized (mPackages) { 1378 if (mPendingBroadcasts == null) { 1379 return; 1380 } 1381 size = mPendingBroadcasts.size(); 1382 if (size <= 0) { 1383 // Nothing to be done. Just return 1384 return; 1385 } 1386 packages = new String[size]; 1387 components = new ArrayList[size]; 1388 uids = new int[size]; 1389 int i = 0; // filling out the above arrays 1390 1391 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1392 int packageUserId = mPendingBroadcasts.userIdAt(n); 1393 Iterator<Map.Entry<String, ArrayList<String>>> it 1394 = mPendingBroadcasts.packagesForUserId(packageUserId) 1395 .entrySet().iterator(); 1396 while (it.hasNext() && i < size) { 1397 Map.Entry<String, ArrayList<String>> ent = it.next(); 1398 packages[i] = ent.getKey(); 1399 components[i] = ent.getValue(); 1400 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1401 uids[i] = (ps != null) 1402 ? UserHandle.getUid(packageUserId, ps.appId) 1403 : -1; 1404 i++; 1405 } 1406 } 1407 size = i; 1408 mPendingBroadcasts.clear(); 1409 } 1410 // Send broadcasts 1411 for (int i = 0; i < size; i++) { 1412 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1413 } 1414 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1415 break; 1416 } 1417 case START_CLEANING_PACKAGE: { 1418 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1419 final String packageName = (String)msg.obj; 1420 final int userId = msg.arg1; 1421 final boolean andCode = msg.arg2 != 0; 1422 synchronized (mPackages) { 1423 if (userId == UserHandle.USER_ALL) { 1424 int[] users = sUserManager.getUserIds(); 1425 for (int user : users) { 1426 mSettings.addPackageToCleanLPw( 1427 new PackageCleanItem(user, packageName, andCode)); 1428 } 1429 } else { 1430 mSettings.addPackageToCleanLPw( 1431 new PackageCleanItem(userId, packageName, andCode)); 1432 } 1433 } 1434 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1435 startCleaningPackages(); 1436 } break; 1437 case POST_INSTALL: { 1438 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1439 1440 PostInstallData data = mRunningInstalls.get(msg.arg1); 1441 mRunningInstalls.delete(msg.arg1); 1442 1443 if (data != null) { 1444 InstallArgs args = data.args; 1445 PackageInstalledInfo parentRes = data.res; 1446 1447 final boolean grantPermissions = (args.installFlags 1448 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1449 final boolean killApp = (args.installFlags 1450 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1451 final String[] grantedPermissions = args.installGrantPermissions; 1452 1453 // Handle the parent package 1454 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1455 grantedPermissions, args.observer); 1456 1457 // Handle the child packages 1458 final int childCount = (parentRes.addedChildPackages != null) 1459 ? parentRes.addedChildPackages.size() : 0; 1460 for (int i = 0; i < childCount; i++) { 1461 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1462 handlePackagePostInstall(childRes, grantPermissions, killApp, 1463 grantedPermissions, args.observer); 1464 } 1465 1466 // Log tracing if needed 1467 if (args.traceMethod != null) { 1468 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1469 args.traceCookie); 1470 } 1471 } else { 1472 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1473 } 1474 1475 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1476 } break; 1477 case UPDATED_MEDIA_STATUS: { 1478 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1479 boolean reportStatus = msg.arg1 == 1; 1480 boolean doGc = msg.arg2 == 1; 1481 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1482 if (doGc) { 1483 // Force a gc to clear up stale containers. 1484 Runtime.getRuntime().gc(); 1485 } 1486 if (msg.obj != null) { 1487 @SuppressWarnings("unchecked") 1488 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1489 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1490 // Unload containers 1491 unloadAllContainers(args); 1492 } 1493 if (reportStatus) { 1494 try { 1495 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1496 PackageHelper.getMountService().finishMediaUpdate(); 1497 } catch (RemoteException e) { 1498 Log.e(TAG, "MountService not running?"); 1499 } 1500 } 1501 } break; 1502 case WRITE_SETTINGS: { 1503 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1504 synchronized (mPackages) { 1505 removeMessages(WRITE_SETTINGS); 1506 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1507 mSettings.writeLPr(); 1508 mDirtyUsers.clear(); 1509 } 1510 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1511 } break; 1512 case WRITE_PACKAGE_RESTRICTIONS: { 1513 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1514 synchronized (mPackages) { 1515 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1516 for (int userId : mDirtyUsers) { 1517 mSettings.writePackageRestrictionsLPr(userId); 1518 } 1519 mDirtyUsers.clear(); 1520 } 1521 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1522 } break; 1523 case CHECK_PENDING_VERIFICATION: { 1524 final int verificationId = msg.arg1; 1525 final PackageVerificationState state = mPendingVerification.get(verificationId); 1526 1527 if ((state != null) && !state.timeoutExtended()) { 1528 final InstallArgs args = state.getInstallArgs(); 1529 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1530 1531 Slog.i(TAG, "Verification timed out for " + originUri); 1532 mPendingVerification.remove(verificationId); 1533 1534 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1535 1536 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1537 Slog.i(TAG, "Continuing with installation of " + originUri); 1538 state.setVerifierResponse(Binder.getCallingUid(), 1539 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1540 broadcastPackageVerified(verificationId, originUri, 1541 PackageManager.VERIFICATION_ALLOW, 1542 state.getInstallArgs().getUser()); 1543 try { 1544 ret = args.copyApk(mContainerService, true); 1545 } catch (RemoteException e) { 1546 Slog.e(TAG, "Could not contact the ContainerService"); 1547 } 1548 } else { 1549 broadcastPackageVerified(verificationId, originUri, 1550 PackageManager.VERIFICATION_REJECT, 1551 state.getInstallArgs().getUser()); 1552 } 1553 1554 Trace.asyncTraceEnd( 1555 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1556 1557 processPendingInstall(args, ret); 1558 mHandler.sendEmptyMessage(MCS_UNBIND); 1559 } 1560 break; 1561 } 1562 case PACKAGE_VERIFIED: { 1563 final int verificationId = msg.arg1; 1564 1565 final PackageVerificationState state = mPendingVerification.get(verificationId); 1566 if (state == null) { 1567 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1568 break; 1569 } 1570 1571 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1572 1573 state.setVerifierResponse(response.callerUid, response.code); 1574 1575 if (state.isVerificationComplete()) { 1576 mPendingVerification.remove(verificationId); 1577 1578 final InstallArgs args = state.getInstallArgs(); 1579 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1580 1581 int ret; 1582 if (state.isInstallAllowed()) { 1583 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1584 broadcastPackageVerified(verificationId, originUri, 1585 response.code, state.getInstallArgs().getUser()); 1586 try { 1587 ret = args.copyApk(mContainerService, true); 1588 } catch (RemoteException e) { 1589 Slog.e(TAG, "Could not contact the ContainerService"); 1590 } 1591 } else { 1592 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1593 } 1594 1595 Trace.asyncTraceEnd( 1596 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1597 1598 processPendingInstall(args, ret); 1599 mHandler.sendEmptyMessage(MCS_UNBIND); 1600 } 1601 1602 break; 1603 } 1604 case START_INTENT_FILTER_VERIFICATIONS: { 1605 IFVerificationParams params = (IFVerificationParams) msg.obj; 1606 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1607 params.replacing, params.pkg); 1608 break; 1609 } 1610 case INTENT_FILTER_VERIFIED: { 1611 final int verificationId = msg.arg1; 1612 1613 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1614 verificationId); 1615 if (state == null) { 1616 Slog.w(TAG, "Invalid IntentFilter verification token " 1617 + verificationId + " received"); 1618 break; 1619 } 1620 1621 final int userId = state.getUserId(); 1622 1623 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1624 "Processing IntentFilter verification with token:" 1625 + verificationId + " and userId:" + userId); 1626 1627 final IntentFilterVerificationResponse response = 1628 (IntentFilterVerificationResponse) msg.obj; 1629 1630 state.setVerifierResponse(response.callerUid, response.code); 1631 1632 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1633 "IntentFilter verification with token:" + verificationId 1634 + " and userId:" + userId 1635 + " is settings verifier response with response code:" 1636 + response.code); 1637 1638 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1639 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1640 + response.getFailedDomainsString()); 1641 } 1642 1643 if (state.isVerificationComplete()) { 1644 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1645 } else { 1646 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1647 "IntentFilter verification with token:" + verificationId 1648 + " was not said to be complete"); 1649 } 1650 1651 break; 1652 } 1653 } 1654 } 1655 } 1656 1657 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1658 boolean killApp, String[] grantedPermissions, 1659 IPackageInstallObserver2 installObserver) { 1660 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1661 // Send the removed broadcasts 1662 if (res.removedInfo != null) { 1663 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1664 } 1665 1666 // Now that we successfully installed the package, grant runtime 1667 // permissions if requested before broadcasting the install. 1668 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1669 >= Build.VERSION_CODES.M) { 1670 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1671 } 1672 1673 final boolean update = res.removedInfo != null 1674 && res.removedInfo.removedPackage != null; 1675 1676 // If this is the first time we have child packages for a disabled privileged 1677 // app that had no children, we grant requested runtime permissions to the new 1678 // children if the parent on the system image had them already granted. 1679 if (res.pkg.parentPackage != null) { 1680 synchronized (mPackages) { 1681 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1682 } 1683 } 1684 1685 synchronized (mPackages) { 1686 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1687 } 1688 1689 final String packageName = res.pkg.applicationInfo.packageName; 1690 Bundle extras = new Bundle(1); 1691 extras.putInt(Intent.EXTRA_UID, res.uid); 1692 1693 // Determine the set of users who are adding this package for 1694 // the first time vs. those who are seeing an update. 1695 int[] firstUsers = EMPTY_INT_ARRAY; 1696 int[] updateUsers = EMPTY_INT_ARRAY; 1697 if (res.origUsers == null || res.origUsers.length == 0) { 1698 firstUsers = res.newUsers; 1699 } else { 1700 for (int newUser : res.newUsers) { 1701 boolean isNew = true; 1702 for (int origUser : res.origUsers) { 1703 if (origUser == newUser) { 1704 isNew = false; 1705 break; 1706 } 1707 } 1708 if (isNew) { 1709 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1710 } else { 1711 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1712 } 1713 } 1714 } 1715 1716 // Send installed broadcasts if the install/update is not ephemeral 1717 if (!isEphemeral(res.pkg)) { 1718 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1719 1720 // Send added for users that see the package for the first time 1721 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1722 extras, 0 /*flags*/, null /*targetPackage*/, 1723 null /*finishedReceiver*/, firstUsers); 1724 1725 // Send added for users that don't see the package for the first time 1726 if (update) { 1727 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1728 } 1729 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1730 extras, 0 /*flags*/, null /*targetPackage*/, 1731 null /*finishedReceiver*/, updateUsers); 1732 1733 // Send replaced for users that don't see the package for the first time 1734 if (update) { 1735 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1736 packageName, extras, 0 /*flags*/, 1737 null /*targetPackage*/, null /*finishedReceiver*/, 1738 updateUsers); 1739 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1740 null /*package*/, null /*extras*/, 0 /*flags*/, 1741 packageName /*targetPackage*/, 1742 null /*finishedReceiver*/, updateUsers); 1743 } 1744 1745 // Send broadcast package appeared if forward locked/external for all users 1746 // treat asec-hosted packages like removable media on upgrade 1747 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1748 if (DEBUG_INSTALL) { 1749 Slog.i(TAG, "upgrading pkg " + res.pkg 1750 + " is ASEC-hosted -> AVAILABLE"); 1751 } 1752 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1753 ArrayList<String> pkgList = new ArrayList<>(1); 1754 pkgList.add(packageName); 1755 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1756 } 1757 } 1758 1759 // Work that needs to happen on first install within each user 1760 if (firstUsers != null && firstUsers.length > 0) { 1761 synchronized (mPackages) { 1762 for (int userId : firstUsers) { 1763 // If this app is a browser and it's newly-installed for some 1764 // users, clear any default-browser state in those users. The 1765 // app's nature doesn't depend on the user, so we can just check 1766 // its browser nature in any user and generalize. 1767 if (packageIsBrowser(packageName, userId)) { 1768 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1769 } 1770 1771 // We may also need to apply pending (restored) runtime 1772 // permission grants within these users. 1773 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1774 } 1775 } 1776 } 1777 1778 // Log current value of "unknown sources" setting 1779 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1780 getUnknownSourcesSettings()); 1781 1782 // Force a gc to clear up things 1783 Runtime.getRuntime().gc(); 1784 1785 // Remove the replaced package's older resources safely now 1786 // We delete after a gc for applications on sdcard. 1787 if (res.removedInfo != null && res.removedInfo.args != null) { 1788 synchronized (mInstallLock) { 1789 res.removedInfo.args.doPostDeleteLI(true); 1790 } 1791 } 1792 } 1793 1794 // If someone is watching installs - notify them 1795 if (installObserver != null) { 1796 try { 1797 Bundle extras = extrasForInstallResult(res); 1798 installObserver.onPackageInstalled(res.name, res.returnCode, 1799 res.returnMsg, extras); 1800 } catch (RemoteException e) { 1801 Slog.i(TAG, "Observer no longer exists."); 1802 } 1803 } 1804 } 1805 1806 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1807 PackageParser.Package pkg) { 1808 if (pkg.parentPackage == null) { 1809 return; 1810 } 1811 if (pkg.requestedPermissions == null) { 1812 return; 1813 } 1814 final PackageSetting disabledSysParentPs = mSettings 1815 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1816 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1817 || !disabledSysParentPs.isPrivileged() 1818 || (disabledSysParentPs.childPackageNames != null 1819 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1820 return; 1821 } 1822 final int[] allUserIds = sUserManager.getUserIds(); 1823 final int permCount = pkg.requestedPermissions.size(); 1824 for (int i = 0; i < permCount; i++) { 1825 String permission = pkg.requestedPermissions.get(i); 1826 BasePermission bp = mSettings.mPermissions.get(permission); 1827 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1828 continue; 1829 } 1830 for (int userId : allUserIds) { 1831 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1832 permission, userId)) { 1833 grantRuntimePermission(pkg.packageName, permission, userId); 1834 } 1835 } 1836 } 1837 } 1838 1839 private StorageEventListener mStorageListener = new StorageEventListener() { 1840 @Override 1841 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1842 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1843 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1844 final String volumeUuid = vol.getFsUuid(); 1845 1846 // Clean up any users or apps that were removed or recreated 1847 // while this volume was missing 1848 reconcileUsers(volumeUuid); 1849 reconcileApps(volumeUuid); 1850 1851 // Clean up any install sessions that expired or were 1852 // cancelled while this volume was missing 1853 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1854 1855 loadPrivatePackages(vol); 1856 1857 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1858 unloadPrivatePackages(vol); 1859 } 1860 } 1861 1862 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1863 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1864 updateExternalMediaStatus(true, false); 1865 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1866 updateExternalMediaStatus(false, false); 1867 } 1868 } 1869 } 1870 1871 @Override 1872 public void onVolumeForgotten(String fsUuid) { 1873 if (TextUtils.isEmpty(fsUuid)) { 1874 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1875 return; 1876 } 1877 1878 // Remove any apps installed on the forgotten volume 1879 synchronized (mPackages) { 1880 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1881 for (PackageSetting ps : packages) { 1882 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1883 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1884 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1885 } 1886 1887 mSettings.onVolumeForgotten(fsUuid); 1888 mSettings.writeLPr(); 1889 } 1890 } 1891 }; 1892 1893 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1894 String[] grantedPermissions) { 1895 for (int userId : userIds) { 1896 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1897 } 1898 1899 // We could have touched GID membership, so flush out packages.list 1900 synchronized (mPackages) { 1901 mSettings.writePackageListLPr(); 1902 } 1903 } 1904 1905 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1906 String[] grantedPermissions) { 1907 SettingBase sb = (SettingBase) pkg.mExtras; 1908 if (sb == null) { 1909 return; 1910 } 1911 1912 PermissionsState permissionsState = sb.getPermissionsState(); 1913 1914 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1915 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1916 1917 synchronized (mPackages) { 1918 for (String permission : pkg.requestedPermissions) { 1919 BasePermission bp = mSettings.mPermissions.get(permission); 1920 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1921 && (grantedPermissions == null 1922 || ArrayUtils.contains(grantedPermissions, permission))) { 1923 final int flags = permissionsState.getPermissionFlags(permission, userId); 1924 // Installer cannot change immutable permissions. 1925 if ((flags & immutableFlags) == 0) { 1926 grantRuntimePermission(pkg.packageName, permission, userId); 1927 } 1928 } 1929 } 1930 } 1931 } 1932 1933 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1934 Bundle extras = null; 1935 switch (res.returnCode) { 1936 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1937 extras = new Bundle(); 1938 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1939 res.origPermission); 1940 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1941 res.origPackage); 1942 break; 1943 } 1944 case PackageManager.INSTALL_SUCCEEDED: { 1945 extras = new Bundle(); 1946 extras.putBoolean(Intent.EXTRA_REPLACING, 1947 res.removedInfo != null && res.removedInfo.removedPackage != null); 1948 break; 1949 } 1950 } 1951 return extras; 1952 } 1953 1954 void scheduleWriteSettingsLocked() { 1955 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1956 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1957 } 1958 } 1959 1960 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 1961 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 1962 scheduleWritePackageRestrictionsLocked(userId); 1963 } 1964 1965 void scheduleWritePackageRestrictionsLocked(int userId) { 1966 final int[] userIds = (userId == UserHandle.USER_ALL) 1967 ? sUserManager.getUserIds() : new int[]{userId}; 1968 for (int nextUserId : userIds) { 1969 if (!sUserManager.exists(nextUserId)) return; 1970 mDirtyUsers.add(nextUserId); 1971 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1972 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1973 } 1974 } 1975 } 1976 1977 public static PackageManagerService main(Context context, Installer installer, 1978 boolean factoryTest, boolean onlyCore) { 1979 // Self-check for initial settings. 1980 PackageManagerServiceCompilerMapping.checkProperties(); 1981 1982 PackageManagerService m = new PackageManagerService(context, installer, 1983 factoryTest, onlyCore); 1984 m.enableSystemUserPackages(); 1985 ServiceManager.addService("package", m); 1986 return m; 1987 } 1988 1989 private void enableSystemUserPackages() { 1990 if (!UserManager.isSplitSystemUser()) { 1991 return; 1992 } 1993 // For system user, enable apps based on the following conditions: 1994 // - app is whitelisted or belong to one of these groups: 1995 // -- system app which has no launcher icons 1996 // -- system app which has INTERACT_ACROSS_USERS permission 1997 // -- system IME app 1998 // - app is not in the blacklist 1999 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2000 Set<String> enableApps = new ArraySet<>(); 2001 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2002 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2003 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2004 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2005 enableApps.addAll(wlApps); 2006 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2007 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2008 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2009 enableApps.removeAll(blApps); 2010 Log.i(TAG, "Applications installed for system user: " + enableApps); 2011 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2012 UserHandle.SYSTEM); 2013 final int allAppsSize = allAps.size(); 2014 synchronized (mPackages) { 2015 for (int i = 0; i < allAppsSize; i++) { 2016 String pName = allAps.get(i); 2017 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2018 // Should not happen, but we shouldn't be failing if it does 2019 if (pkgSetting == null) { 2020 continue; 2021 } 2022 boolean install = enableApps.contains(pName); 2023 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2024 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2025 + " for system user"); 2026 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2027 } 2028 } 2029 } 2030 } 2031 2032 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2033 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2034 Context.DISPLAY_SERVICE); 2035 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2036 } 2037 2038 public PackageManagerService(Context context, Installer installer, 2039 boolean factoryTest, boolean onlyCore) { 2040 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2041 SystemClock.uptimeMillis()); 2042 2043 if (mSdkVersion <= 0) { 2044 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2045 } 2046 2047 mContext = context; 2048 mFactoryTest = factoryTest; 2049 mOnlyCore = onlyCore; 2050 mMetrics = new DisplayMetrics(); 2051 mSettings = new Settings(mPackages); 2052 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2053 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2054 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2055 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2056 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2057 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2058 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2059 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2060 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2061 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2062 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2063 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2064 2065 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2066 if (separateProcesses != null && separateProcesses.length() > 0) { 2067 if ("*".equals(separateProcesses)) { 2068 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2069 mSeparateProcesses = null; 2070 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2071 } else { 2072 mDefParseFlags = 0; 2073 mSeparateProcesses = separateProcesses.split(","); 2074 Slog.w(TAG, "Running with debug.separate_processes: " 2075 + separateProcesses); 2076 } 2077 } else { 2078 mDefParseFlags = 0; 2079 mSeparateProcesses = null; 2080 } 2081 2082 mInstaller = installer; 2083 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2084 "*dexopt*"); 2085 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2086 2087 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2088 FgThread.get().getLooper()); 2089 2090 getDefaultDisplayMetrics(context, mMetrics); 2091 2092 SystemConfig systemConfig = SystemConfig.getInstance(); 2093 mGlobalGids = systemConfig.getGlobalGids(); 2094 mSystemPermissions = systemConfig.getSystemPermissions(); 2095 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2096 2097 synchronized (mInstallLock) { 2098 // writer 2099 synchronized (mPackages) { 2100 mHandlerThread = new ServiceThread(TAG, 2101 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2102 mHandlerThread.start(); 2103 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2104 mProcessLoggingHandler = new ProcessLoggingHandler(); 2105 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2106 2107 File dataDir = Environment.getDataDirectory(); 2108 mAppInstallDir = new File(dataDir, "app"); 2109 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2110 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2111 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2112 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2113 2114 sUserManager = new UserManagerService(context, this, mPackages); 2115 2116 // Propagate permission configuration in to package manager. 2117 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2118 = systemConfig.getPermissions(); 2119 for (int i=0; i<permConfig.size(); i++) { 2120 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2121 BasePermission bp = mSettings.mPermissions.get(perm.name); 2122 if (bp == null) { 2123 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2124 mSettings.mPermissions.put(perm.name, bp); 2125 } 2126 if (perm.gids != null) { 2127 bp.setGids(perm.gids, perm.perUser); 2128 } 2129 } 2130 2131 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2132 for (int i=0; i<libConfig.size(); i++) { 2133 mSharedLibraries.put(libConfig.keyAt(i), 2134 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2135 } 2136 2137 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2138 2139 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2140 2141 String customResolverActivity = Resources.getSystem().getString( 2142 R.string.config_customResolverActivity); 2143 if (TextUtils.isEmpty(customResolverActivity)) { 2144 customResolverActivity = null; 2145 } else { 2146 mCustomResolverComponentName = ComponentName.unflattenFromString( 2147 customResolverActivity); 2148 } 2149 2150 long startTime = SystemClock.uptimeMillis(); 2151 2152 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2153 startTime); 2154 2155 // Set flag to monitor and not change apk file paths when 2156 // scanning install directories. 2157 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2158 2159 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2160 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2161 2162 if (bootClassPath == null) { 2163 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2164 } 2165 2166 if (systemServerClassPath == null) { 2167 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2168 } 2169 2170 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2171 final String[] dexCodeInstructionSets = 2172 getDexCodeInstructionSets( 2173 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2174 2175 /** 2176 * Ensure all external libraries have had dexopt run on them. 2177 */ 2178 if (mSharedLibraries.size() > 0) { 2179 // NOTE: For now, we're compiling these system "shared libraries" 2180 // (and framework jars) into all available architectures. It's possible 2181 // to compile them only when we come across an app that uses them (there's 2182 // already logic for that in scanPackageLI) but that adds some complexity. 2183 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2184 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2185 final String lib = libEntry.path; 2186 if (lib == null) { 2187 continue; 2188 } 2189 2190 try { 2191 // Shared libraries do not have profiles so we perform a full 2192 // AOT compilation (if needed). 2193 int dexoptNeeded = DexFile.getDexOptNeeded( 2194 lib, dexCodeInstructionSet, 2195 getCompilerFilterForReason(REASON_SHARED_APK), 2196 false /* newProfile */); 2197 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2198 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2199 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2200 getCompilerFilterForReason(REASON_SHARED_APK), 2201 StorageManager.UUID_PRIVATE_INTERNAL); 2202 } 2203 } catch (FileNotFoundException e) { 2204 Slog.w(TAG, "Library not found: " + lib); 2205 } catch (IOException | InstallerException e) { 2206 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2207 + e.getMessage()); 2208 } 2209 } 2210 } 2211 } 2212 2213 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2214 2215 final VersionInfo ver = mSettings.getInternalVersion(); 2216 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2217 2218 // when upgrading from pre-M, promote system app permissions from install to runtime 2219 mPromoteSystemApps = 2220 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2221 2222 // save off the names of pre-existing system packages prior to scanning; we don't 2223 // want to automatically grant runtime permissions for new system apps 2224 if (mPromoteSystemApps) { 2225 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2226 while (pkgSettingIter.hasNext()) { 2227 PackageSetting ps = pkgSettingIter.next(); 2228 if (isSystemApp(ps)) { 2229 mExistingSystemPackages.add(ps.name); 2230 } 2231 } 2232 } 2233 2234 // When upgrading from pre-N, we need to handle package extraction like first boot, 2235 // as there is no profiling data available. 2236 mIsPreNUpgrade = !mSettings.isNWorkDone(); 2237 mSettings.setNWorkDone(); 2238 2239 // Collect vendor overlay packages. 2240 // (Do this before scanning any apps.) 2241 // For security and version matching reason, only consider 2242 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2243 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2244 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2245 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2246 2247 // Find base frameworks (resource packages without code). 2248 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2249 | PackageParser.PARSE_IS_SYSTEM_DIR 2250 | PackageParser.PARSE_IS_PRIVILEGED, 2251 scanFlags | SCAN_NO_DEX, 0); 2252 2253 // Collected privileged system packages. 2254 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2255 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2256 | PackageParser.PARSE_IS_SYSTEM_DIR 2257 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2258 2259 // Collect ordinary system packages. 2260 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2261 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2262 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2263 2264 // Collect all vendor packages. 2265 File vendorAppDir = new File("/vendor/app"); 2266 try { 2267 vendorAppDir = vendorAppDir.getCanonicalFile(); 2268 } catch (IOException e) { 2269 // failed to look up canonical path, continue with original one 2270 } 2271 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2272 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2273 2274 // Collect all OEM packages. 2275 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2276 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2277 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2278 2279 // Prune any system packages that no longer exist. 2280 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2281 if (!mOnlyCore) { 2282 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2283 while (psit.hasNext()) { 2284 PackageSetting ps = psit.next(); 2285 2286 /* 2287 * If this is not a system app, it can't be a 2288 * disable system app. 2289 */ 2290 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2291 continue; 2292 } 2293 2294 /* 2295 * If the package is scanned, it's not erased. 2296 */ 2297 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2298 if (scannedPkg != null) { 2299 /* 2300 * If the system app is both scanned and in the 2301 * disabled packages list, then it must have been 2302 * added via OTA. Remove it from the currently 2303 * scanned package so the previously user-installed 2304 * application can be scanned. 2305 */ 2306 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2307 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2308 + ps.name + "; removing system app. Last known codePath=" 2309 + ps.codePathString + ", installStatus=" + ps.installStatus 2310 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2311 + scannedPkg.mVersionCode); 2312 removePackageLI(scannedPkg, true); 2313 mExpectingBetter.put(ps.name, ps.codePath); 2314 } 2315 2316 continue; 2317 } 2318 2319 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2320 psit.remove(); 2321 logCriticalInfo(Log.WARN, "System package " + ps.name 2322 + " no longer exists; wiping its data"); 2323 removeDataDirsLI(null, ps.name); 2324 } else { 2325 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2326 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2327 possiblyDeletedUpdatedSystemApps.add(ps.name); 2328 } 2329 } 2330 } 2331 } 2332 2333 //look for any incomplete package installations 2334 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2335 //clean up list 2336 for(int i = 0; i < deletePkgsList.size(); i++) { 2337 //clean up here 2338 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2339 } 2340 //delete tmp files 2341 deleteTempPackageFiles(); 2342 2343 // Remove any shared userIDs that have no associated packages 2344 mSettings.pruneSharedUsersLPw(); 2345 2346 if (!mOnlyCore) { 2347 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2348 SystemClock.uptimeMillis()); 2349 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2350 2351 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2352 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2353 2354 scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL, 2355 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2356 2357 /** 2358 * Remove disable package settings for any updated system 2359 * apps that were removed via an OTA. If they're not a 2360 * previously-updated app, remove them completely. 2361 * Otherwise, just revoke their system-level permissions. 2362 */ 2363 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2364 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2365 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2366 2367 String msg; 2368 if (deletedPkg == null) { 2369 msg = "Updated system package " + deletedAppName 2370 + " no longer exists; wiping its data"; 2371 removeDataDirsLI(null, deletedAppName); 2372 } else { 2373 msg = "Updated system app + " + deletedAppName 2374 + " no longer present; removing system privileges for " 2375 + deletedAppName; 2376 2377 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2378 2379 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2380 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2381 } 2382 logCriticalInfo(Log.WARN, msg); 2383 } 2384 2385 /** 2386 * Make sure all system apps that we expected to appear on 2387 * the userdata partition actually showed up. If they never 2388 * appeared, crawl back and revive the system version. 2389 */ 2390 for (int i = 0; i < mExpectingBetter.size(); i++) { 2391 final String packageName = mExpectingBetter.keyAt(i); 2392 if (!mPackages.containsKey(packageName)) { 2393 final File scanFile = mExpectingBetter.valueAt(i); 2394 2395 logCriticalInfo(Log.WARN, "Expected better " + packageName 2396 + " but never showed up; reverting to system"); 2397 2398 final int reparseFlags; 2399 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2400 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2401 | PackageParser.PARSE_IS_SYSTEM_DIR 2402 | PackageParser.PARSE_IS_PRIVILEGED; 2403 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2404 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2405 | PackageParser.PARSE_IS_SYSTEM_DIR; 2406 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2407 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2408 | PackageParser.PARSE_IS_SYSTEM_DIR; 2409 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2410 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2411 | PackageParser.PARSE_IS_SYSTEM_DIR; 2412 } else { 2413 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2414 continue; 2415 } 2416 2417 mSettings.enableSystemPackageLPw(packageName); 2418 2419 try { 2420 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2421 } catch (PackageManagerException e) { 2422 Slog.e(TAG, "Failed to parse original system package: " 2423 + e.getMessage()); 2424 } 2425 } 2426 } 2427 } 2428 mExpectingBetter.clear(); 2429 2430 // Now that we know all of the shared libraries, update all clients to have 2431 // the correct library paths. 2432 updateAllSharedLibrariesLPw(); 2433 2434 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2435 // NOTE: We ignore potential failures here during a system scan (like 2436 // the rest of the commands above) because there's precious little we 2437 // can do about it. A settings error is reported, though. 2438 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2439 false /* boot complete */); 2440 } 2441 2442 // Now that we know all the packages we are keeping, 2443 // read and update their last usage times. 2444 mPackageUsage.readLP(); 2445 2446 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2447 SystemClock.uptimeMillis()); 2448 Slog.i(TAG, "Time to scan packages: " 2449 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2450 + " seconds"); 2451 2452 // If the platform SDK has changed since the last time we booted, 2453 // we need to re-grant app permission to catch any new ones that 2454 // appear. This is really a hack, and means that apps can in some 2455 // cases get permissions that the user didn't initially explicitly 2456 // allow... it would be nice to have some better way to handle 2457 // this situation. 2458 int updateFlags = UPDATE_PERMISSIONS_ALL; 2459 if (ver.sdkVersion != mSdkVersion) { 2460 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2461 + mSdkVersion + "; regranting permissions for internal storage"); 2462 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2463 } 2464 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2465 ver.sdkVersion = mSdkVersion; 2466 2467 // If this is the first boot or an update from pre-M, and it is a normal 2468 // boot, then we need to initialize the default preferred apps across 2469 // all defined users. 2470 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2471 for (UserInfo user : sUserManager.getUsers(true)) { 2472 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2473 applyFactoryDefaultBrowserLPw(user.id); 2474 primeDomainVerificationsLPw(user.id); 2475 } 2476 } 2477 2478 // Prepare storage for system user really early during boot, 2479 // since core system apps like SettingsProvider and SystemUI 2480 // can't wait for user to start 2481 final int storageFlags; 2482 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2483 storageFlags = StorageManager.FLAG_STORAGE_DE; 2484 } else { 2485 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2486 } 2487 reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2488 storageFlags); 2489 2490 // If this is first boot after an OTA, and a normal boot, then 2491 // we need to clear code cache directories. 2492 if (mIsUpgrade && !onlyCore) { 2493 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2494 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2495 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2496 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2497 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2498 } 2499 } 2500 ver.fingerprint = Build.FINGERPRINT; 2501 } 2502 2503 checkDefaultBrowser(); 2504 2505 // clear only after permissions and other defaults have been updated 2506 mExistingSystemPackages.clear(); 2507 mPromoteSystemApps = false; 2508 2509 // All the changes are done during package scanning. 2510 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2511 2512 // can downgrade to reader 2513 mSettings.writeLPr(); 2514 2515 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2516 SystemClock.uptimeMillis()); 2517 2518 if (!mOnlyCore) { 2519 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2520 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2521 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2522 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2523 mIntentFilterVerifierComponent); 2524 } else { 2525 mRequiredVerifierPackage = null; 2526 mRequiredInstallerPackage = null; 2527 mIntentFilterVerifierComponent = null; 2528 mIntentFilterVerifier = null; 2529 } 2530 2531 mInstallerService = new PackageInstallerService(context, this); 2532 2533 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2534 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2535 // both the installer and resolver must be present to enable ephemeral 2536 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2537 if (DEBUG_EPHEMERAL) { 2538 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2539 + " installer:" + ephemeralInstallerComponent); 2540 } 2541 mEphemeralResolverComponent = ephemeralResolverComponent; 2542 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2543 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2544 mEphemeralResolverConnection = 2545 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2546 } else { 2547 if (DEBUG_EPHEMERAL) { 2548 final String missingComponent = 2549 (ephemeralResolverComponent == null) 2550 ? (ephemeralInstallerComponent == null) 2551 ? "resolver and installer" 2552 : "resolver" 2553 : "installer"; 2554 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2555 } 2556 mEphemeralResolverComponent = null; 2557 mEphemeralInstallerComponent = null; 2558 mEphemeralResolverConnection = null; 2559 } 2560 2561 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2562 } // synchronized (mPackages) 2563 } // synchronized (mInstallLock) 2564 2565 // Now after opening every single application zip, make sure they 2566 // are all flushed. Not really needed, but keeps things nice and 2567 // tidy. 2568 Runtime.getRuntime().gc(); 2569 2570 // The initial scanning above does many calls into installd while 2571 // holding the mPackages lock, but we're mostly interested in yelling 2572 // once we have a booted system. 2573 mInstaller.setWarnIfHeld(mPackages); 2574 2575 // Expose private service for system components to use. 2576 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2577 } 2578 2579 @Override 2580 public boolean isFirstBoot() { 2581 return !mRestoredSettings; 2582 } 2583 2584 @Override 2585 public boolean isOnlyCoreApps() { 2586 return mOnlyCore; 2587 } 2588 2589 @Override 2590 public boolean isUpgrade() { 2591 return mIsUpgrade; 2592 } 2593 2594 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2595 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2596 2597 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2598 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2599 UserHandle.USER_SYSTEM); 2600 if (matches.size() == 1) { 2601 return matches.get(0).getComponentInfo().packageName; 2602 } else { 2603 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2604 return null; 2605 } 2606 } 2607 2608 private @NonNull String getRequiredInstallerLPr() { 2609 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2610 intent.addCategory(Intent.CATEGORY_DEFAULT); 2611 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2612 2613 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2614 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2615 UserHandle.USER_SYSTEM); 2616 if (matches.size() == 1) { 2617 return matches.get(0).getComponentInfo().packageName; 2618 } else { 2619 throw new RuntimeException("There must be exactly one installer; found " + matches); 2620 } 2621 } 2622 2623 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2624 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2625 2626 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2627 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2628 UserHandle.USER_SYSTEM); 2629 ResolveInfo best = null; 2630 final int N = matches.size(); 2631 for (int i = 0; i < N; i++) { 2632 final ResolveInfo cur = matches.get(i); 2633 final String packageName = cur.getComponentInfo().packageName; 2634 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2635 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2636 continue; 2637 } 2638 2639 if (best == null || cur.priority > best.priority) { 2640 best = cur; 2641 } 2642 } 2643 2644 if (best != null) { 2645 return best.getComponentInfo().getComponentName(); 2646 } else { 2647 throw new RuntimeException("There must be at least one intent filter verifier"); 2648 } 2649 } 2650 2651 private @Nullable ComponentName getEphemeralResolverLPr() { 2652 final String[] packageArray = 2653 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2654 if (packageArray.length == 0) { 2655 if (DEBUG_EPHEMERAL) { 2656 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2657 } 2658 return null; 2659 } 2660 2661 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2662 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2663 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2664 UserHandle.USER_SYSTEM); 2665 2666 final int N = resolvers.size(); 2667 if (N == 0) { 2668 if (DEBUG_EPHEMERAL) { 2669 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2670 } 2671 return null; 2672 } 2673 2674 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2675 for (int i = 0; i < N; i++) { 2676 final ResolveInfo info = resolvers.get(i); 2677 2678 if (info.serviceInfo == null) { 2679 continue; 2680 } 2681 2682 final String packageName = info.serviceInfo.packageName; 2683 if (!possiblePackages.contains(packageName)) { 2684 if (DEBUG_EPHEMERAL) { 2685 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2686 + " pkg: " + packageName + ", info:" + info); 2687 } 2688 continue; 2689 } 2690 2691 if (DEBUG_EPHEMERAL) { 2692 Slog.v(TAG, "Ephemeral resolver found;" 2693 + " pkg: " + packageName + ", info:" + info); 2694 } 2695 return new ComponentName(packageName, info.serviceInfo.name); 2696 } 2697 if (DEBUG_EPHEMERAL) { 2698 Slog.v(TAG, "Ephemeral resolver NOT found"); 2699 } 2700 return null; 2701 } 2702 2703 private @Nullable ComponentName getEphemeralInstallerLPr() { 2704 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2705 intent.addCategory(Intent.CATEGORY_DEFAULT); 2706 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2707 2708 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2709 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2710 UserHandle.USER_SYSTEM); 2711 if (matches.size() == 0) { 2712 return null; 2713 } else if (matches.size() == 1) { 2714 return matches.get(0).getComponentInfo().getComponentName(); 2715 } else { 2716 throw new RuntimeException( 2717 "There must be at most one ephemeral installer; found " + matches); 2718 } 2719 } 2720 2721 private void primeDomainVerificationsLPw(int userId) { 2722 if (DEBUG_DOMAIN_VERIFICATION) { 2723 Slog.d(TAG, "Priming domain verifications in user " + userId); 2724 } 2725 2726 SystemConfig systemConfig = SystemConfig.getInstance(); 2727 ArraySet<String> packages = systemConfig.getLinkedApps(); 2728 ArraySet<String> domains = new ArraySet<String>(); 2729 2730 for (String packageName : packages) { 2731 PackageParser.Package pkg = mPackages.get(packageName); 2732 if (pkg != null) { 2733 if (!pkg.isSystemApp()) { 2734 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2735 continue; 2736 } 2737 2738 domains.clear(); 2739 for (PackageParser.Activity a : pkg.activities) { 2740 for (ActivityIntentInfo filter : a.intents) { 2741 if (hasValidDomains(filter)) { 2742 domains.addAll(filter.getHostsList()); 2743 } 2744 } 2745 } 2746 2747 if (domains.size() > 0) { 2748 if (DEBUG_DOMAIN_VERIFICATION) { 2749 Slog.v(TAG, " + " + packageName); 2750 } 2751 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2752 // state w.r.t. the formal app-linkage "no verification attempted" state; 2753 // and then 'always' in the per-user state actually used for intent resolution. 2754 final IntentFilterVerificationInfo ivi; 2755 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2756 new ArrayList<String>(domains)); 2757 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2758 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2759 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2760 } else { 2761 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2762 + "' does not handle web links"); 2763 } 2764 } else { 2765 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2766 } 2767 } 2768 2769 scheduleWritePackageRestrictionsLocked(userId); 2770 scheduleWriteSettingsLocked(); 2771 } 2772 2773 private void applyFactoryDefaultBrowserLPw(int userId) { 2774 // The default browser app's package name is stored in a string resource, 2775 // with a product-specific overlay used for vendor customization. 2776 String browserPkg = mContext.getResources().getString( 2777 com.android.internal.R.string.default_browser); 2778 if (!TextUtils.isEmpty(browserPkg)) { 2779 // non-empty string => required to be a known package 2780 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2781 if (ps == null) { 2782 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2783 browserPkg = null; 2784 } else { 2785 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2786 } 2787 } 2788 2789 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2790 // default. If there's more than one, just leave everything alone. 2791 if (browserPkg == null) { 2792 calculateDefaultBrowserLPw(userId); 2793 } 2794 } 2795 2796 private void calculateDefaultBrowserLPw(int userId) { 2797 List<String> allBrowsers = resolveAllBrowserApps(userId); 2798 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2799 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2800 } 2801 2802 private List<String> resolveAllBrowserApps(int userId) { 2803 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2804 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2805 PackageManager.MATCH_ALL, userId); 2806 2807 final int count = list.size(); 2808 List<String> result = new ArrayList<String>(count); 2809 for (int i=0; i<count; i++) { 2810 ResolveInfo info = list.get(i); 2811 if (info.activityInfo == null 2812 || !info.handleAllWebDataURI 2813 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2814 || result.contains(info.activityInfo.packageName)) { 2815 continue; 2816 } 2817 result.add(info.activityInfo.packageName); 2818 } 2819 2820 return result; 2821 } 2822 2823 private boolean packageIsBrowser(String packageName, int userId) { 2824 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2825 PackageManager.MATCH_ALL, userId); 2826 final int N = list.size(); 2827 for (int i = 0; i < N; i++) { 2828 ResolveInfo info = list.get(i); 2829 if (packageName.equals(info.activityInfo.packageName)) { 2830 return true; 2831 } 2832 } 2833 return false; 2834 } 2835 2836 private void checkDefaultBrowser() { 2837 final int myUserId = UserHandle.myUserId(); 2838 final String packageName = getDefaultBrowserPackageName(myUserId); 2839 if (packageName != null) { 2840 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2841 if (info == null) { 2842 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2843 synchronized (mPackages) { 2844 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2845 } 2846 } 2847 } 2848 } 2849 2850 @Override 2851 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2852 throws RemoteException { 2853 try { 2854 return super.onTransact(code, data, reply, flags); 2855 } catch (RuntimeException e) { 2856 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2857 Slog.wtf(TAG, "Package Manager Crash", e); 2858 } 2859 throw e; 2860 } 2861 } 2862 2863 void cleanupInstallFailedPackage(PackageSetting ps) { 2864 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2865 2866 removeDataDirsLI(ps.volumeUuid, ps.name); 2867 if (ps.codePath != null) { 2868 removeCodePathLI(ps.codePath); 2869 } 2870 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2871 if (ps.resourcePath.isDirectory()) { 2872 FileUtils.deleteContents(ps.resourcePath); 2873 } 2874 ps.resourcePath.delete(); 2875 } 2876 mSettings.removePackageLPw(ps.name); 2877 } 2878 2879 static int[] appendInts(int[] cur, int[] add) { 2880 if (add == null) return cur; 2881 if (cur == null) return add; 2882 final int N = add.length; 2883 for (int i=0; i<N; i++) { 2884 cur = appendInt(cur, add[i]); 2885 } 2886 return cur; 2887 } 2888 2889 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2890 if (!sUserManager.exists(userId)) return null; 2891 final PackageSetting ps = (PackageSetting) p.mExtras; 2892 if (ps == null) { 2893 return null; 2894 } 2895 2896 final PermissionsState permissionsState = ps.getPermissionsState(); 2897 2898 final int[] gids = permissionsState.computeGids(userId); 2899 final Set<String> permissions = permissionsState.getPermissions(userId); 2900 final PackageUserState state = ps.readUserState(userId); 2901 2902 return PackageParser.generatePackageInfo(p, gids, flags, 2903 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2904 } 2905 2906 @Override 2907 public void checkPackageStartable(String packageName, int userId) { 2908 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 2909 2910 synchronized (mPackages) { 2911 final PackageSetting ps = mSettings.mPackages.get(packageName); 2912 if (ps == null) { 2913 throw new SecurityException("Package " + packageName + " was not found!"); 2914 } 2915 2916 if (!ps.getInstalled(userId)) { 2917 throw new SecurityException( 2918 "Package " + packageName + " was not installed for user " + userId + "!"); 2919 } 2920 2921 if (mSafeMode && !ps.isSystem()) { 2922 throw new SecurityException("Package " + packageName + " not a system app!"); 2923 } 2924 2925 if (ps.frozen) { 2926 throw new SecurityException("Package " + packageName + " is currently frozen!"); 2927 } 2928 2929 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 2930 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 2931 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 2932 } 2933 } 2934 } 2935 2936 @Override 2937 public boolean isPackageAvailable(String packageName, int userId) { 2938 if (!sUserManager.exists(userId)) return false; 2939 enforceCrossUserPermission(Binder.getCallingUid(), userId, 2940 false /* requireFullPermission */, false /* checkShell */, "is package available"); 2941 synchronized (mPackages) { 2942 PackageParser.Package p = mPackages.get(packageName); 2943 if (p != null) { 2944 final PackageSetting ps = (PackageSetting) p.mExtras; 2945 if (ps != null) { 2946 final PackageUserState state = ps.readUserState(userId); 2947 if (state != null) { 2948 return PackageParser.isAvailable(state); 2949 } 2950 } 2951 } 2952 } 2953 return false; 2954 } 2955 2956 @Override 2957 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2958 if (!sUserManager.exists(userId)) return null; 2959 flags = updateFlagsForPackage(flags, userId, packageName); 2960 enforceCrossUserPermission(Binder.getCallingUid(), userId, 2961 false /* requireFullPermission */, false /* checkShell */, "get package info"); 2962 // reader 2963 synchronized (mPackages) { 2964 PackageParser.Package p = mPackages.get(packageName); 2965 if (DEBUG_PACKAGE_INFO) 2966 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2967 if (p != null) { 2968 return generatePackageInfo(p, flags, userId); 2969 } 2970 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2971 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2972 } 2973 } 2974 return null; 2975 } 2976 2977 @Override 2978 public String[] currentToCanonicalPackageNames(String[] names) { 2979 String[] out = new String[names.length]; 2980 // reader 2981 synchronized (mPackages) { 2982 for (int i=names.length-1; i>=0; i--) { 2983 PackageSetting ps = mSettings.mPackages.get(names[i]); 2984 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2985 } 2986 } 2987 return out; 2988 } 2989 2990 @Override 2991 public String[] canonicalToCurrentPackageNames(String[] names) { 2992 String[] out = new String[names.length]; 2993 // reader 2994 synchronized (mPackages) { 2995 for (int i=names.length-1; i>=0; i--) { 2996 String cur = mSettings.mRenamedPackages.get(names[i]); 2997 out[i] = cur != null ? cur : names[i]; 2998 } 2999 } 3000 return out; 3001 } 3002 3003 @Override 3004 public int getPackageUid(String packageName, int flags, int userId) { 3005 if (!sUserManager.exists(userId)) return -1; 3006 flags = updateFlagsForPackage(flags, userId, packageName); 3007 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3008 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3009 3010 // reader 3011 synchronized (mPackages) { 3012 final PackageParser.Package p = mPackages.get(packageName); 3013 if (p != null && p.isMatch(flags)) { 3014 return UserHandle.getUid(userId, p.applicationInfo.uid); 3015 } 3016 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3017 final PackageSetting ps = mSettings.mPackages.get(packageName); 3018 if (ps != null && ps.isMatch(flags)) { 3019 return UserHandle.getUid(userId, ps.appId); 3020 } 3021 } 3022 } 3023 3024 return -1; 3025 } 3026 3027 @Override 3028 public int[] getPackageGids(String packageName, int flags, int userId) { 3029 if (!sUserManager.exists(userId)) return null; 3030 flags = updateFlagsForPackage(flags, userId, packageName); 3031 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3032 false /* requireFullPermission */, false /* checkShell */, 3033 "getPackageGids"); 3034 3035 // reader 3036 synchronized (mPackages) { 3037 final PackageParser.Package p = mPackages.get(packageName); 3038 if (p != null && p.isMatch(flags)) { 3039 PackageSetting ps = (PackageSetting) p.mExtras; 3040 return ps.getPermissionsState().computeGids(userId); 3041 } 3042 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3043 final PackageSetting ps = mSettings.mPackages.get(packageName); 3044 if (ps != null && ps.isMatch(flags)) { 3045 return ps.getPermissionsState().computeGids(userId); 3046 } 3047 } 3048 } 3049 3050 return null; 3051 } 3052 3053 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3054 if (bp.perm != null) { 3055 return PackageParser.generatePermissionInfo(bp.perm, flags); 3056 } 3057 PermissionInfo pi = new PermissionInfo(); 3058 pi.name = bp.name; 3059 pi.packageName = bp.sourcePackage; 3060 pi.nonLocalizedLabel = bp.name; 3061 pi.protectionLevel = bp.protectionLevel; 3062 return pi; 3063 } 3064 3065 @Override 3066 public PermissionInfo getPermissionInfo(String name, int flags) { 3067 // reader 3068 synchronized (mPackages) { 3069 final BasePermission p = mSettings.mPermissions.get(name); 3070 if (p != null) { 3071 return generatePermissionInfo(p, flags); 3072 } 3073 return null; 3074 } 3075 } 3076 3077 @Override 3078 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3079 int flags) { 3080 // reader 3081 synchronized (mPackages) { 3082 if (group != null && !mPermissionGroups.containsKey(group)) { 3083 // This is thrown as NameNotFoundException 3084 return null; 3085 } 3086 3087 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3088 for (BasePermission p : mSettings.mPermissions.values()) { 3089 if (group == null) { 3090 if (p.perm == null || p.perm.info.group == null) { 3091 out.add(generatePermissionInfo(p, flags)); 3092 } 3093 } else { 3094 if (p.perm != null && group.equals(p.perm.info.group)) { 3095 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3096 } 3097 } 3098 } 3099 return new ParceledListSlice<>(out); 3100 } 3101 } 3102 3103 @Override 3104 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3105 // reader 3106 synchronized (mPackages) { 3107 return PackageParser.generatePermissionGroupInfo( 3108 mPermissionGroups.get(name), flags); 3109 } 3110 } 3111 3112 @Override 3113 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3114 // reader 3115 synchronized (mPackages) { 3116 final int N = mPermissionGroups.size(); 3117 ArrayList<PermissionGroupInfo> out 3118 = new ArrayList<PermissionGroupInfo>(N); 3119 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3120 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3121 } 3122 return new ParceledListSlice<>(out); 3123 } 3124 } 3125 3126 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3127 int userId) { 3128 if (!sUserManager.exists(userId)) return null; 3129 PackageSetting ps = mSettings.mPackages.get(packageName); 3130 if (ps != null) { 3131 if (ps.pkg == null) { 3132 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 3133 flags, userId); 3134 if (pInfo != null) { 3135 return pInfo.applicationInfo; 3136 } 3137 return null; 3138 } 3139 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3140 ps.readUserState(userId), userId); 3141 } 3142 return null; 3143 } 3144 3145 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 3146 int userId) { 3147 if (!sUserManager.exists(userId)) return null; 3148 PackageSetting ps = mSettings.mPackages.get(packageName); 3149 if (ps != null) { 3150 PackageParser.Package pkg = ps.pkg; 3151 if (pkg == null) { 3152 if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) { 3153 return null; 3154 } 3155 // Only data remains, so we aren't worried about code paths 3156 pkg = new PackageParser.Package(packageName); 3157 pkg.applicationInfo.packageName = packageName; 3158 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 3159 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 3160 pkg.applicationInfo.uid = ps.appId; 3161 pkg.applicationInfo.initForUser(userId); 3162 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 3163 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 3164 } 3165 return generatePackageInfo(pkg, flags, userId); 3166 } 3167 return null; 3168 } 3169 3170 @Override 3171 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3172 if (!sUserManager.exists(userId)) return null; 3173 flags = updateFlagsForApplication(flags, userId, packageName); 3174 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3175 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3176 // writer 3177 synchronized (mPackages) { 3178 PackageParser.Package p = mPackages.get(packageName); 3179 if (DEBUG_PACKAGE_INFO) Log.v( 3180 TAG, "getApplicationInfo " + packageName 3181 + ": " + p); 3182 if (p != null) { 3183 PackageSetting ps = mSettings.mPackages.get(packageName); 3184 if (ps == null) return null; 3185 // Note: isEnabledLP() does not apply here - always return info 3186 return PackageParser.generateApplicationInfo( 3187 p, flags, ps.readUserState(userId), userId); 3188 } 3189 if ("android".equals(packageName)||"system".equals(packageName)) { 3190 return mAndroidApplication; 3191 } 3192 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3193 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3194 } 3195 } 3196 return null; 3197 } 3198 3199 @Override 3200 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3201 final IPackageDataObserver observer) { 3202 mContext.enforceCallingOrSelfPermission( 3203 android.Manifest.permission.CLEAR_APP_CACHE, null); 3204 // Queue up an async operation since clearing cache may take a little while. 3205 mHandler.post(new Runnable() { 3206 public void run() { 3207 mHandler.removeCallbacks(this); 3208 boolean success = true; 3209 synchronized (mInstallLock) { 3210 try { 3211 mInstaller.freeCache(volumeUuid, freeStorageSize); 3212 } catch (InstallerException e) { 3213 Slog.w(TAG, "Couldn't clear application caches: " + e); 3214 success = false; 3215 } 3216 } 3217 if (observer != null) { 3218 try { 3219 observer.onRemoveCompleted(null, success); 3220 } catch (RemoteException e) { 3221 Slog.w(TAG, "RemoveException when invoking call back"); 3222 } 3223 } 3224 } 3225 }); 3226 } 3227 3228 @Override 3229 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3230 final IntentSender pi) { 3231 mContext.enforceCallingOrSelfPermission( 3232 android.Manifest.permission.CLEAR_APP_CACHE, null); 3233 // Queue up an async operation since clearing cache may take a little while. 3234 mHandler.post(new Runnable() { 3235 public void run() { 3236 mHandler.removeCallbacks(this); 3237 boolean success = true; 3238 synchronized (mInstallLock) { 3239 try { 3240 mInstaller.freeCache(volumeUuid, freeStorageSize); 3241 } catch (InstallerException e) { 3242 Slog.w(TAG, "Couldn't clear application caches: " + e); 3243 success = false; 3244 } 3245 } 3246 if(pi != null) { 3247 try { 3248 // Callback via pending intent 3249 int code = success ? 1 : 0; 3250 pi.sendIntent(null, code, null, 3251 null, null); 3252 } catch (SendIntentException e1) { 3253 Slog.i(TAG, "Failed to send pending intent"); 3254 } 3255 } 3256 } 3257 }); 3258 } 3259 3260 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3261 synchronized (mInstallLock) { 3262 try { 3263 mInstaller.freeCache(volumeUuid, freeStorageSize); 3264 } catch (InstallerException e) { 3265 throw new IOException("Failed to free enough space", e); 3266 } 3267 } 3268 } 3269 3270 /** 3271 * Return if the user key is currently unlocked. 3272 */ 3273 private boolean isUserKeyUnlocked(int userId) { 3274 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 3275 final IMountService mount = IMountService.Stub 3276 .asInterface(ServiceManager.getService("mount")); 3277 if (mount == null) { 3278 Slog.w(TAG, "Early during boot, assuming locked"); 3279 return false; 3280 } 3281 final long token = Binder.clearCallingIdentity(); 3282 try { 3283 return mount.isUserKeyUnlocked(userId); 3284 } catch (RemoteException e) { 3285 throw e.rethrowAsRuntimeException(); 3286 } finally { 3287 Binder.restoreCallingIdentity(token); 3288 } 3289 } else { 3290 return true; 3291 } 3292 } 3293 3294 /** 3295 * Update given flags based on encryption status of current user. 3296 */ 3297 private int updateFlags(int flags, int userId) { 3298 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3299 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3300 // Caller expressed an explicit opinion about what encryption 3301 // aware/unaware components they want to see, so fall through and 3302 // give them what they want 3303 } else { 3304 // Caller expressed no opinion, so match based on user state 3305 if (isUserKeyUnlocked(userId)) { 3306 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3307 } else { 3308 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3309 } 3310 } 3311 return flags; 3312 } 3313 3314 /** 3315 * Update given flags when being used to request {@link PackageInfo}. 3316 */ 3317 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3318 boolean triaged = true; 3319 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3320 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3321 // Caller is asking for component details, so they'd better be 3322 // asking for specific encryption matching behavior, or be triaged 3323 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3324 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3325 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3326 triaged = false; 3327 } 3328 } 3329 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3330 | PackageManager.MATCH_SYSTEM_ONLY 3331 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3332 triaged = false; 3333 } 3334 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3335 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3336 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3337 } 3338 return updateFlags(flags, userId); 3339 } 3340 3341 /** 3342 * Update given flags when being used to request {@link ApplicationInfo}. 3343 */ 3344 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3345 return updateFlagsForPackage(flags, userId, cookie); 3346 } 3347 3348 /** 3349 * Update given flags when being used to request {@link ComponentInfo}. 3350 */ 3351 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3352 if (cookie instanceof Intent) { 3353 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3354 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3355 } 3356 } 3357 3358 boolean triaged = true; 3359 // Caller is asking for component details, so they'd better be 3360 // asking for specific encryption matching behavior, or be triaged 3361 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3362 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3363 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3364 triaged = false; 3365 } 3366 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3367 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3368 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3369 } 3370 3371 return updateFlags(flags, userId); 3372 } 3373 3374 /** 3375 * Update given flags when being used to request {@link ResolveInfo}. 3376 */ 3377 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3378 // Safe mode means we shouldn't match any third-party components 3379 if (mSafeMode) { 3380 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3381 } 3382 3383 return updateFlagsForComponent(flags, userId, cookie); 3384 } 3385 3386 @Override 3387 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3388 if (!sUserManager.exists(userId)) return null; 3389 flags = updateFlagsForComponent(flags, userId, component); 3390 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3391 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3392 synchronized (mPackages) { 3393 PackageParser.Activity a = mActivities.mActivities.get(component); 3394 3395 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3396 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3397 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3398 if (ps == null) return null; 3399 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3400 userId); 3401 } 3402 if (mResolveComponentName.equals(component)) { 3403 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3404 new PackageUserState(), userId); 3405 } 3406 } 3407 return null; 3408 } 3409 3410 @Override 3411 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3412 String resolvedType) { 3413 synchronized (mPackages) { 3414 if (component.equals(mResolveComponentName)) { 3415 // The resolver supports EVERYTHING! 3416 return true; 3417 } 3418 PackageParser.Activity a = mActivities.mActivities.get(component); 3419 if (a == null) { 3420 return false; 3421 } 3422 for (int i=0; i<a.intents.size(); i++) { 3423 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3424 intent.getData(), intent.getCategories(), TAG) >= 0) { 3425 return true; 3426 } 3427 } 3428 return false; 3429 } 3430 } 3431 3432 @Override 3433 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3434 if (!sUserManager.exists(userId)) return null; 3435 flags = updateFlagsForComponent(flags, userId, component); 3436 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3437 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3438 synchronized (mPackages) { 3439 PackageParser.Activity a = mReceivers.mActivities.get(component); 3440 if (DEBUG_PACKAGE_INFO) Log.v( 3441 TAG, "getReceiverInfo " + component + ": " + a); 3442 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3443 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3444 if (ps == null) return null; 3445 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3446 userId); 3447 } 3448 } 3449 return null; 3450 } 3451 3452 @Override 3453 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3454 if (!sUserManager.exists(userId)) return null; 3455 flags = updateFlagsForComponent(flags, userId, component); 3456 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3457 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3458 synchronized (mPackages) { 3459 PackageParser.Service s = mServices.mServices.get(component); 3460 if (DEBUG_PACKAGE_INFO) Log.v( 3461 TAG, "getServiceInfo " + component + ": " + s); 3462 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3463 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3464 if (ps == null) return null; 3465 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3466 userId); 3467 } 3468 } 3469 return null; 3470 } 3471 3472 @Override 3473 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3474 if (!sUserManager.exists(userId)) return null; 3475 flags = updateFlagsForComponent(flags, userId, component); 3476 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3477 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3478 synchronized (mPackages) { 3479 PackageParser.Provider p = mProviders.mProviders.get(component); 3480 if (DEBUG_PACKAGE_INFO) Log.v( 3481 TAG, "getProviderInfo " + component + ": " + p); 3482 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3483 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3484 if (ps == null) return null; 3485 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3486 userId); 3487 } 3488 } 3489 return null; 3490 } 3491 3492 @Override 3493 public String[] getSystemSharedLibraryNames() { 3494 Set<String> libSet; 3495 synchronized (mPackages) { 3496 libSet = mSharedLibraries.keySet(); 3497 int size = libSet.size(); 3498 if (size > 0) { 3499 String[] libs = new String[size]; 3500 libSet.toArray(libs); 3501 return libs; 3502 } 3503 } 3504 return null; 3505 } 3506 3507 @Override 3508 public @Nullable String getServicesSystemSharedLibraryPackageName() { 3509 synchronized (mPackages) { 3510 SharedLibraryEntry libraryEntry = mSharedLibraries.get( 3511 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 3512 if (libraryEntry != null) { 3513 return libraryEntry.apk; 3514 } 3515 } 3516 return null; 3517 } 3518 3519 @Override 3520 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3521 synchronized (mPackages) { 3522 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3523 3524 final FeatureInfo fi = new FeatureInfo(); 3525 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3526 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3527 res.add(fi); 3528 3529 return new ParceledListSlice<>(res); 3530 } 3531 } 3532 3533 @Override 3534 public boolean hasSystemFeature(String name, int version) { 3535 synchronized (mPackages) { 3536 final FeatureInfo feat = mAvailableFeatures.get(name); 3537 if (feat == null) { 3538 return false; 3539 } else { 3540 return feat.version >= version; 3541 } 3542 } 3543 } 3544 3545 @Override 3546 public int checkPermission(String permName, String pkgName, int userId) { 3547 if (!sUserManager.exists(userId)) { 3548 return PackageManager.PERMISSION_DENIED; 3549 } 3550 3551 synchronized (mPackages) { 3552 final PackageParser.Package p = mPackages.get(pkgName); 3553 if (p != null && p.mExtras != null) { 3554 final PackageSetting ps = (PackageSetting) p.mExtras; 3555 final PermissionsState permissionsState = ps.getPermissionsState(); 3556 if (permissionsState.hasPermission(permName, userId)) { 3557 return PackageManager.PERMISSION_GRANTED; 3558 } 3559 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3560 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3561 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3562 return PackageManager.PERMISSION_GRANTED; 3563 } 3564 } 3565 } 3566 3567 return PackageManager.PERMISSION_DENIED; 3568 } 3569 3570 @Override 3571 public int checkUidPermission(String permName, int uid) { 3572 final int userId = UserHandle.getUserId(uid); 3573 3574 if (!sUserManager.exists(userId)) { 3575 return PackageManager.PERMISSION_DENIED; 3576 } 3577 3578 synchronized (mPackages) { 3579 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3580 if (obj != null) { 3581 final SettingBase ps = (SettingBase) obj; 3582 final PermissionsState permissionsState = ps.getPermissionsState(); 3583 if (permissionsState.hasPermission(permName, userId)) { 3584 return PackageManager.PERMISSION_GRANTED; 3585 } 3586 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3587 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3588 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3589 return PackageManager.PERMISSION_GRANTED; 3590 } 3591 } else { 3592 ArraySet<String> perms = mSystemPermissions.get(uid); 3593 if (perms != null) { 3594 if (perms.contains(permName)) { 3595 return PackageManager.PERMISSION_GRANTED; 3596 } 3597 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3598 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3599 return PackageManager.PERMISSION_GRANTED; 3600 } 3601 } 3602 } 3603 } 3604 3605 return PackageManager.PERMISSION_DENIED; 3606 } 3607 3608 @Override 3609 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3610 if (UserHandle.getCallingUserId() != userId) { 3611 mContext.enforceCallingPermission( 3612 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3613 "isPermissionRevokedByPolicy for user " + userId); 3614 } 3615 3616 if (checkPermission(permission, packageName, userId) 3617 == PackageManager.PERMISSION_GRANTED) { 3618 return false; 3619 } 3620 3621 final long identity = Binder.clearCallingIdentity(); 3622 try { 3623 final int flags = getPermissionFlags(permission, packageName, userId); 3624 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3625 } finally { 3626 Binder.restoreCallingIdentity(identity); 3627 } 3628 } 3629 3630 @Override 3631 public String getPermissionControllerPackageName() { 3632 synchronized (mPackages) { 3633 return mRequiredInstallerPackage; 3634 } 3635 } 3636 3637 /** 3638 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3639 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3640 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3641 * @param message the message to log on security exception 3642 */ 3643 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3644 boolean checkShell, String message) { 3645 if (userId < 0) { 3646 throw new IllegalArgumentException("Invalid userId " + userId); 3647 } 3648 if (checkShell) { 3649 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3650 } 3651 if (userId == UserHandle.getUserId(callingUid)) return; 3652 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3653 if (requireFullPermission) { 3654 mContext.enforceCallingOrSelfPermission( 3655 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3656 } else { 3657 try { 3658 mContext.enforceCallingOrSelfPermission( 3659 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3660 } catch (SecurityException se) { 3661 mContext.enforceCallingOrSelfPermission( 3662 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3663 } 3664 } 3665 } 3666 } 3667 3668 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3669 if (callingUid == Process.SHELL_UID) { 3670 if (userHandle >= 0 3671 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3672 throw new SecurityException("Shell does not have permission to access user " 3673 + userHandle); 3674 } else if (userHandle < 0) { 3675 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3676 + Debug.getCallers(3)); 3677 } 3678 } 3679 } 3680 3681 private BasePermission findPermissionTreeLP(String permName) { 3682 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3683 if (permName.startsWith(bp.name) && 3684 permName.length() > bp.name.length() && 3685 permName.charAt(bp.name.length()) == '.') { 3686 return bp; 3687 } 3688 } 3689 return null; 3690 } 3691 3692 private BasePermission checkPermissionTreeLP(String permName) { 3693 if (permName != null) { 3694 BasePermission bp = findPermissionTreeLP(permName); 3695 if (bp != null) { 3696 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3697 return bp; 3698 } 3699 throw new SecurityException("Calling uid " 3700 + Binder.getCallingUid() 3701 + " is not allowed to add to permission tree " 3702 + bp.name + " owned by uid " + bp.uid); 3703 } 3704 } 3705 throw new SecurityException("No permission tree found for " + permName); 3706 } 3707 3708 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3709 if (s1 == null) { 3710 return s2 == null; 3711 } 3712 if (s2 == null) { 3713 return false; 3714 } 3715 if (s1.getClass() != s2.getClass()) { 3716 return false; 3717 } 3718 return s1.equals(s2); 3719 } 3720 3721 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3722 if (pi1.icon != pi2.icon) return false; 3723 if (pi1.logo != pi2.logo) return false; 3724 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3725 if (!compareStrings(pi1.name, pi2.name)) return false; 3726 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3727 // We'll take care of setting this one. 3728 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3729 // These are not currently stored in settings. 3730 //if (!compareStrings(pi1.group, pi2.group)) return false; 3731 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3732 //if (pi1.labelRes != pi2.labelRes) return false; 3733 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3734 return true; 3735 } 3736 3737 int permissionInfoFootprint(PermissionInfo info) { 3738 int size = info.name.length(); 3739 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3740 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3741 return size; 3742 } 3743 3744 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3745 int size = 0; 3746 for (BasePermission perm : mSettings.mPermissions.values()) { 3747 if (perm.uid == tree.uid) { 3748 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3749 } 3750 } 3751 return size; 3752 } 3753 3754 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3755 // We calculate the max size of permissions defined by this uid and throw 3756 // if that plus the size of 'info' would exceed our stated maximum. 3757 if (tree.uid != Process.SYSTEM_UID) { 3758 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3759 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3760 throw new SecurityException("Permission tree size cap exceeded"); 3761 } 3762 } 3763 } 3764 3765 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3766 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3767 throw new SecurityException("Label must be specified in permission"); 3768 } 3769 BasePermission tree = checkPermissionTreeLP(info.name); 3770 BasePermission bp = mSettings.mPermissions.get(info.name); 3771 boolean added = bp == null; 3772 boolean changed = true; 3773 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3774 if (added) { 3775 enforcePermissionCapLocked(info, tree); 3776 bp = new BasePermission(info.name, tree.sourcePackage, 3777 BasePermission.TYPE_DYNAMIC); 3778 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3779 throw new SecurityException( 3780 "Not allowed to modify non-dynamic permission " 3781 + info.name); 3782 } else { 3783 if (bp.protectionLevel == fixedLevel 3784 && bp.perm.owner.equals(tree.perm.owner) 3785 && bp.uid == tree.uid 3786 && comparePermissionInfos(bp.perm.info, info)) { 3787 changed = false; 3788 } 3789 } 3790 bp.protectionLevel = fixedLevel; 3791 info = new PermissionInfo(info); 3792 info.protectionLevel = fixedLevel; 3793 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3794 bp.perm.info.packageName = tree.perm.info.packageName; 3795 bp.uid = tree.uid; 3796 if (added) { 3797 mSettings.mPermissions.put(info.name, bp); 3798 } 3799 if (changed) { 3800 if (!async) { 3801 mSettings.writeLPr(); 3802 } else { 3803 scheduleWriteSettingsLocked(); 3804 } 3805 } 3806 return added; 3807 } 3808 3809 @Override 3810 public boolean addPermission(PermissionInfo info) { 3811 synchronized (mPackages) { 3812 return addPermissionLocked(info, false); 3813 } 3814 } 3815 3816 @Override 3817 public boolean addPermissionAsync(PermissionInfo info) { 3818 synchronized (mPackages) { 3819 return addPermissionLocked(info, true); 3820 } 3821 } 3822 3823 @Override 3824 public void removePermission(String name) { 3825 synchronized (mPackages) { 3826 checkPermissionTreeLP(name); 3827 BasePermission bp = mSettings.mPermissions.get(name); 3828 if (bp != null) { 3829 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3830 throw new SecurityException( 3831 "Not allowed to modify non-dynamic permission " 3832 + name); 3833 } 3834 mSettings.mPermissions.remove(name); 3835 mSettings.writeLPr(); 3836 } 3837 } 3838 } 3839 3840 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3841 BasePermission bp) { 3842 int index = pkg.requestedPermissions.indexOf(bp.name); 3843 if (index == -1) { 3844 throw new SecurityException("Package " + pkg.packageName 3845 + " has not requested permission " + bp.name); 3846 } 3847 if (!bp.isRuntime() && !bp.isDevelopment()) { 3848 throw new SecurityException("Permission " + bp.name 3849 + " is not a changeable permission type"); 3850 } 3851 } 3852 3853 @Override 3854 public void grantRuntimePermission(String packageName, String name, final int userId) { 3855 if (!sUserManager.exists(userId)) { 3856 Log.e(TAG, "No such user:" + userId); 3857 return; 3858 } 3859 3860 mContext.enforceCallingOrSelfPermission( 3861 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3862 "grantRuntimePermission"); 3863 3864 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3865 true /* requireFullPermission */, true /* checkShell */, 3866 "grantRuntimePermission"); 3867 3868 final int uid; 3869 final SettingBase sb; 3870 3871 synchronized (mPackages) { 3872 final PackageParser.Package pkg = mPackages.get(packageName); 3873 if (pkg == null) { 3874 throw new IllegalArgumentException("Unknown package: " + packageName); 3875 } 3876 3877 final BasePermission bp = mSettings.mPermissions.get(name); 3878 if (bp == null) { 3879 throw new IllegalArgumentException("Unknown permission: " + name); 3880 } 3881 3882 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3883 3884 // If a permission review is required for legacy apps we represent 3885 // their permissions as always granted runtime ones since we need 3886 // to keep the review required permission flag per user while an 3887 // install permission's state is shared across all users. 3888 if (Build.PERMISSIONS_REVIEW_REQUIRED 3889 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3890 && bp.isRuntime()) { 3891 return; 3892 } 3893 3894 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3895 sb = (SettingBase) pkg.mExtras; 3896 if (sb == null) { 3897 throw new IllegalArgumentException("Unknown package: " + packageName); 3898 } 3899 3900 final PermissionsState permissionsState = sb.getPermissionsState(); 3901 3902 final int flags = permissionsState.getPermissionFlags(name, userId); 3903 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3904 throw new SecurityException("Cannot grant system fixed permission " 3905 + name + " for package " + packageName); 3906 } 3907 3908 if (bp.isDevelopment()) { 3909 // Development permissions must be handled specially, since they are not 3910 // normal runtime permissions. For now they apply to all users. 3911 if (permissionsState.grantInstallPermission(bp) != 3912 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3913 scheduleWriteSettingsLocked(); 3914 } 3915 return; 3916 } 3917 3918 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 3919 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 3920 return; 3921 } 3922 3923 final int result = permissionsState.grantRuntimePermission(bp, userId); 3924 switch (result) { 3925 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3926 return; 3927 } 3928 3929 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3930 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3931 mHandler.post(new Runnable() { 3932 @Override 3933 public void run() { 3934 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3935 } 3936 }); 3937 } 3938 break; 3939 } 3940 3941 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3942 3943 // Not critical if that is lost - app has to request again. 3944 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3945 } 3946 3947 // Only need to do this if user is initialized. Otherwise it's a new user 3948 // and there are no processes running as the user yet and there's no need 3949 // to make an expensive call to remount processes for the changed permissions. 3950 if (READ_EXTERNAL_STORAGE.equals(name) 3951 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3952 final long token = Binder.clearCallingIdentity(); 3953 try { 3954 if (sUserManager.isInitialized(userId)) { 3955 MountServiceInternal mountServiceInternal = LocalServices.getService( 3956 MountServiceInternal.class); 3957 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3958 } 3959 } finally { 3960 Binder.restoreCallingIdentity(token); 3961 } 3962 } 3963 } 3964 3965 @Override 3966 public void revokeRuntimePermission(String packageName, String name, int userId) { 3967 if (!sUserManager.exists(userId)) { 3968 Log.e(TAG, "No such user:" + userId); 3969 return; 3970 } 3971 3972 mContext.enforceCallingOrSelfPermission( 3973 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3974 "revokeRuntimePermission"); 3975 3976 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3977 true /* requireFullPermission */, true /* checkShell */, 3978 "revokeRuntimePermission"); 3979 3980 final int appId; 3981 3982 synchronized (mPackages) { 3983 final PackageParser.Package pkg = mPackages.get(packageName); 3984 if (pkg == null) { 3985 throw new IllegalArgumentException("Unknown package: " + packageName); 3986 } 3987 3988 final BasePermission bp = mSettings.mPermissions.get(name); 3989 if (bp == null) { 3990 throw new IllegalArgumentException("Unknown permission: " + name); 3991 } 3992 3993 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3994 3995 // If a permission review is required for legacy apps we represent 3996 // their permissions as always granted runtime ones since we need 3997 // to keep the review required permission flag per user while an 3998 // install permission's state is shared across all users. 3999 if (Build.PERMISSIONS_REVIEW_REQUIRED 4000 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4001 && bp.isRuntime()) { 4002 return; 4003 } 4004 4005 SettingBase sb = (SettingBase) pkg.mExtras; 4006 if (sb == null) { 4007 throw new IllegalArgumentException("Unknown package: " + packageName); 4008 } 4009 4010 final PermissionsState permissionsState = sb.getPermissionsState(); 4011 4012 final int flags = permissionsState.getPermissionFlags(name, userId); 4013 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4014 throw new SecurityException("Cannot revoke system fixed permission " 4015 + name + " for package " + packageName); 4016 } 4017 4018 if (bp.isDevelopment()) { 4019 // Development permissions must be handled specially, since they are not 4020 // normal runtime permissions. For now they apply to all users. 4021 if (permissionsState.revokeInstallPermission(bp) != 4022 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4023 scheduleWriteSettingsLocked(); 4024 } 4025 return; 4026 } 4027 4028 if (permissionsState.revokeRuntimePermission(bp, userId) == 4029 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4030 return; 4031 } 4032 4033 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4034 4035 // Critical, after this call app should never have the permission. 4036 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4037 4038 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4039 } 4040 4041 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4042 } 4043 4044 @Override 4045 public void resetRuntimePermissions() { 4046 mContext.enforceCallingOrSelfPermission( 4047 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4048 "revokeRuntimePermission"); 4049 4050 int callingUid = Binder.getCallingUid(); 4051 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4052 mContext.enforceCallingOrSelfPermission( 4053 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4054 "resetRuntimePermissions"); 4055 } 4056 4057 synchronized (mPackages) { 4058 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4059 for (int userId : UserManagerService.getInstance().getUserIds()) { 4060 final int packageCount = mPackages.size(); 4061 for (int i = 0; i < packageCount; i++) { 4062 PackageParser.Package pkg = mPackages.valueAt(i); 4063 if (!(pkg.mExtras instanceof PackageSetting)) { 4064 continue; 4065 } 4066 PackageSetting ps = (PackageSetting) pkg.mExtras; 4067 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4068 } 4069 } 4070 } 4071 } 4072 4073 @Override 4074 public int getPermissionFlags(String name, String packageName, int userId) { 4075 if (!sUserManager.exists(userId)) { 4076 return 0; 4077 } 4078 4079 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4080 4081 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4082 true /* requireFullPermission */, false /* checkShell */, 4083 "getPermissionFlags"); 4084 4085 synchronized (mPackages) { 4086 final PackageParser.Package pkg = mPackages.get(packageName); 4087 if (pkg == null) { 4088 throw new IllegalArgumentException("Unknown package: " + packageName); 4089 } 4090 4091 final BasePermission bp = mSettings.mPermissions.get(name); 4092 if (bp == null) { 4093 throw new IllegalArgumentException("Unknown permission: " + name); 4094 } 4095 4096 SettingBase sb = (SettingBase) pkg.mExtras; 4097 if (sb == null) { 4098 throw new IllegalArgumentException("Unknown package: " + packageName); 4099 } 4100 4101 PermissionsState permissionsState = sb.getPermissionsState(); 4102 return permissionsState.getPermissionFlags(name, userId); 4103 } 4104 } 4105 4106 @Override 4107 public void updatePermissionFlags(String name, String packageName, int flagMask, 4108 int flagValues, int userId) { 4109 if (!sUserManager.exists(userId)) { 4110 return; 4111 } 4112 4113 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4114 4115 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4116 true /* requireFullPermission */, true /* checkShell */, 4117 "updatePermissionFlags"); 4118 4119 // Only the system can change these flags and nothing else. 4120 if (getCallingUid() != Process.SYSTEM_UID) { 4121 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4122 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4123 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4124 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4125 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4126 } 4127 4128 synchronized (mPackages) { 4129 final PackageParser.Package pkg = mPackages.get(packageName); 4130 if (pkg == null) { 4131 throw new IllegalArgumentException("Unknown package: " + packageName); 4132 } 4133 4134 final BasePermission bp = mSettings.mPermissions.get(name); 4135 if (bp == null) { 4136 throw new IllegalArgumentException("Unknown permission: " + name); 4137 } 4138 4139 SettingBase sb = (SettingBase) pkg.mExtras; 4140 if (sb == null) { 4141 throw new IllegalArgumentException("Unknown package: " + packageName); 4142 } 4143 4144 PermissionsState permissionsState = sb.getPermissionsState(); 4145 4146 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4147 4148 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4149 // Install and runtime permissions are stored in different places, 4150 // so figure out what permission changed and persist the change. 4151 if (permissionsState.getInstallPermissionState(name) != null) { 4152 scheduleWriteSettingsLocked(); 4153 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4154 || hadState) { 4155 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4156 } 4157 } 4158 } 4159 } 4160 4161 /** 4162 * Update the permission flags for all packages and runtime permissions of a user in order 4163 * to allow device or profile owner to remove POLICY_FIXED. 4164 */ 4165 @Override 4166 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4167 if (!sUserManager.exists(userId)) { 4168 return; 4169 } 4170 4171 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4172 4173 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4174 true /* requireFullPermission */, true /* checkShell */, 4175 "updatePermissionFlagsForAllApps"); 4176 4177 // Only the system can change system fixed flags. 4178 if (getCallingUid() != Process.SYSTEM_UID) { 4179 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4180 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4181 } 4182 4183 synchronized (mPackages) { 4184 boolean changed = false; 4185 final int packageCount = mPackages.size(); 4186 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4187 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4188 SettingBase sb = (SettingBase) pkg.mExtras; 4189 if (sb == null) { 4190 continue; 4191 } 4192 PermissionsState permissionsState = sb.getPermissionsState(); 4193 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4194 userId, flagMask, flagValues); 4195 } 4196 if (changed) { 4197 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4198 } 4199 } 4200 } 4201 4202 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4203 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4204 != PackageManager.PERMISSION_GRANTED 4205 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4206 != PackageManager.PERMISSION_GRANTED) { 4207 throw new SecurityException(message + " requires " 4208 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4209 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4210 } 4211 } 4212 4213 @Override 4214 public boolean shouldShowRequestPermissionRationale(String permissionName, 4215 String packageName, int userId) { 4216 if (UserHandle.getCallingUserId() != userId) { 4217 mContext.enforceCallingPermission( 4218 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4219 "canShowRequestPermissionRationale for user " + userId); 4220 } 4221 4222 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4223 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4224 return false; 4225 } 4226 4227 if (checkPermission(permissionName, packageName, userId) 4228 == PackageManager.PERMISSION_GRANTED) { 4229 return false; 4230 } 4231 4232 final int flags; 4233 4234 final long identity = Binder.clearCallingIdentity(); 4235 try { 4236 flags = getPermissionFlags(permissionName, 4237 packageName, userId); 4238 } finally { 4239 Binder.restoreCallingIdentity(identity); 4240 } 4241 4242 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4243 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4244 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4245 4246 if ((flags & fixedFlags) != 0) { 4247 return false; 4248 } 4249 4250 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4251 } 4252 4253 @Override 4254 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4255 mContext.enforceCallingOrSelfPermission( 4256 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4257 "addOnPermissionsChangeListener"); 4258 4259 synchronized (mPackages) { 4260 mOnPermissionChangeListeners.addListenerLocked(listener); 4261 } 4262 } 4263 4264 @Override 4265 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4266 synchronized (mPackages) { 4267 mOnPermissionChangeListeners.removeListenerLocked(listener); 4268 } 4269 } 4270 4271 @Override 4272 public boolean isProtectedBroadcast(String actionName) { 4273 synchronized (mPackages) { 4274 if (mProtectedBroadcasts.contains(actionName)) { 4275 return true; 4276 } else if (actionName != null) { 4277 // TODO: remove these terrible hacks 4278 if (actionName.startsWith("android.net.netmon.lingerExpired") 4279 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4280 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4281 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4282 return true; 4283 } 4284 } 4285 } 4286 return false; 4287 } 4288 4289 @Override 4290 public int checkSignatures(String pkg1, String pkg2) { 4291 synchronized (mPackages) { 4292 final PackageParser.Package p1 = mPackages.get(pkg1); 4293 final PackageParser.Package p2 = mPackages.get(pkg2); 4294 if (p1 == null || p1.mExtras == null 4295 || p2 == null || p2.mExtras == null) { 4296 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4297 } 4298 return compareSignatures(p1.mSignatures, p2.mSignatures); 4299 } 4300 } 4301 4302 @Override 4303 public int checkUidSignatures(int uid1, int uid2) { 4304 // Map to base uids. 4305 uid1 = UserHandle.getAppId(uid1); 4306 uid2 = UserHandle.getAppId(uid2); 4307 // reader 4308 synchronized (mPackages) { 4309 Signature[] s1; 4310 Signature[] s2; 4311 Object obj = mSettings.getUserIdLPr(uid1); 4312 if (obj != null) { 4313 if (obj instanceof SharedUserSetting) { 4314 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4315 } else if (obj instanceof PackageSetting) { 4316 s1 = ((PackageSetting)obj).signatures.mSignatures; 4317 } else { 4318 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4319 } 4320 } else { 4321 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4322 } 4323 obj = mSettings.getUserIdLPr(uid2); 4324 if (obj != null) { 4325 if (obj instanceof SharedUserSetting) { 4326 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4327 } else if (obj instanceof PackageSetting) { 4328 s2 = ((PackageSetting)obj).signatures.mSignatures; 4329 } else { 4330 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4331 } 4332 } else { 4333 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4334 } 4335 return compareSignatures(s1, s2); 4336 } 4337 } 4338 4339 private void killUid(int appId, int userId, String reason) { 4340 final long identity = Binder.clearCallingIdentity(); 4341 try { 4342 IActivityManager am = ActivityManagerNative.getDefault(); 4343 if (am != null) { 4344 try { 4345 am.killUid(appId, userId, reason); 4346 } catch (RemoteException e) { 4347 /* ignore - same process */ 4348 } 4349 } 4350 } finally { 4351 Binder.restoreCallingIdentity(identity); 4352 } 4353 } 4354 4355 /** 4356 * Compares two sets of signatures. Returns: 4357 * <br /> 4358 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4359 * <br /> 4360 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4361 * <br /> 4362 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4363 * <br /> 4364 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4365 * <br /> 4366 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4367 */ 4368 static int compareSignatures(Signature[] s1, Signature[] s2) { 4369 if (s1 == null) { 4370 return s2 == null 4371 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4372 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4373 } 4374 4375 if (s2 == null) { 4376 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4377 } 4378 4379 if (s1.length != s2.length) { 4380 return PackageManager.SIGNATURE_NO_MATCH; 4381 } 4382 4383 // Since both signature sets are of size 1, we can compare without HashSets. 4384 if (s1.length == 1) { 4385 return s1[0].equals(s2[0]) ? 4386 PackageManager.SIGNATURE_MATCH : 4387 PackageManager.SIGNATURE_NO_MATCH; 4388 } 4389 4390 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4391 for (Signature sig : s1) { 4392 set1.add(sig); 4393 } 4394 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4395 for (Signature sig : s2) { 4396 set2.add(sig); 4397 } 4398 // Make sure s2 contains all signatures in s1. 4399 if (set1.equals(set2)) { 4400 return PackageManager.SIGNATURE_MATCH; 4401 } 4402 return PackageManager.SIGNATURE_NO_MATCH; 4403 } 4404 4405 /** 4406 * If the database version for this type of package (internal storage or 4407 * external storage) is less than the version where package signatures 4408 * were updated, return true. 4409 */ 4410 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4411 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4412 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4413 } 4414 4415 /** 4416 * Used for backward compatibility to make sure any packages with 4417 * certificate chains get upgraded to the new style. {@code existingSigs} 4418 * will be in the old format (since they were stored on disk from before the 4419 * system upgrade) and {@code scannedSigs} will be in the newer format. 4420 */ 4421 private int compareSignaturesCompat(PackageSignatures existingSigs, 4422 PackageParser.Package scannedPkg) { 4423 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4424 return PackageManager.SIGNATURE_NO_MATCH; 4425 } 4426 4427 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4428 for (Signature sig : existingSigs.mSignatures) { 4429 existingSet.add(sig); 4430 } 4431 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4432 for (Signature sig : scannedPkg.mSignatures) { 4433 try { 4434 Signature[] chainSignatures = sig.getChainSignatures(); 4435 for (Signature chainSig : chainSignatures) { 4436 scannedCompatSet.add(chainSig); 4437 } 4438 } catch (CertificateEncodingException e) { 4439 scannedCompatSet.add(sig); 4440 } 4441 } 4442 /* 4443 * Make sure the expanded scanned set contains all signatures in the 4444 * existing one. 4445 */ 4446 if (scannedCompatSet.equals(existingSet)) { 4447 // Migrate the old signatures to the new scheme. 4448 existingSigs.assignSignatures(scannedPkg.mSignatures); 4449 // The new KeySets will be re-added later in the scanning process. 4450 synchronized (mPackages) { 4451 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4452 } 4453 return PackageManager.SIGNATURE_MATCH; 4454 } 4455 return PackageManager.SIGNATURE_NO_MATCH; 4456 } 4457 4458 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4459 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4460 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4461 } 4462 4463 private int compareSignaturesRecover(PackageSignatures existingSigs, 4464 PackageParser.Package scannedPkg) { 4465 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4466 return PackageManager.SIGNATURE_NO_MATCH; 4467 } 4468 4469 String msg = null; 4470 try { 4471 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4472 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4473 + scannedPkg.packageName); 4474 return PackageManager.SIGNATURE_MATCH; 4475 } 4476 } catch (CertificateException e) { 4477 msg = e.getMessage(); 4478 } 4479 4480 logCriticalInfo(Log.INFO, 4481 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4482 return PackageManager.SIGNATURE_NO_MATCH; 4483 } 4484 4485 @Override 4486 public List<String> getAllPackages() { 4487 synchronized (mPackages) { 4488 return new ArrayList<String>(mPackages.keySet()); 4489 } 4490 } 4491 4492 @Override 4493 public String[] getPackagesForUid(int uid) { 4494 uid = UserHandle.getAppId(uid); 4495 // reader 4496 synchronized (mPackages) { 4497 Object obj = mSettings.getUserIdLPr(uid); 4498 if (obj instanceof SharedUserSetting) { 4499 final SharedUserSetting sus = (SharedUserSetting) obj; 4500 final int N = sus.packages.size(); 4501 final String[] res = new String[N]; 4502 final Iterator<PackageSetting> it = sus.packages.iterator(); 4503 int i = 0; 4504 while (it.hasNext()) { 4505 res[i++] = it.next().name; 4506 } 4507 return res; 4508 } else if (obj instanceof PackageSetting) { 4509 final PackageSetting ps = (PackageSetting) obj; 4510 return new String[] { ps.name }; 4511 } 4512 } 4513 return null; 4514 } 4515 4516 @Override 4517 public String getNameForUid(int uid) { 4518 // reader 4519 synchronized (mPackages) { 4520 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4521 if (obj instanceof SharedUserSetting) { 4522 final SharedUserSetting sus = (SharedUserSetting) obj; 4523 return sus.name + ":" + sus.userId; 4524 } else if (obj instanceof PackageSetting) { 4525 final PackageSetting ps = (PackageSetting) obj; 4526 return ps.name; 4527 } 4528 } 4529 return null; 4530 } 4531 4532 @Override 4533 public int getUidForSharedUser(String sharedUserName) { 4534 if(sharedUserName == null) { 4535 return -1; 4536 } 4537 // reader 4538 synchronized (mPackages) { 4539 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4540 if (suid == null) { 4541 return -1; 4542 } 4543 return suid.userId; 4544 } 4545 } 4546 4547 @Override 4548 public int getFlagsForUid(int uid) { 4549 synchronized (mPackages) { 4550 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4551 if (obj instanceof SharedUserSetting) { 4552 final SharedUserSetting sus = (SharedUserSetting) obj; 4553 return sus.pkgFlags; 4554 } else if (obj instanceof PackageSetting) { 4555 final PackageSetting ps = (PackageSetting) obj; 4556 return ps.pkgFlags; 4557 } 4558 } 4559 return 0; 4560 } 4561 4562 @Override 4563 public int getPrivateFlagsForUid(int uid) { 4564 synchronized (mPackages) { 4565 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4566 if (obj instanceof SharedUserSetting) { 4567 final SharedUserSetting sus = (SharedUserSetting) obj; 4568 return sus.pkgPrivateFlags; 4569 } else if (obj instanceof PackageSetting) { 4570 final PackageSetting ps = (PackageSetting) obj; 4571 return ps.pkgPrivateFlags; 4572 } 4573 } 4574 return 0; 4575 } 4576 4577 @Override 4578 public boolean isUidPrivileged(int uid) { 4579 uid = UserHandle.getAppId(uid); 4580 // reader 4581 synchronized (mPackages) { 4582 Object obj = mSettings.getUserIdLPr(uid); 4583 if (obj instanceof SharedUserSetting) { 4584 final SharedUserSetting sus = (SharedUserSetting) obj; 4585 final Iterator<PackageSetting> it = sus.packages.iterator(); 4586 while (it.hasNext()) { 4587 if (it.next().isPrivileged()) { 4588 return true; 4589 } 4590 } 4591 } else if (obj instanceof PackageSetting) { 4592 final PackageSetting ps = (PackageSetting) obj; 4593 return ps.isPrivileged(); 4594 } 4595 } 4596 return false; 4597 } 4598 4599 @Override 4600 public String[] getAppOpPermissionPackages(String permissionName) { 4601 synchronized (mPackages) { 4602 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4603 if (pkgs == null) { 4604 return null; 4605 } 4606 return pkgs.toArray(new String[pkgs.size()]); 4607 } 4608 } 4609 4610 @Override 4611 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4612 int flags, int userId) { 4613 if (!sUserManager.exists(userId)) return null; 4614 flags = updateFlagsForResolve(flags, userId, intent); 4615 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4616 false /* requireFullPermission */, false /* checkShell */, "resolve intent"); 4617 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4618 userId); 4619 final ResolveInfo bestChoice = 4620 chooseBestActivity(intent, resolvedType, flags, query, userId); 4621 4622 if (isEphemeralAllowed(intent, query, userId)) { 4623 final EphemeralResolveInfo ai = 4624 getEphemeralResolveInfo(intent, resolvedType, userId); 4625 if (ai != null) { 4626 if (DEBUG_EPHEMERAL) { 4627 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4628 } 4629 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4630 bestChoice.ephemeralResolveInfo = ai; 4631 } 4632 } 4633 return bestChoice; 4634 } 4635 4636 @Override 4637 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4638 IntentFilter filter, int match, ComponentName activity) { 4639 final int userId = UserHandle.getCallingUserId(); 4640 if (DEBUG_PREFERRED) { 4641 Log.v(TAG, "setLastChosenActivity intent=" + intent 4642 + " resolvedType=" + resolvedType 4643 + " flags=" + flags 4644 + " filter=" + filter 4645 + " match=" + match 4646 + " activity=" + activity); 4647 filter.dump(new PrintStreamPrinter(System.out), " "); 4648 } 4649 intent.setComponent(null); 4650 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4651 userId); 4652 // Find any earlier preferred or last chosen entries and nuke them 4653 findPreferredActivity(intent, resolvedType, 4654 flags, query, 0, false, true, false, userId); 4655 // Add the new activity as the last chosen for this filter 4656 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4657 "Setting last chosen"); 4658 } 4659 4660 @Override 4661 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4662 final int userId = UserHandle.getCallingUserId(); 4663 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4664 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4665 userId); 4666 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4667 false, false, false, userId); 4668 } 4669 4670 4671 private boolean isEphemeralAllowed( 4672 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4673 // Short circuit and return early if possible. 4674 if (DISABLE_EPHEMERAL_APPS) { 4675 return false; 4676 } 4677 final int callingUser = UserHandle.getCallingUserId(); 4678 if (callingUser != UserHandle.USER_SYSTEM) { 4679 return false; 4680 } 4681 if (mEphemeralResolverConnection == null) { 4682 return false; 4683 } 4684 if (intent.getComponent() != null) { 4685 return false; 4686 } 4687 if (intent.getPackage() != null) { 4688 return false; 4689 } 4690 final boolean isWebUri = hasWebURI(intent); 4691 if (!isWebUri) { 4692 return false; 4693 } 4694 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4695 synchronized (mPackages) { 4696 final int count = resolvedActivites.size(); 4697 for (int n = 0; n < count; n++) { 4698 ResolveInfo info = resolvedActivites.get(n); 4699 String packageName = info.activityInfo.packageName; 4700 PackageSetting ps = mSettings.mPackages.get(packageName); 4701 if (ps != null) { 4702 // Try to get the status from User settings first 4703 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4704 int status = (int) (packedStatus >> 32); 4705 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4706 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4707 if (DEBUG_EPHEMERAL) { 4708 Slog.v(TAG, "DENY ephemeral apps;" 4709 + " pkg: " + packageName + ", status: " + status); 4710 } 4711 return false; 4712 } 4713 } 4714 } 4715 } 4716 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4717 return true; 4718 } 4719 4720 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4721 int userId) { 4722 MessageDigest digest = null; 4723 try { 4724 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4725 } catch (NoSuchAlgorithmException e) { 4726 // If we can't create a digest, ignore ephemeral apps. 4727 return null; 4728 } 4729 4730 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4731 final byte[] digestBytes = digest.digest(hostBytes); 4732 int shaPrefix = 4733 digestBytes[0] << 24 4734 | digestBytes[1] << 16 4735 | digestBytes[2] << 8 4736 | digestBytes[3] << 0; 4737 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4738 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4739 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4740 // No hash prefix match; there are no ephemeral apps for this domain. 4741 return null; 4742 } 4743 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4744 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4745 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4746 continue; 4747 } 4748 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4749 // No filters; this should never happen. 4750 if (filters.isEmpty()) { 4751 continue; 4752 } 4753 // We have a domain match; resolve the filters to see if anything matches. 4754 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4755 for (int j = filters.size() - 1; j >= 0; --j) { 4756 final EphemeralResolveIntentInfo intentInfo = 4757 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4758 ephemeralResolver.addFilter(intentInfo); 4759 } 4760 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4761 intent, resolvedType, false /*defaultOnly*/, userId); 4762 if (!matchedResolveInfoList.isEmpty()) { 4763 return matchedResolveInfoList.get(0); 4764 } 4765 } 4766 // Hash or filter mis-match; no ephemeral apps for this domain. 4767 return null; 4768 } 4769 4770 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4771 int flags, List<ResolveInfo> query, int userId) { 4772 if (query != null) { 4773 final int N = query.size(); 4774 if (N == 1) { 4775 return query.get(0); 4776 } else if (N > 1) { 4777 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4778 // If there is more than one activity with the same priority, 4779 // then let the user decide between them. 4780 ResolveInfo r0 = query.get(0); 4781 ResolveInfo r1 = query.get(1); 4782 if (DEBUG_INTENT_MATCHING || debug) { 4783 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4784 + r1.activityInfo.name + "=" + r1.priority); 4785 } 4786 // If the first activity has a higher priority, or a different 4787 // default, then it is always desirable to pick it. 4788 if (r0.priority != r1.priority 4789 || r0.preferredOrder != r1.preferredOrder 4790 || r0.isDefault != r1.isDefault) { 4791 return query.get(0); 4792 } 4793 // If we have saved a preference for a preferred activity for 4794 // this Intent, use that. 4795 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4796 flags, query, r0.priority, true, false, debug, userId); 4797 if (ri != null) { 4798 return ri; 4799 } 4800 ri = new ResolveInfo(mResolveInfo); 4801 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4802 ri.activityInfo.applicationInfo = new ApplicationInfo( 4803 ri.activityInfo.applicationInfo); 4804 if (userId != 0) { 4805 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4806 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4807 } 4808 // Make sure that the resolver is displayable in car mode 4809 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4810 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4811 return ri; 4812 } 4813 } 4814 return null; 4815 } 4816 4817 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4818 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4819 final int N = query.size(); 4820 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4821 .get(userId); 4822 // Get the list of persistent preferred activities that handle the intent 4823 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4824 List<PersistentPreferredActivity> pprefs = ppir != null 4825 ? ppir.queryIntent(intent, resolvedType, 4826 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4827 : null; 4828 if (pprefs != null && pprefs.size() > 0) { 4829 final int M = pprefs.size(); 4830 for (int i=0; i<M; i++) { 4831 final PersistentPreferredActivity ppa = pprefs.get(i); 4832 if (DEBUG_PREFERRED || debug) { 4833 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4834 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4835 + "\n component=" + ppa.mComponent); 4836 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4837 } 4838 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4839 flags | MATCH_DISABLED_COMPONENTS, userId); 4840 if (DEBUG_PREFERRED || debug) { 4841 Slog.v(TAG, "Found persistent preferred activity:"); 4842 if (ai != null) { 4843 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4844 } else { 4845 Slog.v(TAG, " null"); 4846 } 4847 } 4848 if (ai == null) { 4849 // This previously registered persistent preferred activity 4850 // component is no longer known. Ignore it and do NOT remove it. 4851 continue; 4852 } 4853 for (int j=0; j<N; j++) { 4854 final ResolveInfo ri = query.get(j); 4855 if (!ri.activityInfo.applicationInfo.packageName 4856 .equals(ai.applicationInfo.packageName)) { 4857 continue; 4858 } 4859 if (!ri.activityInfo.name.equals(ai.name)) { 4860 continue; 4861 } 4862 // Found a persistent preference that can handle the intent. 4863 if (DEBUG_PREFERRED || debug) { 4864 Slog.v(TAG, "Returning persistent preferred activity: " + 4865 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4866 } 4867 return ri; 4868 } 4869 } 4870 } 4871 return null; 4872 } 4873 4874 // TODO: handle preferred activities missing while user has amnesia 4875 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4876 List<ResolveInfo> query, int priority, boolean always, 4877 boolean removeMatches, boolean debug, int userId) { 4878 if (!sUserManager.exists(userId)) return null; 4879 flags = updateFlagsForResolve(flags, userId, intent); 4880 // writer 4881 synchronized (mPackages) { 4882 if (intent.getSelector() != null) { 4883 intent = intent.getSelector(); 4884 } 4885 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4886 4887 // Try to find a matching persistent preferred activity. 4888 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4889 debug, userId); 4890 4891 // If a persistent preferred activity matched, use it. 4892 if (pri != null) { 4893 return pri; 4894 } 4895 4896 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4897 // Get the list of preferred activities that handle the intent 4898 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4899 List<PreferredActivity> prefs = pir != null 4900 ? pir.queryIntent(intent, resolvedType, 4901 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4902 : null; 4903 if (prefs != null && prefs.size() > 0) { 4904 boolean changed = false; 4905 try { 4906 // First figure out how good the original match set is. 4907 // We will only allow preferred activities that came 4908 // from the same match quality. 4909 int match = 0; 4910 4911 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4912 4913 final int N = query.size(); 4914 for (int j=0; j<N; j++) { 4915 final ResolveInfo ri = query.get(j); 4916 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4917 + ": 0x" + Integer.toHexString(match)); 4918 if (ri.match > match) { 4919 match = ri.match; 4920 } 4921 } 4922 4923 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4924 + Integer.toHexString(match)); 4925 4926 match &= IntentFilter.MATCH_CATEGORY_MASK; 4927 final int M = prefs.size(); 4928 for (int i=0; i<M; i++) { 4929 final PreferredActivity pa = prefs.get(i); 4930 if (DEBUG_PREFERRED || debug) { 4931 Slog.v(TAG, "Checking PreferredActivity ds=" 4932 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4933 + "\n component=" + pa.mPref.mComponent); 4934 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4935 } 4936 if (pa.mPref.mMatch != match) { 4937 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4938 + Integer.toHexString(pa.mPref.mMatch)); 4939 continue; 4940 } 4941 // If it's not an "always" type preferred activity and that's what we're 4942 // looking for, skip it. 4943 if (always && !pa.mPref.mAlways) { 4944 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4945 continue; 4946 } 4947 final ActivityInfo ai = getActivityInfo( 4948 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 4949 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 4950 userId); 4951 if (DEBUG_PREFERRED || debug) { 4952 Slog.v(TAG, "Found preferred activity:"); 4953 if (ai != null) { 4954 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4955 } else { 4956 Slog.v(TAG, " null"); 4957 } 4958 } 4959 if (ai == null) { 4960 // This previously registered preferred activity 4961 // component is no longer known. Most likely an update 4962 // to the app was installed and in the new version this 4963 // component no longer exists. Clean it up by removing 4964 // it from the preferred activities list, and skip it. 4965 Slog.w(TAG, "Removing dangling preferred activity: " 4966 + pa.mPref.mComponent); 4967 pir.removeFilter(pa); 4968 changed = true; 4969 continue; 4970 } 4971 for (int j=0; j<N; j++) { 4972 final ResolveInfo ri = query.get(j); 4973 if (!ri.activityInfo.applicationInfo.packageName 4974 .equals(ai.applicationInfo.packageName)) { 4975 continue; 4976 } 4977 if (!ri.activityInfo.name.equals(ai.name)) { 4978 continue; 4979 } 4980 4981 if (removeMatches) { 4982 pir.removeFilter(pa); 4983 changed = true; 4984 if (DEBUG_PREFERRED) { 4985 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4986 } 4987 break; 4988 } 4989 4990 // Okay we found a previously set preferred or last chosen app. 4991 // If the result set is different from when this 4992 // was created, we need to clear it and re-ask the 4993 // user their preference, if we're looking for an "always" type entry. 4994 if (always && !pa.mPref.sameSet(query)) { 4995 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4996 + intent + " type " + resolvedType); 4997 if (DEBUG_PREFERRED) { 4998 Slog.v(TAG, "Removing preferred activity since set changed " 4999 + pa.mPref.mComponent); 5000 } 5001 pir.removeFilter(pa); 5002 // Re-add the filter as a "last chosen" entry (!always) 5003 PreferredActivity lastChosen = new PreferredActivity( 5004 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5005 pir.addFilter(lastChosen); 5006 changed = true; 5007 return null; 5008 } 5009 5010 // Yay! Either the set matched or we're looking for the last chosen 5011 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5012 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5013 return ri; 5014 } 5015 } 5016 } finally { 5017 if (changed) { 5018 if (DEBUG_PREFERRED) { 5019 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5020 } 5021 scheduleWritePackageRestrictionsLocked(userId); 5022 } 5023 } 5024 } 5025 } 5026 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5027 return null; 5028 } 5029 5030 /* 5031 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5032 */ 5033 @Override 5034 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5035 int targetUserId) { 5036 mContext.enforceCallingOrSelfPermission( 5037 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5038 List<CrossProfileIntentFilter> matches = 5039 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5040 if (matches != null) { 5041 int size = matches.size(); 5042 for (int i = 0; i < size; i++) { 5043 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5044 } 5045 } 5046 if (hasWebURI(intent)) { 5047 // cross-profile app linking works only towards the parent. 5048 final UserInfo parent = getProfileParent(sourceUserId); 5049 synchronized(mPackages) { 5050 int flags = updateFlagsForResolve(0, parent.id, intent); 5051 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5052 intent, resolvedType, flags, sourceUserId, parent.id); 5053 return xpDomainInfo != null; 5054 } 5055 } 5056 return false; 5057 } 5058 5059 private UserInfo getProfileParent(int userId) { 5060 final long identity = Binder.clearCallingIdentity(); 5061 try { 5062 return sUserManager.getProfileParent(userId); 5063 } finally { 5064 Binder.restoreCallingIdentity(identity); 5065 } 5066 } 5067 5068 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5069 String resolvedType, int userId) { 5070 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5071 if (resolver != null) { 5072 return resolver.queryIntent(intent, resolvedType, false, userId); 5073 } 5074 return null; 5075 } 5076 5077 @Override 5078 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5079 String resolvedType, int flags, int userId) { 5080 return new ParceledListSlice<>( 5081 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5082 } 5083 5084 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5085 String resolvedType, int flags, int userId) { 5086 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5087 flags = updateFlagsForResolve(flags, userId, intent); 5088 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5089 false /* requireFullPermission */, false /* checkShell */, 5090 "query intent activities"); 5091 ComponentName comp = intent.getComponent(); 5092 if (comp == null) { 5093 if (intent.getSelector() != null) { 5094 intent = intent.getSelector(); 5095 comp = intent.getComponent(); 5096 } 5097 } 5098 5099 if (comp != null) { 5100 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5101 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5102 if (ai != null) { 5103 final ResolveInfo ri = new ResolveInfo(); 5104 ri.activityInfo = ai; 5105 list.add(ri); 5106 } 5107 return list; 5108 } 5109 5110 // reader 5111 synchronized (mPackages) { 5112 final String pkgName = intent.getPackage(); 5113 if (pkgName == null) { 5114 List<CrossProfileIntentFilter> matchingFilters = 5115 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5116 // Check for results that need to skip the current profile. 5117 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5118 resolvedType, flags, userId); 5119 if (xpResolveInfo != null) { 5120 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5121 result.add(xpResolveInfo); 5122 return filterIfNotSystemUser(result, userId); 5123 } 5124 5125 // Check for results in the current profile. 5126 List<ResolveInfo> result = mActivities.queryIntent( 5127 intent, resolvedType, flags, userId); 5128 result = filterIfNotSystemUser(result, userId); 5129 5130 // Check for cross profile results. 5131 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5132 xpResolveInfo = queryCrossProfileIntents( 5133 matchingFilters, intent, resolvedType, flags, userId, 5134 hasNonNegativePriorityResult); 5135 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5136 boolean isVisibleToUser = filterIfNotSystemUser( 5137 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5138 if (isVisibleToUser) { 5139 result.add(xpResolveInfo); 5140 Collections.sort(result, mResolvePrioritySorter); 5141 } 5142 } 5143 if (hasWebURI(intent)) { 5144 CrossProfileDomainInfo xpDomainInfo = null; 5145 final UserInfo parent = getProfileParent(userId); 5146 if (parent != null) { 5147 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5148 flags, userId, parent.id); 5149 } 5150 if (xpDomainInfo != null) { 5151 if (xpResolveInfo != null) { 5152 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5153 // in the result. 5154 result.remove(xpResolveInfo); 5155 } 5156 if (result.size() == 0) { 5157 result.add(xpDomainInfo.resolveInfo); 5158 return result; 5159 } 5160 } else if (result.size() <= 1) { 5161 return result; 5162 } 5163 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5164 xpDomainInfo, userId); 5165 Collections.sort(result, mResolvePrioritySorter); 5166 } 5167 return result; 5168 } 5169 final PackageParser.Package pkg = mPackages.get(pkgName); 5170 if (pkg != null) { 5171 return filterIfNotSystemUser( 5172 mActivities.queryIntentForPackage( 5173 intent, resolvedType, flags, pkg.activities, userId), 5174 userId); 5175 } 5176 return new ArrayList<ResolveInfo>(); 5177 } 5178 } 5179 5180 private static class CrossProfileDomainInfo { 5181 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5182 ResolveInfo resolveInfo; 5183 /* Best domain verification status of the activities found in the other profile */ 5184 int bestDomainVerificationStatus; 5185 } 5186 5187 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5188 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5189 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5190 sourceUserId)) { 5191 return null; 5192 } 5193 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5194 resolvedType, flags, parentUserId); 5195 5196 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5197 return null; 5198 } 5199 CrossProfileDomainInfo result = null; 5200 int size = resultTargetUser.size(); 5201 for (int i = 0; i < size; i++) { 5202 ResolveInfo riTargetUser = resultTargetUser.get(i); 5203 // Intent filter verification is only for filters that specify a host. So don't return 5204 // those that handle all web uris. 5205 if (riTargetUser.handleAllWebDataURI) { 5206 continue; 5207 } 5208 String packageName = riTargetUser.activityInfo.packageName; 5209 PackageSetting ps = mSettings.mPackages.get(packageName); 5210 if (ps == null) { 5211 continue; 5212 } 5213 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5214 int status = (int)(verificationState >> 32); 5215 if (result == null) { 5216 result = new CrossProfileDomainInfo(); 5217 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5218 sourceUserId, parentUserId); 5219 result.bestDomainVerificationStatus = status; 5220 } else { 5221 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5222 result.bestDomainVerificationStatus); 5223 } 5224 } 5225 // Don't consider matches with status NEVER across profiles. 5226 if (result != null && result.bestDomainVerificationStatus 5227 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5228 return null; 5229 } 5230 return result; 5231 } 5232 5233 /** 5234 * Verification statuses are ordered from the worse to the best, except for 5235 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5236 */ 5237 private int bestDomainVerificationStatus(int status1, int status2) { 5238 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5239 return status2; 5240 } 5241 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5242 return status1; 5243 } 5244 return (int) MathUtils.max(status1, status2); 5245 } 5246 5247 private boolean isUserEnabled(int userId) { 5248 long callingId = Binder.clearCallingIdentity(); 5249 try { 5250 UserInfo userInfo = sUserManager.getUserInfo(userId); 5251 return userInfo != null && userInfo.isEnabled(); 5252 } finally { 5253 Binder.restoreCallingIdentity(callingId); 5254 } 5255 } 5256 5257 /** 5258 * Filter out activities with systemUserOnly flag set, when current user is not System. 5259 * 5260 * @return filtered list 5261 */ 5262 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5263 if (userId == UserHandle.USER_SYSTEM) { 5264 return resolveInfos; 5265 } 5266 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5267 ResolveInfo info = resolveInfos.get(i); 5268 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5269 resolveInfos.remove(i); 5270 } 5271 } 5272 return resolveInfos; 5273 } 5274 5275 /** 5276 * @param resolveInfos list of resolve infos in descending priority order 5277 * @return if the list contains a resolve info with non-negative priority 5278 */ 5279 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5280 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5281 } 5282 5283 private static boolean hasWebURI(Intent intent) { 5284 if (intent.getData() == null) { 5285 return false; 5286 } 5287 final String scheme = intent.getScheme(); 5288 if (TextUtils.isEmpty(scheme)) { 5289 return false; 5290 } 5291 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5292 } 5293 5294 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5295 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5296 int userId) { 5297 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5298 5299 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5300 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5301 candidates.size()); 5302 } 5303 5304 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5305 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5306 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5307 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5308 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5309 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5310 5311 synchronized (mPackages) { 5312 final int count = candidates.size(); 5313 // First, try to use linked apps. Partition the candidates into four lists: 5314 // one for the final results, one for the "do not use ever", one for "undefined status" 5315 // and finally one for "browser app type". 5316 for (int n=0; n<count; n++) { 5317 ResolveInfo info = candidates.get(n); 5318 String packageName = info.activityInfo.packageName; 5319 PackageSetting ps = mSettings.mPackages.get(packageName); 5320 if (ps != null) { 5321 // Add to the special match all list (Browser use case) 5322 if (info.handleAllWebDataURI) { 5323 matchAllList.add(info); 5324 continue; 5325 } 5326 // Try to get the status from User settings first 5327 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5328 int status = (int)(packedStatus >> 32); 5329 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5330 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5331 if (DEBUG_DOMAIN_VERIFICATION) { 5332 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5333 + " : linkgen=" + linkGeneration); 5334 } 5335 // Use link-enabled generation as preferredOrder, i.e. 5336 // prefer newly-enabled over earlier-enabled. 5337 info.preferredOrder = linkGeneration; 5338 alwaysList.add(info); 5339 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5340 if (DEBUG_DOMAIN_VERIFICATION) { 5341 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5342 } 5343 neverList.add(info); 5344 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5345 if (DEBUG_DOMAIN_VERIFICATION) { 5346 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5347 } 5348 alwaysAskList.add(info); 5349 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5350 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5351 if (DEBUG_DOMAIN_VERIFICATION) { 5352 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5353 } 5354 undefinedList.add(info); 5355 } 5356 } 5357 } 5358 5359 // We'll want to include browser possibilities in a few cases 5360 boolean includeBrowser = false; 5361 5362 // First try to add the "always" resolution(s) for the current user, if any 5363 if (alwaysList.size() > 0) { 5364 result.addAll(alwaysList); 5365 } else { 5366 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5367 result.addAll(undefinedList); 5368 // Maybe add one for the other profile. 5369 if (xpDomainInfo != null && ( 5370 xpDomainInfo.bestDomainVerificationStatus 5371 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5372 result.add(xpDomainInfo.resolveInfo); 5373 } 5374 includeBrowser = true; 5375 } 5376 5377 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5378 // If there were 'always' entries their preferred order has been set, so we also 5379 // back that off to make the alternatives equivalent 5380 if (alwaysAskList.size() > 0) { 5381 for (ResolveInfo i : result) { 5382 i.preferredOrder = 0; 5383 } 5384 result.addAll(alwaysAskList); 5385 includeBrowser = true; 5386 } 5387 5388 if (includeBrowser) { 5389 // Also add browsers (all of them or only the default one) 5390 if (DEBUG_DOMAIN_VERIFICATION) { 5391 Slog.v(TAG, " ...including browsers in candidate set"); 5392 } 5393 if ((matchFlags & MATCH_ALL) != 0) { 5394 result.addAll(matchAllList); 5395 } else { 5396 // Browser/generic handling case. If there's a default browser, go straight 5397 // to that (but only if there is no other higher-priority match). 5398 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5399 int maxMatchPrio = 0; 5400 ResolveInfo defaultBrowserMatch = null; 5401 final int numCandidates = matchAllList.size(); 5402 for (int n = 0; n < numCandidates; n++) { 5403 ResolveInfo info = matchAllList.get(n); 5404 // track the highest overall match priority... 5405 if (info.priority > maxMatchPrio) { 5406 maxMatchPrio = info.priority; 5407 } 5408 // ...and the highest-priority default browser match 5409 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5410 if (defaultBrowserMatch == null 5411 || (defaultBrowserMatch.priority < info.priority)) { 5412 if (debug) { 5413 Slog.v(TAG, "Considering default browser match " + info); 5414 } 5415 defaultBrowserMatch = info; 5416 } 5417 } 5418 } 5419 if (defaultBrowserMatch != null 5420 && defaultBrowserMatch.priority >= maxMatchPrio 5421 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5422 { 5423 if (debug) { 5424 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5425 } 5426 result.add(defaultBrowserMatch); 5427 } else { 5428 result.addAll(matchAllList); 5429 } 5430 } 5431 5432 // If there is nothing selected, add all candidates and remove the ones that the user 5433 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5434 if (result.size() == 0) { 5435 result.addAll(candidates); 5436 result.removeAll(neverList); 5437 } 5438 } 5439 } 5440 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5441 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5442 result.size()); 5443 for (ResolveInfo info : result) { 5444 Slog.v(TAG, " + " + info.activityInfo); 5445 } 5446 } 5447 return result; 5448 } 5449 5450 // Returns a packed value as a long: 5451 // 5452 // high 'int'-sized word: link status: undefined/ask/never/always. 5453 // low 'int'-sized word: relative priority among 'always' results. 5454 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5455 long result = ps.getDomainVerificationStatusForUser(userId); 5456 // if none available, get the master status 5457 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5458 if (ps.getIntentFilterVerificationInfo() != null) { 5459 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5460 } 5461 } 5462 return result; 5463 } 5464 5465 private ResolveInfo querySkipCurrentProfileIntents( 5466 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5467 int flags, int sourceUserId) { 5468 if (matchingFilters != null) { 5469 int size = matchingFilters.size(); 5470 for (int i = 0; i < size; i ++) { 5471 CrossProfileIntentFilter filter = matchingFilters.get(i); 5472 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5473 // Checking if there are activities in the target user that can handle the 5474 // intent. 5475 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5476 resolvedType, flags, sourceUserId); 5477 if (resolveInfo != null) { 5478 return resolveInfo; 5479 } 5480 } 5481 } 5482 } 5483 return null; 5484 } 5485 5486 // Return matching ResolveInfo in target user if any. 5487 private ResolveInfo queryCrossProfileIntents( 5488 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5489 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5490 if (matchingFilters != null) { 5491 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5492 // match the same intent. For performance reasons, it is better not to 5493 // run queryIntent twice for the same userId 5494 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5495 int size = matchingFilters.size(); 5496 for (int i = 0; i < size; i++) { 5497 CrossProfileIntentFilter filter = matchingFilters.get(i); 5498 int targetUserId = filter.getTargetUserId(); 5499 boolean skipCurrentProfile = 5500 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5501 boolean skipCurrentProfileIfNoMatchFound = 5502 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5503 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5504 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5505 // Checking if there are activities in the target user that can handle the 5506 // intent. 5507 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5508 resolvedType, flags, sourceUserId); 5509 if (resolveInfo != null) return resolveInfo; 5510 alreadyTriedUserIds.put(targetUserId, true); 5511 } 5512 } 5513 } 5514 return null; 5515 } 5516 5517 /** 5518 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5519 * will forward the intent to the filter's target user. 5520 * Otherwise, returns null. 5521 */ 5522 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5523 String resolvedType, int flags, int sourceUserId) { 5524 int targetUserId = filter.getTargetUserId(); 5525 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5526 resolvedType, flags, targetUserId); 5527 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5528 // If all the matches in the target profile are suspended, return null. 5529 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5530 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5531 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5532 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5533 targetUserId); 5534 } 5535 } 5536 } 5537 return null; 5538 } 5539 5540 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5541 int sourceUserId, int targetUserId) { 5542 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5543 long ident = Binder.clearCallingIdentity(); 5544 boolean targetIsProfile; 5545 try { 5546 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5547 } finally { 5548 Binder.restoreCallingIdentity(ident); 5549 } 5550 String className; 5551 if (targetIsProfile) { 5552 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5553 } else { 5554 className = FORWARD_INTENT_TO_PARENT; 5555 } 5556 ComponentName forwardingActivityComponentName = new ComponentName( 5557 mAndroidApplication.packageName, className); 5558 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5559 sourceUserId); 5560 if (!targetIsProfile) { 5561 forwardingActivityInfo.showUserIcon = targetUserId; 5562 forwardingResolveInfo.noResourceId = true; 5563 } 5564 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5565 forwardingResolveInfo.priority = 0; 5566 forwardingResolveInfo.preferredOrder = 0; 5567 forwardingResolveInfo.match = 0; 5568 forwardingResolveInfo.isDefault = true; 5569 forwardingResolveInfo.filter = filter; 5570 forwardingResolveInfo.targetUserId = targetUserId; 5571 return forwardingResolveInfo; 5572 } 5573 5574 @Override 5575 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5576 Intent[] specifics, String[] specificTypes, Intent intent, 5577 String resolvedType, int flags, int userId) { 5578 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5579 specificTypes, intent, resolvedType, flags, userId)); 5580 } 5581 5582 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5583 Intent[] specifics, String[] specificTypes, Intent intent, 5584 String resolvedType, int flags, int userId) { 5585 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5586 flags = updateFlagsForResolve(flags, userId, intent); 5587 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5588 false /* requireFullPermission */, false /* checkShell */, 5589 "query intent activity options"); 5590 final String resultsAction = intent.getAction(); 5591 5592 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5593 | PackageManager.GET_RESOLVED_FILTER, userId); 5594 5595 if (DEBUG_INTENT_MATCHING) { 5596 Log.v(TAG, "Query " + intent + ": " + results); 5597 } 5598 5599 int specificsPos = 0; 5600 int N; 5601 5602 // todo: note that the algorithm used here is O(N^2). This 5603 // isn't a problem in our current environment, but if we start running 5604 // into situations where we have more than 5 or 10 matches then this 5605 // should probably be changed to something smarter... 5606 5607 // First we go through and resolve each of the specific items 5608 // that were supplied, taking care of removing any corresponding 5609 // duplicate items in the generic resolve list. 5610 if (specifics != null) { 5611 for (int i=0; i<specifics.length; i++) { 5612 final Intent sintent = specifics[i]; 5613 if (sintent == null) { 5614 continue; 5615 } 5616 5617 if (DEBUG_INTENT_MATCHING) { 5618 Log.v(TAG, "Specific #" + i + ": " + sintent); 5619 } 5620 5621 String action = sintent.getAction(); 5622 if (resultsAction != null && resultsAction.equals(action)) { 5623 // If this action was explicitly requested, then don't 5624 // remove things that have it. 5625 action = null; 5626 } 5627 5628 ResolveInfo ri = null; 5629 ActivityInfo ai = null; 5630 5631 ComponentName comp = sintent.getComponent(); 5632 if (comp == null) { 5633 ri = resolveIntent( 5634 sintent, 5635 specificTypes != null ? specificTypes[i] : null, 5636 flags, userId); 5637 if (ri == null) { 5638 continue; 5639 } 5640 if (ri == mResolveInfo) { 5641 // ACK! Must do something better with this. 5642 } 5643 ai = ri.activityInfo; 5644 comp = new ComponentName(ai.applicationInfo.packageName, 5645 ai.name); 5646 } else { 5647 ai = getActivityInfo(comp, flags, userId); 5648 if (ai == null) { 5649 continue; 5650 } 5651 } 5652 5653 // Look for any generic query activities that are duplicates 5654 // of this specific one, and remove them from the results. 5655 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5656 N = results.size(); 5657 int j; 5658 for (j=specificsPos; j<N; j++) { 5659 ResolveInfo sri = results.get(j); 5660 if ((sri.activityInfo.name.equals(comp.getClassName()) 5661 && sri.activityInfo.applicationInfo.packageName.equals( 5662 comp.getPackageName())) 5663 || (action != null && sri.filter.matchAction(action))) { 5664 results.remove(j); 5665 if (DEBUG_INTENT_MATCHING) Log.v( 5666 TAG, "Removing duplicate item from " + j 5667 + " due to specific " + specificsPos); 5668 if (ri == null) { 5669 ri = sri; 5670 } 5671 j--; 5672 N--; 5673 } 5674 } 5675 5676 // Add this specific item to its proper place. 5677 if (ri == null) { 5678 ri = new ResolveInfo(); 5679 ri.activityInfo = ai; 5680 } 5681 results.add(specificsPos, ri); 5682 ri.specificIndex = i; 5683 specificsPos++; 5684 } 5685 } 5686 5687 // Now we go through the remaining generic results and remove any 5688 // duplicate actions that are found here. 5689 N = results.size(); 5690 for (int i=specificsPos; i<N-1; i++) { 5691 final ResolveInfo rii = results.get(i); 5692 if (rii.filter == null) { 5693 continue; 5694 } 5695 5696 // Iterate over all of the actions of this result's intent 5697 // filter... typically this should be just one. 5698 final Iterator<String> it = rii.filter.actionsIterator(); 5699 if (it == null) { 5700 continue; 5701 } 5702 while (it.hasNext()) { 5703 final String action = it.next(); 5704 if (resultsAction != null && resultsAction.equals(action)) { 5705 // If this action was explicitly requested, then don't 5706 // remove things that have it. 5707 continue; 5708 } 5709 for (int j=i+1; j<N; j++) { 5710 final ResolveInfo rij = results.get(j); 5711 if (rij.filter != null && rij.filter.hasAction(action)) { 5712 results.remove(j); 5713 if (DEBUG_INTENT_MATCHING) Log.v( 5714 TAG, "Removing duplicate item from " + j 5715 + " due to action " + action + " at " + i); 5716 j--; 5717 N--; 5718 } 5719 } 5720 } 5721 5722 // If the caller didn't request filter information, drop it now 5723 // so we don't have to marshall/unmarshall it. 5724 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5725 rii.filter = null; 5726 } 5727 } 5728 5729 // Filter out the caller activity if so requested. 5730 if (caller != null) { 5731 N = results.size(); 5732 for (int i=0; i<N; i++) { 5733 ActivityInfo ainfo = results.get(i).activityInfo; 5734 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5735 && caller.getClassName().equals(ainfo.name)) { 5736 results.remove(i); 5737 break; 5738 } 5739 } 5740 } 5741 5742 // If the caller didn't request filter information, 5743 // drop them now so we don't have to 5744 // marshall/unmarshall it. 5745 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5746 N = results.size(); 5747 for (int i=0; i<N; i++) { 5748 results.get(i).filter = null; 5749 } 5750 } 5751 5752 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5753 return results; 5754 } 5755 5756 @Override 5757 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 5758 String resolvedType, int flags, int userId) { 5759 return new ParceledListSlice<>( 5760 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 5761 } 5762 5763 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 5764 String resolvedType, int flags, int userId) { 5765 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5766 flags = updateFlagsForResolve(flags, userId, intent); 5767 ComponentName comp = intent.getComponent(); 5768 if (comp == null) { 5769 if (intent.getSelector() != null) { 5770 intent = intent.getSelector(); 5771 comp = intent.getComponent(); 5772 } 5773 } 5774 if (comp != null) { 5775 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5776 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5777 if (ai != null) { 5778 ResolveInfo ri = new ResolveInfo(); 5779 ri.activityInfo = ai; 5780 list.add(ri); 5781 } 5782 return list; 5783 } 5784 5785 // reader 5786 synchronized (mPackages) { 5787 String pkgName = intent.getPackage(); 5788 if (pkgName == null) { 5789 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5790 } 5791 final PackageParser.Package pkg = mPackages.get(pkgName); 5792 if (pkg != null) { 5793 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5794 userId); 5795 } 5796 return Collections.emptyList(); 5797 } 5798 } 5799 5800 @Override 5801 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5802 if (!sUserManager.exists(userId)) return null; 5803 flags = updateFlagsForResolve(flags, userId, intent); 5804 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 5805 if (query != null) { 5806 if (query.size() >= 1) { 5807 // If there is more than one service with the same priority, 5808 // just arbitrarily pick the first one. 5809 return query.get(0); 5810 } 5811 } 5812 return null; 5813 } 5814 5815 @Override 5816 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 5817 String resolvedType, int flags, int userId) { 5818 return new ParceledListSlice<>( 5819 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 5820 } 5821 5822 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 5823 String resolvedType, int flags, int userId) { 5824 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5825 flags = updateFlagsForResolve(flags, userId, intent); 5826 ComponentName comp = intent.getComponent(); 5827 if (comp == null) { 5828 if (intent.getSelector() != null) { 5829 intent = intent.getSelector(); 5830 comp = intent.getComponent(); 5831 } 5832 } 5833 if (comp != null) { 5834 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5835 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5836 if (si != null) { 5837 final ResolveInfo ri = new ResolveInfo(); 5838 ri.serviceInfo = si; 5839 list.add(ri); 5840 } 5841 return list; 5842 } 5843 5844 // reader 5845 synchronized (mPackages) { 5846 String pkgName = intent.getPackage(); 5847 if (pkgName == null) { 5848 return mServices.queryIntent(intent, resolvedType, flags, userId); 5849 } 5850 final PackageParser.Package pkg = mPackages.get(pkgName); 5851 if (pkg != null) { 5852 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5853 userId); 5854 } 5855 return Collections.emptyList(); 5856 } 5857 } 5858 5859 @Override 5860 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 5861 String resolvedType, int flags, int userId) { 5862 return new ParceledListSlice<>( 5863 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 5864 } 5865 5866 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 5867 Intent intent, String resolvedType, int flags, int userId) { 5868 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5869 flags = updateFlagsForResolve(flags, userId, intent); 5870 ComponentName comp = intent.getComponent(); 5871 if (comp == null) { 5872 if (intent.getSelector() != null) { 5873 intent = intent.getSelector(); 5874 comp = intent.getComponent(); 5875 } 5876 } 5877 if (comp != null) { 5878 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5879 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5880 if (pi != null) { 5881 final ResolveInfo ri = new ResolveInfo(); 5882 ri.providerInfo = pi; 5883 list.add(ri); 5884 } 5885 return list; 5886 } 5887 5888 // reader 5889 synchronized (mPackages) { 5890 String pkgName = intent.getPackage(); 5891 if (pkgName == null) { 5892 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5893 } 5894 final PackageParser.Package pkg = mPackages.get(pkgName); 5895 if (pkg != null) { 5896 return mProviders.queryIntentForPackage( 5897 intent, resolvedType, flags, pkg.providers, userId); 5898 } 5899 return Collections.emptyList(); 5900 } 5901 } 5902 5903 @Override 5904 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5905 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5906 flags = updateFlagsForPackage(flags, userId, null); 5907 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5908 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5909 true /* requireFullPermission */, false /* checkShell */, 5910 "get installed packages"); 5911 5912 // writer 5913 synchronized (mPackages) { 5914 ArrayList<PackageInfo> list; 5915 if (listUninstalled) { 5916 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5917 for (PackageSetting ps : mSettings.mPackages.values()) { 5918 PackageInfo pi; 5919 if (ps.pkg != null) { 5920 pi = generatePackageInfo(ps.pkg, flags, userId); 5921 } else { 5922 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5923 } 5924 if (pi != null) { 5925 list.add(pi); 5926 } 5927 } 5928 } else { 5929 list = new ArrayList<PackageInfo>(mPackages.size()); 5930 for (PackageParser.Package p : mPackages.values()) { 5931 PackageInfo pi = generatePackageInfo(p, flags, userId); 5932 if (pi != null) { 5933 list.add(pi); 5934 } 5935 } 5936 } 5937 5938 return new ParceledListSlice<PackageInfo>(list); 5939 } 5940 } 5941 5942 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5943 String[] permissions, boolean[] tmp, int flags, int userId) { 5944 int numMatch = 0; 5945 final PermissionsState permissionsState = ps.getPermissionsState(); 5946 for (int i=0; i<permissions.length; i++) { 5947 final String permission = permissions[i]; 5948 if (permissionsState.hasPermission(permission, userId)) { 5949 tmp[i] = true; 5950 numMatch++; 5951 } else { 5952 tmp[i] = false; 5953 } 5954 } 5955 if (numMatch == 0) { 5956 return; 5957 } 5958 PackageInfo pi; 5959 if (ps.pkg != null) { 5960 pi = generatePackageInfo(ps.pkg, flags, userId); 5961 } else { 5962 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5963 } 5964 // The above might return null in cases of uninstalled apps or install-state 5965 // skew across users/profiles. 5966 if (pi != null) { 5967 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5968 if (numMatch == permissions.length) { 5969 pi.requestedPermissions = permissions; 5970 } else { 5971 pi.requestedPermissions = new String[numMatch]; 5972 numMatch = 0; 5973 for (int i=0; i<permissions.length; i++) { 5974 if (tmp[i]) { 5975 pi.requestedPermissions[numMatch] = permissions[i]; 5976 numMatch++; 5977 } 5978 } 5979 } 5980 } 5981 list.add(pi); 5982 } 5983 } 5984 5985 @Override 5986 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5987 String[] permissions, int flags, int userId) { 5988 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5989 flags = updateFlagsForPackage(flags, userId, permissions); 5990 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5991 5992 // writer 5993 synchronized (mPackages) { 5994 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5995 boolean[] tmpBools = new boolean[permissions.length]; 5996 if (listUninstalled) { 5997 for (PackageSetting ps : mSettings.mPackages.values()) { 5998 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5999 } 6000 } else { 6001 for (PackageParser.Package pkg : mPackages.values()) { 6002 PackageSetting ps = (PackageSetting)pkg.mExtras; 6003 if (ps != null) { 6004 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6005 userId); 6006 } 6007 } 6008 } 6009 6010 return new ParceledListSlice<PackageInfo>(list); 6011 } 6012 } 6013 6014 @Override 6015 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6016 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6017 flags = updateFlagsForApplication(flags, userId, null); 6018 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6019 6020 // writer 6021 synchronized (mPackages) { 6022 ArrayList<ApplicationInfo> list; 6023 if (listUninstalled) { 6024 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6025 for (PackageSetting ps : mSettings.mPackages.values()) { 6026 ApplicationInfo ai; 6027 if (ps.pkg != null) { 6028 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6029 ps.readUserState(userId), userId); 6030 } else { 6031 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6032 } 6033 if (ai != null) { 6034 list.add(ai); 6035 } 6036 } 6037 } else { 6038 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6039 for (PackageParser.Package p : mPackages.values()) { 6040 if (p.mExtras != null) { 6041 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6042 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6043 if (ai != null) { 6044 list.add(ai); 6045 } 6046 } 6047 } 6048 } 6049 6050 return new ParceledListSlice<ApplicationInfo>(list); 6051 } 6052 } 6053 6054 @Override 6055 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6056 if (DISABLE_EPHEMERAL_APPS) { 6057 return null; 6058 } 6059 6060 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6061 "getEphemeralApplications"); 6062 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6063 true /* requireFullPermission */, false /* checkShell */, 6064 "getEphemeralApplications"); 6065 synchronized (mPackages) { 6066 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6067 .getEphemeralApplicationsLPw(userId); 6068 if (ephemeralApps != null) { 6069 return new ParceledListSlice<>(ephemeralApps); 6070 } 6071 } 6072 return null; 6073 } 6074 6075 @Override 6076 public boolean isEphemeralApplication(String packageName, int userId) { 6077 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6078 true /* requireFullPermission */, false /* checkShell */, 6079 "isEphemeral"); 6080 if (DISABLE_EPHEMERAL_APPS) { 6081 return false; 6082 } 6083 6084 if (!isCallerSameApp(packageName)) { 6085 return false; 6086 } 6087 synchronized (mPackages) { 6088 PackageParser.Package pkg = mPackages.get(packageName); 6089 if (pkg != null) { 6090 return pkg.applicationInfo.isEphemeralApp(); 6091 } 6092 } 6093 return false; 6094 } 6095 6096 @Override 6097 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6098 if (DISABLE_EPHEMERAL_APPS) { 6099 return null; 6100 } 6101 6102 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6103 true /* requireFullPermission */, false /* checkShell */, 6104 "getCookie"); 6105 if (!isCallerSameApp(packageName)) { 6106 return null; 6107 } 6108 synchronized (mPackages) { 6109 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6110 packageName, userId); 6111 } 6112 } 6113 6114 @Override 6115 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6116 if (DISABLE_EPHEMERAL_APPS) { 6117 return true; 6118 } 6119 6120 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6121 true /* requireFullPermission */, true /* checkShell */, 6122 "setCookie"); 6123 if (!isCallerSameApp(packageName)) { 6124 return false; 6125 } 6126 synchronized (mPackages) { 6127 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6128 packageName, cookie, userId); 6129 } 6130 } 6131 6132 @Override 6133 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6134 if (DISABLE_EPHEMERAL_APPS) { 6135 return null; 6136 } 6137 6138 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6139 "getEphemeralApplicationIcon"); 6140 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6141 true /* requireFullPermission */, false /* checkShell */, 6142 "getEphemeralApplicationIcon"); 6143 synchronized (mPackages) { 6144 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6145 packageName, userId); 6146 } 6147 } 6148 6149 private boolean isCallerSameApp(String packageName) { 6150 PackageParser.Package pkg = mPackages.get(packageName); 6151 return pkg != null 6152 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6153 } 6154 6155 @Override 6156 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6157 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6158 } 6159 6160 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6161 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6162 6163 // reader 6164 synchronized (mPackages) { 6165 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6166 final int userId = UserHandle.getCallingUserId(); 6167 while (i.hasNext()) { 6168 final PackageParser.Package p = i.next(); 6169 if (p.applicationInfo == null) continue; 6170 6171 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6172 && !p.applicationInfo.isDirectBootAware(); 6173 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6174 && p.applicationInfo.isDirectBootAware(); 6175 6176 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6177 && (!mSafeMode || isSystemApp(p)) 6178 && (matchesUnaware || matchesAware)) { 6179 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6180 if (ps != null) { 6181 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6182 ps.readUserState(userId), userId); 6183 if (ai != null) { 6184 finalList.add(ai); 6185 } 6186 } 6187 } 6188 } 6189 } 6190 6191 return finalList; 6192 } 6193 6194 @Override 6195 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6196 if (!sUserManager.exists(userId)) return null; 6197 flags = updateFlagsForComponent(flags, userId, name); 6198 // reader 6199 synchronized (mPackages) { 6200 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6201 PackageSetting ps = provider != null 6202 ? mSettings.mPackages.get(provider.owner.packageName) 6203 : null; 6204 return ps != null 6205 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6206 ? PackageParser.generateProviderInfo(provider, flags, 6207 ps.readUserState(userId), userId) 6208 : null; 6209 } 6210 } 6211 6212 /** 6213 * @deprecated 6214 */ 6215 @Deprecated 6216 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6217 // reader 6218 synchronized (mPackages) { 6219 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6220 .entrySet().iterator(); 6221 final int userId = UserHandle.getCallingUserId(); 6222 while (i.hasNext()) { 6223 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6224 PackageParser.Provider p = entry.getValue(); 6225 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6226 6227 if (ps != null && p.syncable 6228 && (!mSafeMode || (p.info.applicationInfo.flags 6229 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6230 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6231 ps.readUserState(userId), userId); 6232 if (info != null) { 6233 outNames.add(entry.getKey()); 6234 outInfo.add(info); 6235 } 6236 } 6237 } 6238 } 6239 } 6240 6241 @Override 6242 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6243 int uid, int flags) { 6244 final int userId = processName != null ? UserHandle.getUserId(uid) 6245 : UserHandle.getCallingUserId(); 6246 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6247 flags = updateFlagsForComponent(flags, userId, processName); 6248 6249 ArrayList<ProviderInfo> finalList = null; 6250 // reader 6251 synchronized (mPackages) { 6252 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6253 while (i.hasNext()) { 6254 final PackageParser.Provider p = i.next(); 6255 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6256 if (ps != null && p.info.authority != null 6257 && (processName == null 6258 || (p.info.processName.equals(processName) 6259 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6260 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6261 if (finalList == null) { 6262 finalList = new ArrayList<ProviderInfo>(3); 6263 } 6264 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6265 ps.readUserState(userId), userId); 6266 if (info != null) { 6267 finalList.add(info); 6268 } 6269 } 6270 } 6271 } 6272 6273 if (finalList != null) { 6274 Collections.sort(finalList, mProviderInitOrderSorter); 6275 return new ParceledListSlice<ProviderInfo>(finalList); 6276 } 6277 6278 return ParceledListSlice.emptyList(); 6279 } 6280 6281 @Override 6282 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6283 // reader 6284 synchronized (mPackages) { 6285 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6286 return PackageParser.generateInstrumentationInfo(i, flags); 6287 } 6288 } 6289 6290 @Override 6291 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6292 String targetPackage, int flags) { 6293 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6294 } 6295 6296 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6297 int flags) { 6298 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6299 6300 // reader 6301 synchronized (mPackages) { 6302 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6303 while (i.hasNext()) { 6304 final PackageParser.Instrumentation p = i.next(); 6305 if (targetPackage == null 6306 || targetPackage.equals(p.info.targetPackage)) { 6307 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6308 flags); 6309 if (ii != null) { 6310 finalList.add(ii); 6311 } 6312 } 6313 } 6314 } 6315 6316 return finalList; 6317 } 6318 6319 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6320 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6321 if (overlays == null) { 6322 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6323 return; 6324 } 6325 for (PackageParser.Package opkg : overlays.values()) { 6326 // Not much to do if idmap fails: we already logged the error 6327 // and we certainly don't want to abort installation of pkg simply 6328 // because an overlay didn't fit properly. For these reasons, 6329 // ignore the return value of createIdmapForPackagePairLI. 6330 createIdmapForPackagePairLI(pkg, opkg); 6331 } 6332 } 6333 6334 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6335 PackageParser.Package opkg) { 6336 if (!opkg.mTrustedOverlay) { 6337 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6338 opkg.baseCodePath + ": overlay not trusted"); 6339 return false; 6340 } 6341 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6342 if (overlaySet == null) { 6343 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6344 opkg.baseCodePath + " but target package has no known overlays"); 6345 return false; 6346 } 6347 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6348 // TODO: generate idmap for split APKs 6349 try { 6350 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6351 } catch (InstallerException e) { 6352 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6353 + opkg.baseCodePath); 6354 return false; 6355 } 6356 PackageParser.Package[] overlayArray = 6357 overlaySet.values().toArray(new PackageParser.Package[0]); 6358 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6359 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6360 return p1.mOverlayPriority - p2.mOverlayPriority; 6361 } 6362 }; 6363 Arrays.sort(overlayArray, cmp); 6364 6365 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6366 int i = 0; 6367 for (PackageParser.Package p : overlayArray) { 6368 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6369 } 6370 return true; 6371 } 6372 6373 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6374 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6375 try { 6376 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6377 } finally { 6378 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6379 } 6380 } 6381 6382 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6383 final File[] files = dir.listFiles(); 6384 if (ArrayUtils.isEmpty(files)) { 6385 Log.d(TAG, "No files in app dir " + dir); 6386 return; 6387 } 6388 6389 if (DEBUG_PACKAGE_SCANNING) { 6390 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6391 + " flags=0x" + Integer.toHexString(parseFlags)); 6392 } 6393 6394 for (File file : files) { 6395 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6396 && !PackageInstallerService.isStageName(file.getName()); 6397 if (!isPackage) { 6398 // Ignore entries which are not packages 6399 continue; 6400 } 6401 try { 6402 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6403 scanFlags, currentTime, null); 6404 } catch (PackageManagerException e) { 6405 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6406 6407 // Delete invalid userdata apps 6408 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6409 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6410 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6411 removeCodePathLI(file); 6412 } 6413 } 6414 } 6415 } 6416 6417 private static File getSettingsProblemFile() { 6418 File dataDir = Environment.getDataDirectory(); 6419 File systemDir = new File(dataDir, "system"); 6420 File fname = new File(systemDir, "uiderrors.txt"); 6421 return fname; 6422 } 6423 6424 static void reportSettingsProblem(int priority, String msg) { 6425 logCriticalInfo(priority, msg); 6426 } 6427 6428 static void logCriticalInfo(int priority, String msg) { 6429 Slog.println(priority, TAG, msg); 6430 EventLogTags.writePmCriticalInfo(msg); 6431 try { 6432 File fname = getSettingsProblemFile(); 6433 FileOutputStream out = new FileOutputStream(fname, true); 6434 PrintWriter pw = new FastPrintWriter(out); 6435 SimpleDateFormat formatter = new SimpleDateFormat(); 6436 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6437 pw.println(dateString + ": " + msg); 6438 pw.close(); 6439 FileUtils.setPermissions( 6440 fname.toString(), 6441 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6442 -1, -1); 6443 } catch (java.io.IOException e) { 6444 } 6445 } 6446 6447 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6448 int parseFlags) throws PackageManagerException { 6449 if (ps != null 6450 && ps.codePath.equals(srcFile) 6451 && ps.timeStamp == srcFile.lastModified() 6452 && !isCompatSignatureUpdateNeeded(pkg) 6453 && !isRecoverSignatureUpdateNeeded(pkg)) { 6454 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6455 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6456 ArraySet<PublicKey> signingKs; 6457 synchronized (mPackages) { 6458 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6459 } 6460 if (ps.signatures.mSignatures != null 6461 && ps.signatures.mSignatures.length != 0 6462 && signingKs != null) { 6463 // Optimization: reuse the existing cached certificates 6464 // if the package appears to be unchanged. 6465 pkg.mSignatures = ps.signatures.mSignatures; 6466 pkg.mSigningKeys = signingKs; 6467 return; 6468 } 6469 6470 Slog.w(TAG, "PackageSetting for " + ps.name 6471 + " is missing signatures. Collecting certs again to recover them."); 6472 } else { 6473 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6474 } 6475 6476 try { 6477 PackageParser.collectCertificates(pkg, parseFlags); 6478 } catch (PackageParserException e) { 6479 throw PackageManagerException.from(e); 6480 } 6481 } 6482 6483 /** 6484 * Traces a package scan. 6485 * @see #scanPackageLI(File, int, int, long, UserHandle) 6486 */ 6487 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6488 long currentTime, UserHandle user) throws PackageManagerException { 6489 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6490 try { 6491 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6492 } finally { 6493 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6494 } 6495 } 6496 6497 /** 6498 * Scans a package and returns the newly parsed package. 6499 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6500 */ 6501 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6502 long currentTime, UserHandle user) throws PackageManagerException { 6503 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6504 parseFlags |= mDefParseFlags; 6505 PackageParser pp = new PackageParser(); 6506 pp.setSeparateProcesses(mSeparateProcesses); 6507 pp.setOnlyCoreApps(mOnlyCore); 6508 pp.setDisplayMetrics(mMetrics); 6509 6510 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6511 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6512 } 6513 6514 final PackageParser.Package pkg; 6515 try { 6516 pkg = pp.parsePackage(scanFile, parseFlags); 6517 } catch (PackageParserException e) { 6518 throw PackageManagerException.from(e); 6519 } 6520 6521 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6522 } 6523 6524 /** 6525 * Scans a package and returns the newly parsed package. 6526 * @throws PackageManagerException on a parse error. 6527 */ 6528 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6529 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6530 throws PackageManagerException { 6531 // If the package has children and this is the first dive in the function 6532 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6533 // packages (parent and children) would be successfully scanned before the 6534 // actual scan since scanning mutates internal state and we want to atomically 6535 // install the package and its children. 6536 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6537 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6538 scanFlags |= SCAN_CHECK_ONLY; 6539 } 6540 } else { 6541 scanFlags &= ~SCAN_CHECK_ONLY; 6542 } 6543 6544 // Scan the parent 6545 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags, 6546 scanFlags, currentTime, user); 6547 6548 // Scan the children 6549 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6550 for (int i = 0; i < childCount; i++) { 6551 PackageParser.Package childPackage = pkg.childPackages.get(i); 6552 scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags, 6553 currentTime, user); 6554 } 6555 6556 6557 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6558 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6559 } 6560 6561 return scannedPkg; 6562 } 6563 6564 /** 6565 * Scans a package and returns the newly parsed package. 6566 * @throws PackageManagerException on a parse error. 6567 */ 6568 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6569 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6570 throws PackageManagerException { 6571 PackageSetting ps = null; 6572 PackageSetting updatedPkg; 6573 // reader 6574 synchronized (mPackages) { 6575 // Look to see if we already know about this package. 6576 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6577 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6578 // This package has been renamed to its original name. Let's 6579 // use that. 6580 ps = mSettings.peekPackageLPr(oldName); 6581 } 6582 // If there was no original package, see one for the real package name. 6583 if (ps == null) { 6584 ps = mSettings.peekPackageLPr(pkg.packageName); 6585 } 6586 // Check to see if this package could be hiding/updating a system 6587 // package. Must look for it either under the original or real 6588 // package name depending on our state. 6589 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6590 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6591 6592 // If this is a package we don't know about on the system partition, we 6593 // may need to remove disabled child packages on the system partition 6594 // or may need to not add child packages if the parent apk is updated 6595 // on the data partition and no longer defines this child package. 6596 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6597 // If this is a parent package for an updated system app and this system 6598 // app got an OTA update which no longer defines some of the child packages 6599 // we have to prune them from the disabled system packages. 6600 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6601 if (disabledPs != null) { 6602 final int scannedChildCount = (pkg.childPackages != null) 6603 ? pkg.childPackages.size() : 0; 6604 final int disabledChildCount = disabledPs.childPackageNames != null 6605 ? disabledPs.childPackageNames.size() : 0; 6606 for (int i = 0; i < disabledChildCount; i++) { 6607 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6608 boolean disabledPackageAvailable = false; 6609 for (int j = 0; j < scannedChildCount; j++) { 6610 PackageParser.Package childPkg = pkg.childPackages.get(j); 6611 if (childPkg.packageName.equals(disabledChildPackageName)) { 6612 disabledPackageAvailable = true; 6613 break; 6614 } 6615 } 6616 if (!disabledPackageAvailable) { 6617 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6618 } 6619 } 6620 } 6621 } 6622 } 6623 6624 boolean updatedPkgBetter = false; 6625 // First check if this is a system package that may involve an update 6626 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6627 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6628 // it needs to drop FLAG_PRIVILEGED. 6629 if (locationIsPrivileged(scanFile)) { 6630 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6631 } else { 6632 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6633 } 6634 6635 if (ps != null && !ps.codePath.equals(scanFile)) { 6636 // The path has changed from what was last scanned... check the 6637 // version of the new path against what we have stored to determine 6638 // what to do. 6639 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6640 if (pkg.mVersionCode <= ps.versionCode) { 6641 // The system package has been updated and the code path does not match 6642 // Ignore entry. Skip it. 6643 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6644 + " ignored: updated version " + ps.versionCode 6645 + " better than this " + pkg.mVersionCode); 6646 if (!updatedPkg.codePath.equals(scanFile)) { 6647 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6648 + ps.name + " changing from " + updatedPkg.codePathString 6649 + " to " + scanFile); 6650 updatedPkg.codePath = scanFile; 6651 updatedPkg.codePathString = scanFile.toString(); 6652 updatedPkg.resourcePath = scanFile; 6653 updatedPkg.resourcePathString = scanFile.toString(); 6654 } 6655 updatedPkg.pkg = pkg; 6656 updatedPkg.versionCode = pkg.mVersionCode; 6657 6658 // Update the disabled system child packages to point to the package too. 6659 final int childCount = updatedPkg.childPackageNames != null 6660 ? updatedPkg.childPackageNames.size() : 0; 6661 for (int i = 0; i < childCount; i++) { 6662 String childPackageName = updatedPkg.childPackageNames.get(i); 6663 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6664 childPackageName); 6665 if (updatedChildPkg != null) { 6666 updatedChildPkg.pkg = pkg; 6667 updatedChildPkg.versionCode = pkg.mVersionCode; 6668 } 6669 } 6670 6671 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6672 + scanFile + " ignored: updated version " + ps.versionCode 6673 + " better than this " + pkg.mVersionCode); 6674 } else { 6675 // The current app on the system partition is better than 6676 // what we have updated to on the data partition; switch 6677 // back to the system partition version. 6678 // At this point, its safely assumed that package installation for 6679 // apps in system partition will go through. If not there won't be a working 6680 // version of the app 6681 // writer 6682 synchronized (mPackages) { 6683 // Just remove the loaded entries from package lists. 6684 mPackages.remove(ps.name); 6685 } 6686 6687 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6688 + " reverting from " + ps.codePathString 6689 + ": new version " + pkg.mVersionCode 6690 + " better than installed " + ps.versionCode); 6691 6692 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6693 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6694 synchronized (mInstallLock) { 6695 args.cleanUpResourcesLI(); 6696 } 6697 synchronized (mPackages) { 6698 mSettings.enableSystemPackageLPw(ps.name); 6699 } 6700 updatedPkgBetter = true; 6701 } 6702 } 6703 } 6704 6705 if (updatedPkg != null) { 6706 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6707 // initially 6708 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6709 6710 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6711 // flag set initially 6712 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6713 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6714 } 6715 } 6716 6717 // Verify certificates against what was last scanned 6718 collectCertificatesLI(ps, pkg, scanFile, parseFlags); 6719 6720 /* 6721 * A new system app appeared, but we already had a non-system one of the 6722 * same name installed earlier. 6723 */ 6724 boolean shouldHideSystemApp = false; 6725 if (updatedPkg == null && ps != null 6726 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6727 /* 6728 * Check to make sure the signatures match first. If they don't, 6729 * wipe the installed application and its data. 6730 */ 6731 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6732 != PackageManager.SIGNATURE_MATCH) { 6733 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6734 + " signatures don't match existing userdata copy; removing"); 6735 deletePackageLI(pkg.packageName, null, true, null, 0, null, false, null); 6736 ps = null; 6737 } else { 6738 /* 6739 * If the newly-added system app is an older version than the 6740 * already installed version, hide it. It will be scanned later 6741 * and re-added like an update. 6742 */ 6743 if (pkg.mVersionCode <= ps.versionCode) { 6744 shouldHideSystemApp = true; 6745 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6746 + " but new version " + pkg.mVersionCode + " better than installed " 6747 + ps.versionCode + "; hiding system"); 6748 } else { 6749 /* 6750 * The newly found system app is a newer version that the 6751 * one previously installed. Simply remove the 6752 * already-installed application and replace it with our own 6753 * while keeping the application data. 6754 */ 6755 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6756 + " reverting from " + ps.codePathString + ": new version " 6757 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6758 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6759 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6760 synchronized (mInstallLock) { 6761 args.cleanUpResourcesLI(); 6762 } 6763 } 6764 } 6765 } 6766 6767 // The apk is forward locked (not public) if its code and resources 6768 // are kept in different files. (except for app in either system or 6769 // vendor path). 6770 // TODO grab this value from PackageSettings 6771 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6772 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6773 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6774 } 6775 } 6776 6777 // TODO: extend to support forward-locked splits 6778 String resourcePath = null; 6779 String baseResourcePath = null; 6780 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6781 if (ps != null && ps.resourcePathString != null) { 6782 resourcePath = ps.resourcePathString; 6783 baseResourcePath = ps.resourcePathString; 6784 } else { 6785 // Should not happen at all. Just log an error. 6786 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6787 } 6788 } else { 6789 resourcePath = pkg.codePath; 6790 baseResourcePath = pkg.baseCodePath; 6791 } 6792 6793 // Set application objects path explicitly. 6794 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 6795 pkg.setApplicationInfoCodePath(pkg.codePath); 6796 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 6797 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 6798 pkg.setApplicationInfoResourcePath(resourcePath); 6799 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 6800 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 6801 6802 // Note that we invoke the following method only if we are about to unpack an application 6803 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6804 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6805 6806 /* 6807 * If the system app should be overridden by a previously installed 6808 * data, hide the system app now and let the /data/app scan pick it up 6809 * again. 6810 */ 6811 if (shouldHideSystemApp) { 6812 synchronized (mPackages) { 6813 mSettings.disableSystemPackageLPw(pkg.packageName, true); 6814 } 6815 } 6816 6817 return scannedPkg; 6818 } 6819 6820 private static String fixProcessName(String defProcessName, 6821 String processName, int uid) { 6822 if (processName == null) { 6823 return defProcessName; 6824 } 6825 return processName; 6826 } 6827 6828 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6829 throws PackageManagerException { 6830 if (pkgSetting.signatures.mSignatures != null) { 6831 // Already existing package. Make sure signatures match 6832 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6833 == PackageManager.SIGNATURE_MATCH; 6834 if (!match) { 6835 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6836 == PackageManager.SIGNATURE_MATCH; 6837 } 6838 if (!match) { 6839 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6840 == PackageManager.SIGNATURE_MATCH; 6841 } 6842 if (!match) { 6843 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6844 + pkg.packageName + " signatures do not match the " 6845 + "previously installed version; ignoring!"); 6846 } 6847 } 6848 6849 // Check for shared user signatures 6850 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6851 // Already existing package. Make sure signatures match 6852 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6853 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6854 if (!match) { 6855 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6856 == PackageManager.SIGNATURE_MATCH; 6857 } 6858 if (!match) { 6859 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6860 == PackageManager.SIGNATURE_MATCH; 6861 } 6862 if (!match) { 6863 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6864 "Package " + pkg.packageName 6865 + " has no signatures that match those in shared user " 6866 + pkgSetting.sharedUser.name + "; ignoring!"); 6867 } 6868 } 6869 } 6870 6871 /** 6872 * Enforces that only the system UID or root's UID can call a method exposed 6873 * via Binder. 6874 * 6875 * @param message used as message if SecurityException is thrown 6876 * @throws SecurityException if the caller is not system or root 6877 */ 6878 private static final void enforceSystemOrRoot(String message) { 6879 final int uid = Binder.getCallingUid(); 6880 if (uid != Process.SYSTEM_UID && uid != 0) { 6881 throw new SecurityException(message); 6882 } 6883 } 6884 6885 @Override 6886 public void performFstrimIfNeeded() { 6887 enforceSystemOrRoot("Only the system can request fstrim"); 6888 6889 // Before everything else, see whether we need to fstrim. 6890 try { 6891 IMountService ms = PackageHelper.getMountService(); 6892 if (ms != null) { 6893 final boolean isUpgrade = isUpgrade(); 6894 boolean doTrim = isUpgrade; 6895 if (doTrim) { 6896 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6897 } else { 6898 final long interval = android.provider.Settings.Global.getLong( 6899 mContext.getContentResolver(), 6900 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6901 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6902 if (interval > 0) { 6903 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6904 if (timeSinceLast > interval) { 6905 doTrim = true; 6906 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6907 + "; running immediately"); 6908 } 6909 } 6910 } 6911 if (doTrim) { 6912 if (!isFirstBoot()) { 6913 try { 6914 ActivityManagerNative.getDefault().showBootMessage( 6915 mContext.getResources().getString( 6916 R.string.android_upgrading_fstrim), true); 6917 } catch (RemoteException e) { 6918 } 6919 } 6920 ms.runMaintenance(); 6921 } 6922 } else { 6923 Slog.e(TAG, "Mount service unavailable!"); 6924 } 6925 } catch (RemoteException e) { 6926 // Can't happen; MountService is local 6927 } 6928 } 6929 6930 @Override 6931 public void extractPackagesIfNeeded() { 6932 enforceSystemOrRoot("Only the system can request package extraction"); 6933 6934 // We need to re-extract after an OTA. 6935 boolean causeUpgrade = isUpgrade(); 6936 6937 // First boot or factory reset. 6938 // Note: we also handle devices that are upgrading to N right now as if it is their 6939 // first boot, as they do not have profile data. 6940 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 6941 6942 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 6943 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 6944 6945 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 6946 return; 6947 } 6948 6949 List<PackageParser.Package> pkgs; 6950 synchronized (mPackages) { 6951 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 6952 } 6953 6954 int curr = 0; 6955 int total = pkgs.size(); 6956 for (PackageParser.Package pkg : pkgs) { 6957 curr++; 6958 6959 if (DEBUG_DEXOPT) { 6960 Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName); 6961 } 6962 6963 if (!isFirstBoot()) { 6964 try { 6965 ActivityManagerNative.getDefault().showBootMessage( 6966 mContext.getResources().getString(R.string.android_upgrading_apk, 6967 curr, total), true); 6968 } catch (RemoteException e) { 6969 } 6970 } 6971 6972 if (PackageDexOptimizer.canOptimizePackage(pkg)) { 6973 // If the cache was pruned, any compiled odex files will likely be out of date 6974 // and would have to be patched (would be SELF_PATCHOAT, which is deprecated). 6975 // Instead, force the extraction in this case. 6976 performDexOpt(pkg.packageName, null /* instructionSet */, 6977 false /* checkProfiles */, 6978 causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT, 6979 causePrunedCache); 6980 } 6981 } 6982 } 6983 6984 @Override 6985 public void notifyPackageUse(String packageName) { 6986 synchronized (mPackages) { 6987 PackageParser.Package p = mPackages.get(packageName); 6988 if (p == null) { 6989 return; 6990 } 6991 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6992 } 6993 } 6994 6995 // TODO: this is not used nor needed. Delete it. 6996 @Override 6997 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6998 return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */, 6999 getFullCompilerFilter(), false /* force */); 7000 } 7001 7002 @Override 7003 public boolean performDexOpt(String packageName, String instructionSet, 7004 boolean checkProfiles, int compileReason, boolean force) { 7005 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7006 getCompilerFilterForReason(compileReason), force); 7007 } 7008 7009 @Override 7010 public boolean performDexOptMode(String packageName, String instructionSet, 7011 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7012 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7013 targetCompilerFilter, force); 7014 } 7015 7016 private boolean performDexOptTraced(String packageName, String instructionSet, 7017 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7018 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7019 try { 7020 return performDexOptInternal(packageName, instructionSet, checkProfiles, 7021 targetCompilerFilter, force); 7022 } finally { 7023 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7024 } 7025 } 7026 7027 private boolean performDexOptInternal(String packageName, String instructionSet, 7028 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7029 PackageParser.Package p; 7030 final String targetInstructionSet; 7031 synchronized (mPackages) { 7032 p = mPackages.get(packageName); 7033 if (p == null) { 7034 return false; 7035 } 7036 mPackageUsage.write(false); 7037 7038 targetInstructionSet = instructionSet != null ? instructionSet : 7039 getPrimaryInstructionSet(p.applicationInfo); 7040 } 7041 long callingId = Binder.clearCallingIdentity(); 7042 try { 7043 synchronized (mInstallLock) { 7044 final String[] instructionSets = new String[] { targetInstructionSet }; 7045 int result = performDexOptInternalWithDependenciesLI(p, instructionSets, 7046 checkProfiles, targetCompilerFilter, force); 7047 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 7048 } 7049 } finally { 7050 Binder.restoreCallingIdentity(callingId); 7051 } 7052 } 7053 7054 public ArraySet<String> getOptimizablePackages() { 7055 ArraySet<String> pkgs = new ArraySet<String>(); 7056 synchronized (mPackages) { 7057 for (PackageParser.Package p : mPackages.values()) { 7058 if (PackageDexOptimizer.canOptimizePackage(p)) { 7059 pkgs.add(p.packageName); 7060 } 7061 } 7062 } 7063 return pkgs; 7064 } 7065 7066 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7067 String instructionSets[], boolean checkProfiles, String targetCompilerFilter, 7068 boolean force) { 7069 // Select the dex optimizer based on the force parameter. 7070 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7071 // allocate an object here. 7072 PackageDexOptimizer pdo = force 7073 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7074 : mPackageDexOptimizer; 7075 7076 // Optimize all dependencies first. Note: we ignore the return value and march on 7077 // on errors. 7078 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7079 if (!deps.isEmpty()) { 7080 for (PackageParser.Package depPackage : deps) { 7081 // TODO: Analyze and investigate if we (should) profile libraries. 7082 // Currently this will do a full compilation of the library by default. 7083 pdo.performDexOpt(depPackage, instructionSets, false /* checkProfiles */, 7084 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7085 } 7086 } 7087 7088 return pdo.performDexOpt(p, instructionSets, checkProfiles, targetCompilerFilter); 7089 } 7090 7091 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7092 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7093 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7094 Set<String> collectedNames = new HashSet<>(); 7095 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7096 7097 retValue.remove(p); 7098 7099 return retValue; 7100 } else { 7101 return Collections.emptyList(); 7102 } 7103 } 7104 7105 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7106 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7107 if (!collectedNames.contains(p.packageName)) { 7108 collectedNames.add(p.packageName); 7109 collected.add(p); 7110 7111 if (p.usesLibraries != null) { 7112 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7113 } 7114 if (p.usesOptionalLibraries != null) { 7115 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7116 collectedNames); 7117 } 7118 } 7119 } 7120 7121 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7122 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7123 for (String libName : libs) { 7124 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7125 if (libPkg != null) { 7126 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7127 } 7128 } 7129 } 7130 7131 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7132 synchronized (mPackages) { 7133 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7134 if (lib != null && lib.apk != null) { 7135 return mPackages.get(lib.apk); 7136 } 7137 } 7138 return null; 7139 } 7140 7141 public void shutdown() { 7142 mPackageUsage.write(true); 7143 } 7144 7145 @Override 7146 public void forceDexOpt(String packageName) { 7147 enforceSystemOrRoot("forceDexOpt"); 7148 7149 PackageParser.Package pkg; 7150 synchronized (mPackages) { 7151 pkg = mPackages.get(packageName); 7152 if (pkg == null) { 7153 throw new IllegalArgumentException("Unknown package: " + packageName); 7154 } 7155 } 7156 7157 synchronized (mInstallLock) { 7158 final String[] instructionSets = new String[] { 7159 getPrimaryInstructionSet(pkg.applicationInfo) }; 7160 7161 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7162 7163 // Whoever is calling forceDexOpt wants a fully compiled package. 7164 // Don't use profiles since that may cause compilation to be skipped. 7165 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7166 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7167 true /* force */); 7168 7169 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7170 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7171 throw new IllegalStateException("Failed to dexopt: " + res); 7172 } 7173 } 7174 } 7175 7176 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7177 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7178 Slog.w(TAG, "Unable to update from " + oldPkg.name 7179 + " to " + newPkg.packageName 7180 + ": old package not in system partition"); 7181 return false; 7182 } else if (mPackages.get(oldPkg.name) != null) { 7183 Slog.w(TAG, "Unable to update from " + oldPkg.name 7184 + " to " + newPkg.packageName 7185 + ": old package still exists"); 7186 return false; 7187 } 7188 return true; 7189 } 7190 7191 private boolean removeDataDirsLI(String volumeUuid, String packageName) { 7192 // TODO: triage flags as part of 26466827 7193 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7194 7195 boolean res = true; 7196 final int[] users = sUserManager.getUserIds(); 7197 for (int user : users) { 7198 try { 7199 mInstaller.destroyAppData(volumeUuid, packageName, user, flags); 7200 } catch (InstallerException e) { 7201 Slog.w(TAG, "Failed to delete data directory", e); 7202 res = false; 7203 } 7204 } 7205 return res; 7206 } 7207 7208 void removeCodePathLI(File codePath) { 7209 if (codePath.isDirectory()) { 7210 try { 7211 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7212 } catch (InstallerException e) { 7213 Slog.w(TAG, "Failed to remove code path", e); 7214 } 7215 } else { 7216 codePath.delete(); 7217 } 7218 } 7219 7220 void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) { 7221 try { 7222 mInstaller.destroyAppData(volumeUuid, packageName, userId, flags); 7223 } catch (InstallerException e) { 7224 Slog.w(TAG, "Failed to destroy app data", e); 7225 } 7226 } 7227 7228 void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags, 7229 int appId, String seinfo) { 7230 try { 7231 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo); 7232 } catch (InstallerException e) { 7233 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 7234 } 7235 } 7236 7237 private void deleteProfilesLI(String packageName, boolean destroy) { 7238 final PackageParser.Package pkg; 7239 synchronized (mPackages) { 7240 pkg = mPackages.get(packageName); 7241 } 7242 if (pkg == null) { 7243 Slog.w(TAG, "Failed to delete profiles. No package: " + packageName); 7244 return; 7245 } 7246 deleteProfilesLI(pkg, destroy); 7247 } 7248 7249 private void deleteProfilesLI(PackageParser.Package pkg, boolean destroy) { 7250 try { 7251 if (destroy) { 7252 mInstaller.clearAppProfiles(pkg.packageName); 7253 } else { 7254 mInstaller.destroyAppProfiles(pkg.packageName); 7255 } 7256 } catch (InstallerException ex) { 7257 Log.e(TAG, "Could not delete profiles for package " + pkg.packageName); 7258 } 7259 } 7260 7261 private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 7262 final PackageParser.Package pkg; 7263 synchronized (mPackages) { 7264 pkg = mPackages.get(packageName); 7265 } 7266 if (pkg == null) { 7267 Slog.w(TAG, "Failed to delete code cache directory. No package: " + packageName); 7268 return; 7269 } 7270 deleteCodeCacheDirsLI(pkg); 7271 } 7272 7273 private void deleteCodeCacheDirsLI(PackageParser.Package pkg) { 7274 // TODO: triage flags as part of 26466827 7275 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7276 7277 int[] users = sUserManager.getUserIds(); 7278 int res = 0; 7279 for (int user : users) { 7280 // Remove the parent code cache 7281 try { 7282 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, user, 7283 flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7284 } catch (InstallerException e) { 7285 Slog.w(TAG, "Failed to delete code cache directory", e); 7286 } 7287 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7288 for (int i = 0; i < childCount; i++) { 7289 PackageParser.Package childPkg = pkg.childPackages.get(i); 7290 // Remove the child code cache 7291 try { 7292 mInstaller.clearAppData(childPkg.volumeUuid, childPkg.packageName, 7293 user, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7294 } catch (InstallerException e) { 7295 Slog.w(TAG, "Failed to delete code cache directory", e); 7296 } 7297 } 7298 } 7299 } 7300 7301 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7302 long lastUpdateTime) { 7303 // Set parent install/update time 7304 PackageSetting ps = (PackageSetting) pkg.mExtras; 7305 if (ps != null) { 7306 ps.firstInstallTime = firstInstallTime; 7307 ps.lastUpdateTime = lastUpdateTime; 7308 } 7309 // Set children install/update time 7310 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7311 for (int i = 0; i < childCount; i++) { 7312 PackageParser.Package childPkg = pkg.childPackages.get(i); 7313 ps = (PackageSetting) childPkg.mExtras; 7314 if (ps != null) { 7315 ps.firstInstallTime = firstInstallTime; 7316 ps.lastUpdateTime = lastUpdateTime; 7317 } 7318 } 7319 } 7320 7321 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7322 PackageParser.Package changingLib) { 7323 if (file.path != null) { 7324 usesLibraryFiles.add(file.path); 7325 return; 7326 } 7327 PackageParser.Package p = mPackages.get(file.apk); 7328 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7329 // If we are doing this while in the middle of updating a library apk, 7330 // then we need to make sure to use that new apk for determining the 7331 // dependencies here. (We haven't yet finished committing the new apk 7332 // to the package manager state.) 7333 if (p == null || p.packageName.equals(changingLib.packageName)) { 7334 p = changingLib; 7335 } 7336 } 7337 if (p != null) { 7338 usesLibraryFiles.addAll(p.getAllCodePaths()); 7339 } 7340 } 7341 7342 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7343 PackageParser.Package changingLib) throws PackageManagerException { 7344 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7345 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7346 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7347 for (int i=0; i<N; i++) { 7348 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7349 if (file == null) { 7350 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7351 "Package " + pkg.packageName + " requires unavailable shared library " 7352 + pkg.usesLibraries.get(i) + "; failing!"); 7353 } 7354 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7355 } 7356 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7357 for (int i=0; i<N; i++) { 7358 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7359 if (file == null) { 7360 Slog.w(TAG, "Package " + pkg.packageName 7361 + " desires unavailable shared library " 7362 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7363 } else { 7364 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7365 } 7366 } 7367 N = usesLibraryFiles.size(); 7368 if (N > 0) { 7369 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7370 } else { 7371 pkg.usesLibraryFiles = null; 7372 } 7373 } 7374 } 7375 7376 private static boolean hasString(List<String> list, List<String> which) { 7377 if (list == null) { 7378 return false; 7379 } 7380 for (int i=list.size()-1; i>=0; i--) { 7381 for (int j=which.size()-1; j>=0; j--) { 7382 if (which.get(j).equals(list.get(i))) { 7383 return true; 7384 } 7385 } 7386 } 7387 return false; 7388 } 7389 7390 private void updateAllSharedLibrariesLPw() { 7391 for (PackageParser.Package pkg : mPackages.values()) { 7392 try { 7393 updateSharedLibrariesLPw(pkg, null); 7394 } catch (PackageManagerException e) { 7395 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7396 } 7397 } 7398 } 7399 7400 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7401 PackageParser.Package changingPkg) { 7402 ArrayList<PackageParser.Package> res = null; 7403 for (PackageParser.Package pkg : mPackages.values()) { 7404 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7405 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7406 if (res == null) { 7407 res = new ArrayList<PackageParser.Package>(); 7408 } 7409 res.add(pkg); 7410 try { 7411 updateSharedLibrariesLPw(pkg, changingPkg); 7412 } catch (PackageManagerException e) { 7413 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7414 } 7415 } 7416 } 7417 return res; 7418 } 7419 7420 /** 7421 * Derive the value of the {@code cpuAbiOverride} based on the provided 7422 * value and an optional stored value from the package settings. 7423 */ 7424 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7425 String cpuAbiOverride = null; 7426 7427 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7428 cpuAbiOverride = null; 7429 } else if (abiOverride != null) { 7430 cpuAbiOverride = abiOverride; 7431 } else if (settings != null) { 7432 cpuAbiOverride = settings.cpuAbiOverrideString; 7433 } 7434 7435 return cpuAbiOverride; 7436 } 7437 7438 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 7439 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7440 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7441 // If the package has children and this is the first dive in the function 7442 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7443 // whether all packages (parent and children) would be successfully scanned 7444 // before the actual scan since scanning mutates internal state and we want 7445 // to atomically install the package and its children. 7446 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7447 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7448 scanFlags |= SCAN_CHECK_ONLY; 7449 } 7450 } else { 7451 scanFlags &= ~SCAN_CHECK_ONLY; 7452 } 7453 7454 final PackageParser.Package scannedPkg; 7455 try { 7456 // Scan the parent 7457 scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 7458 // Scan the children 7459 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7460 for (int i = 0; i < childCount; i++) { 7461 PackageParser.Package childPkg = pkg.childPackages.get(i); 7462 scanPackageLI(childPkg, parseFlags, 7463 scanFlags, currentTime, user); 7464 } 7465 } finally { 7466 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7467 } 7468 7469 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7470 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 7471 } 7472 7473 return scannedPkg; 7474 } 7475 7476 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 7477 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7478 boolean success = false; 7479 try { 7480 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 7481 currentTime, user); 7482 success = true; 7483 return res; 7484 } finally { 7485 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7486 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 7487 } 7488 } 7489 } 7490 7491 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 7492 int scanFlags, long currentTime, UserHandle user) 7493 throws PackageManagerException { 7494 final File scanFile = new File(pkg.codePath); 7495 if (pkg.applicationInfo.getCodePath() == null || 7496 pkg.applicationInfo.getResourcePath() == null) { 7497 // Bail out. The resource and code paths haven't been set. 7498 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7499 "Code and resource paths haven't been set correctly"); 7500 } 7501 7502 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7503 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7504 } else { 7505 // Only allow system apps to be flagged as core apps. 7506 pkg.coreApp = false; 7507 } 7508 7509 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7510 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7511 } 7512 7513 if (mCustomResolverComponentName != null && 7514 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7515 setUpCustomResolverActivity(pkg); 7516 } 7517 7518 if (pkg.packageName.equals("android")) { 7519 synchronized (mPackages) { 7520 if (mAndroidApplication != null) { 7521 Slog.w(TAG, "*************************************************"); 7522 Slog.w(TAG, "Core android package being redefined. Skipping."); 7523 Slog.w(TAG, " file=" + scanFile); 7524 Slog.w(TAG, "*************************************************"); 7525 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7526 "Core android package being redefined. Skipping."); 7527 } 7528 7529 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7530 // Set up information for our fall-back user intent resolution activity. 7531 mPlatformPackage = pkg; 7532 pkg.mVersionCode = mSdkVersion; 7533 mAndroidApplication = pkg.applicationInfo; 7534 7535 if (!mResolverReplaced) { 7536 mResolveActivity.applicationInfo = mAndroidApplication; 7537 mResolveActivity.name = ResolverActivity.class.getName(); 7538 mResolveActivity.packageName = mAndroidApplication.packageName; 7539 mResolveActivity.processName = "system:ui"; 7540 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7541 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7542 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7543 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7544 mResolveActivity.exported = true; 7545 mResolveActivity.enabled = true; 7546 mResolveInfo.activityInfo = mResolveActivity; 7547 mResolveInfo.priority = 0; 7548 mResolveInfo.preferredOrder = 0; 7549 mResolveInfo.match = 0; 7550 mResolveComponentName = new ComponentName( 7551 mAndroidApplication.packageName, mResolveActivity.name); 7552 } 7553 } 7554 } 7555 } 7556 7557 if (DEBUG_PACKAGE_SCANNING) { 7558 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7559 Log.d(TAG, "Scanning package " + pkg.packageName); 7560 } 7561 7562 synchronized (mPackages) { 7563 if (mPackages.containsKey(pkg.packageName) 7564 || mSharedLibraries.containsKey(pkg.packageName)) { 7565 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7566 "Application package " + pkg.packageName 7567 + " already installed. Skipping duplicate."); 7568 } 7569 7570 // If we're only installing presumed-existing packages, require that the 7571 // scanned APK is both already known and at the path previously established 7572 // for it. Previously unknown packages we pick up normally, but if we have an 7573 // a priori expectation about this package's install presence, enforce it. 7574 // With a singular exception for new system packages. When an OTA contains 7575 // a new system package, we allow the codepath to change from a system location 7576 // to the user-installed location. If we don't allow this change, any newer, 7577 // user-installed version of the application will be ignored. 7578 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7579 if (mExpectingBetter.containsKey(pkg.packageName)) { 7580 logCriticalInfo(Log.WARN, 7581 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7582 } else { 7583 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7584 if (known != null) { 7585 if (DEBUG_PACKAGE_SCANNING) { 7586 Log.d(TAG, "Examining " + pkg.codePath 7587 + " and requiring known paths " + known.codePathString 7588 + " & " + known.resourcePathString); 7589 } 7590 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7591 || !pkg.applicationInfo.getResourcePath().equals( 7592 known.resourcePathString)) { 7593 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7594 "Application package " + pkg.packageName 7595 + " found at " + pkg.applicationInfo.getCodePath() 7596 + " but expected at " + known.codePathString 7597 + "; ignoring."); 7598 } 7599 } 7600 } 7601 } 7602 } 7603 7604 // Initialize package source and resource directories 7605 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7606 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7607 7608 SharedUserSetting suid = null; 7609 PackageSetting pkgSetting = null; 7610 7611 if (!isSystemApp(pkg)) { 7612 // Only system apps can use these features. 7613 pkg.mOriginalPackages = null; 7614 pkg.mRealPackage = null; 7615 pkg.mAdoptPermissions = null; 7616 } 7617 7618 // Getting the package setting may have a side-effect, so if we 7619 // are only checking if scan would succeed, stash a copy of the 7620 // old setting to restore at the end. 7621 PackageSetting nonMutatedPs = null; 7622 7623 // writer 7624 synchronized (mPackages) { 7625 if (pkg.mSharedUserId != null) { 7626 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7627 if (suid == null) { 7628 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7629 "Creating application package " + pkg.packageName 7630 + " for shared user failed"); 7631 } 7632 if (DEBUG_PACKAGE_SCANNING) { 7633 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7634 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7635 + "): packages=" + suid.packages); 7636 } 7637 } 7638 7639 // Check if we are renaming from an original package name. 7640 PackageSetting origPackage = null; 7641 String realName = null; 7642 if (pkg.mOriginalPackages != null) { 7643 // This package may need to be renamed to a previously 7644 // installed name. Let's check on that... 7645 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7646 if (pkg.mOriginalPackages.contains(renamed)) { 7647 // This package had originally been installed as the 7648 // original name, and we have already taken care of 7649 // transitioning to the new one. Just update the new 7650 // one to continue using the old name. 7651 realName = pkg.mRealPackage; 7652 if (!pkg.packageName.equals(renamed)) { 7653 // Callers into this function may have already taken 7654 // care of renaming the package; only do it here if 7655 // it is not already done. 7656 pkg.setPackageName(renamed); 7657 } 7658 7659 } else { 7660 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7661 if ((origPackage = mSettings.peekPackageLPr( 7662 pkg.mOriginalPackages.get(i))) != null) { 7663 // We do have the package already installed under its 7664 // original name... should we use it? 7665 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7666 // New package is not compatible with original. 7667 origPackage = null; 7668 continue; 7669 } else if (origPackage.sharedUser != null) { 7670 // Make sure uid is compatible between packages. 7671 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7672 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7673 + " to " + pkg.packageName + ": old uid " 7674 + origPackage.sharedUser.name 7675 + " differs from " + pkg.mSharedUserId); 7676 origPackage = null; 7677 continue; 7678 } 7679 } else { 7680 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7681 + pkg.packageName + " to old name " + origPackage.name); 7682 } 7683 break; 7684 } 7685 } 7686 } 7687 } 7688 7689 if (mTransferedPackages.contains(pkg.packageName)) { 7690 Slog.w(TAG, "Package " + pkg.packageName 7691 + " was transferred to another, but its .apk remains"); 7692 } 7693 7694 // See comments in nonMutatedPs declaration 7695 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7696 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 7697 if (foundPs != null) { 7698 nonMutatedPs = new PackageSetting(foundPs); 7699 } 7700 } 7701 7702 // Just create the setting, don't add it yet. For already existing packages 7703 // the PkgSetting exists already and doesn't have to be created. 7704 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7705 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7706 pkg.applicationInfo.primaryCpuAbi, 7707 pkg.applicationInfo.secondaryCpuAbi, 7708 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7709 user, false); 7710 if (pkgSetting == null) { 7711 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7712 "Creating application package " + pkg.packageName + " failed"); 7713 } 7714 7715 if (pkgSetting.origPackage != null) { 7716 // If we are first transitioning from an original package, 7717 // fix up the new package's name now. We need to do this after 7718 // looking up the package under its new name, so getPackageLP 7719 // can take care of fiddling things correctly. 7720 pkg.setPackageName(origPackage.name); 7721 7722 // File a report about this. 7723 String msg = "New package " + pkgSetting.realName 7724 + " renamed to replace old package " + pkgSetting.name; 7725 reportSettingsProblem(Log.WARN, msg); 7726 7727 // Make a note of it. 7728 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7729 mTransferedPackages.add(origPackage.name); 7730 } 7731 7732 // No longer need to retain this. 7733 pkgSetting.origPackage = null; 7734 } 7735 7736 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 7737 // Make a note of it. 7738 mTransferedPackages.add(pkg.packageName); 7739 } 7740 7741 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7742 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7743 } 7744 7745 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7746 // Check all shared libraries and map to their actual file path. 7747 // We only do this here for apps not on a system dir, because those 7748 // are the only ones that can fail an install due to this. We 7749 // will take care of the system apps by updating all of their 7750 // library paths after the scan is done. 7751 updateSharedLibrariesLPw(pkg, null); 7752 } 7753 7754 if (mFoundPolicyFile) { 7755 SELinuxMMAC.assignSeinfoValue(pkg); 7756 } 7757 7758 pkg.applicationInfo.uid = pkgSetting.appId; 7759 pkg.mExtras = pkgSetting; 7760 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7761 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7762 // We just determined the app is signed correctly, so bring 7763 // over the latest parsed certs. 7764 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7765 } else { 7766 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7767 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7768 "Package " + pkg.packageName + " upgrade keys do not match the " 7769 + "previously installed version"); 7770 } else { 7771 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7772 String msg = "System package " + pkg.packageName 7773 + " signature changed; retaining data."; 7774 reportSettingsProblem(Log.WARN, msg); 7775 } 7776 } 7777 } else { 7778 try { 7779 verifySignaturesLP(pkgSetting, pkg); 7780 // We just determined the app is signed correctly, so bring 7781 // over the latest parsed certs. 7782 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7783 } catch (PackageManagerException e) { 7784 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7785 throw e; 7786 } 7787 // The signature has changed, but this package is in the system 7788 // image... let's recover! 7789 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7790 // However... if this package is part of a shared user, but it 7791 // doesn't match the signature of the shared user, let's fail. 7792 // What this means is that you can't change the signatures 7793 // associated with an overall shared user, which doesn't seem all 7794 // that unreasonable. 7795 if (pkgSetting.sharedUser != null) { 7796 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7797 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7798 throw new PackageManagerException( 7799 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7800 "Signature mismatch for shared user: " 7801 + pkgSetting.sharedUser); 7802 } 7803 } 7804 // File a report about this. 7805 String msg = "System package " + pkg.packageName 7806 + " signature changed; retaining data."; 7807 reportSettingsProblem(Log.WARN, msg); 7808 } 7809 } 7810 // Verify that this new package doesn't have any content providers 7811 // that conflict with existing packages. Only do this if the 7812 // package isn't already installed, since we don't want to break 7813 // things that are installed. 7814 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7815 final int N = pkg.providers.size(); 7816 int i; 7817 for (i=0; i<N; i++) { 7818 PackageParser.Provider p = pkg.providers.get(i); 7819 if (p.info.authority != null) { 7820 String names[] = p.info.authority.split(";"); 7821 for (int j = 0; j < names.length; j++) { 7822 if (mProvidersByAuthority.containsKey(names[j])) { 7823 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7824 final String otherPackageName = 7825 ((other != null && other.getComponentName() != null) ? 7826 other.getComponentName().getPackageName() : "?"); 7827 throw new PackageManagerException( 7828 INSTALL_FAILED_CONFLICTING_PROVIDER, 7829 "Can't install because provider name " + names[j] 7830 + " (in package " + pkg.applicationInfo.packageName 7831 + ") is already used by " + otherPackageName); 7832 } 7833 } 7834 } 7835 } 7836 } 7837 7838 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 7839 // This package wants to adopt ownership of permissions from 7840 // another package. 7841 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7842 final String origName = pkg.mAdoptPermissions.get(i); 7843 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7844 if (orig != null) { 7845 if (verifyPackageUpdateLPr(orig, pkg)) { 7846 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7847 + pkg.packageName); 7848 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7849 } 7850 } 7851 } 7852 } 7853 } 7854 7855 final String pkgName = pkg.packageName; 7856 7857 final long scanFileTime = scanFile.lastModified(); 7858 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7859 pkg.applicationInfo.processName = fixProcessName( 7860 pkg.applicationInfo.packageName, 7861 pkg.applicationInfo.processName, 7862 pkg.applicationInfo.uid); 7863 7864 if (pkg != mPlatformPackage) { 7865 // Get all of our default paths setup 7866 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7867 } 7868 7869 final String path = scanFile.getPath(); 7870 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7871 7872 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7873 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7874 7875 // Some system apps still use directory structure for native libraries 7876 // in which case we might end up not detecting abi solely based on apk 7877 // structure. Try to detect abi based on directory structure. 7878 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7879 pkg.applicationInfo.primaryCpuAbi == null) { 7880 setBundledAppAbisAndRoots(pkg, pkgSetting); 7881 setNativeLibraryPaths(pkg); 7882 } 7883 7884 } else { 7885 if ((scanFlags & SCAN_MOVE) != 0) { 7886 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7887 // but we already have this packages package info in the PackageSetting. We just 7888 // use that and derive the native library path based on the new codepath. 7889 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7890 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7891 } 7892 7893 // Set native library paths again. For moves, the path will be updated based on the 7894 // ABIs we've determined above. For non-moves, the path will be updated based on the 7895 // ABIs we determined during compilation, but the path will depend on the final 7896 // package path (after the rename away from the stage path). 7897 setNativeLibraryPaths(pkg); 7898 } 7899 7900 // This is a special case for the "system" package, where the ABI is 7901 // dictated by the zygote configuration (and init.rc). We should keep track 7902 // of this ABI so that we can deal with "normal" applications that run under 7903 // the same UID correctly. 7904 if (mPlatformPackage == pkg) { 7905 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7906 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7907 } 7908 7909 // If there's a mismatch between the abi-override in the package setting 7910 // and the abiOverride specified for the install. Warn about this because we 7911 // would've already compiled the app without taking the package setting into 7912 // account. 7913 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7914 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7915 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7916 " for package " + pkg.packageName); 7917 } 7918 } 7919 7920 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7921 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7922 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7923 7924 // Copy the derived override back to the parsed package, so that we can 7925 // update the package settings accordingly. 7926 pkg.cpuAbiOverride = cpuAbiOverride; 7927 7928 if (DEBUG_ABI_SELECTION) { 7929 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7930 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7931 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7932 } 7933 7934 // Push the derived path down into PackageSettings so we know what to 7935 // clean up at uninstall time. 7936 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7937 7938 if (DEBUG_ABI_SELECTION) { 7939 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7940 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7941 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7942 } 7943 7944 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7945 // We don't do this here during boot because we can do it all 7946 // at once after scanning all existing packages. 7947 // 7948 // We also do this *before* we perform dexopt on this package, so that 7949 // we can avoid redundant dexopts, and also to make sure we've got the 7950 // code and package path correct. 7951 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7952 pkg, true /* boot complete */); 7953 } 7954 7955 if (mFactoryTest && pkg.requestedPermissions.contains( 7956 android.Manifest.permission.FACTORY_TEST)) { 7957 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7958 } 7959 7960 ArrayList<PackageParser.Package> clientLibPkgs = null; 7961 7962 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7963 if (nonMutatedPs != null) { 7964 synchronized (mPackages) { 7965 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 7966 } 7967 } 7968 return pkg; 7969 } 7970 7971 // Only privileged apps and updated privileged apps can add child packages. 7972 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 7973 if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) { 7974 throw new PackageManagerException("Only privileged apps and updated " 7975 + "privileged apps can add child packages. Ignoring package " 7976 + pkg.packageName); 7977 } 7978 final int childCount = pkg.childPackages.size(); 7979 for (int i = 0; i < childCount; i++) { 7980 PackageParser.Package childPkg = pkg.childPackages.get(i); 7981 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 7982 childPkg.packageName)) { 7983 throw new PackageManagerException("Cannot override a child package of " 7984 + "another disabled system app. Ignoring package " + pkg.packageName); 7985 } 7986 } 7987 } 7988 7989 // writer 7990 synchronized (mPackages) { 7991 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7992 // Only system apps can add new shared libraries. 7993 if (pkg.libraryNames != null) { 7994 for (int i=0; i<pkg.libraryNames.size(); i++) { 7995 String name = pkg.libraryNames.get(i); 7996 boolean allowed = false; 7997 if (pkg.isUpdatedSystemApp()) { 7998 // New library entries can only be added through the 7999 // system image. This is important to get rid of a lot 8000 // of nasty edge cases: for example if we allowed a non- 8001 // system update of the app to add a library, then uninstalling 8002 // the update would make the library go away, and assumptions 8003 // we made such as through app install filtering would now 8004 // have allowed apps on the device which aren't compatible 8005 // with it. Better to just have the restriction here, be 8006 // conservative, and create many fewer cases that can negatively 8007 // impact the user experience. 8008 final PackageSetting sysPs = mSettings 8009 .getDisabledSystemPkgLPr(pkg.packageName); 8010 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8011 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8012 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8013 allowed = true; 8014 break; 8015 } 8016 } 8017 } 8018 } else { 8019 allowed = true; 8020 } 8021 if (allowed) { 8022 if (!mSharedLibraries.containsKey(name)) { 8023 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8024 } else if (!name.equals(pkg.packageName)) { 8025 Slog.w(TAG, "Package " + pkg.packageName + " library " 8026 + name + " already exists; skipping"); 8027 } 8028 } else { 8029 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8030 + name + " that is not declared on system image; skipping"); 8031 } 8032 } 8033 if ((scanFlags & SCAN_BOOTING) == 0) { 8034 // If we are not booting, we need to update any applications 8035 // that are clients of our shared library. If we are booting, 8036 // this will all be done once the scan is complete. 8037 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8038 } 8039 } 8040 } 8041 } 8042 8043 // Request the ActivityManager to kill the process(only for existing packages) 8044 // so that we do not end up in a confused state while the user is still using the older 8045 // version of the application while the new one gets installed. 8046 final boolean isReplacing = (scanFlags & SCAN_REPLACING) != 0; 8047 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 8048 if (killApp) { 8049 if (isReplacing) { 8050 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 8051 8052 killApplication(pkg.applicationInfo.packageName, 8053 pkg.applicationInfo.uid, "replace pkg"); 8054 8055 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8056 } 8057 } 8058 8059 // Also need to kill any apps that are dependent on the library. 8060 if (clientLibPkgs != null) { 8061 for (int i=0; i<clientLibPkgs.size(); i++) { 8062 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8063 killApplication(clientPkg.applicationInfo.packageName, 8064 clientPkg.applicationInfo.uid, "update lib"); 8065 } 8066 } 8067 8068 // Make sure we're not adding any bogus keyset info 8069 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8070 ksms.assertScannedPackageValid(pkg); 8071 8072 // writer 8073 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8074 8075 boolean createIdmapFailed = false; 8076 synchronized (mPackages) { 8077 // We don't expect installation to fail beyond this point 8078 8079 // Add the new setting to mSettings 8080 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8081 // Add the new setting to mPackages 8082 mPackages.put(pkg.applicationInfo.packageName, pkg); 8083 // Make sure we don't accidentally delete its data. 8084 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8085 while (iter.hasNext()) { 8086 PackageCleanItem item = iter.next(); 8087 if (pkgName.equals(item.packageName)) { 8088 iter.remove(); 8089 } 8090 } 8091 8092 // Take care of first install / last update times. 8093 if (currentTime != 0) { 8094 if (pkgSetting.firstInstallTime == 0) { 8095 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8096 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8097 pkgSetting.lastUpdateTime = currentTime; 8098 } 8099 } else if (pkgSetting.firstInstallTime == 0) { 8100 // We need *something*. Take time time stamp of the file. 8101 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8102 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8103 if (scanFileTime != pkgSetting.timeStamp) { 8104 // A package on the system image has changed; consider this 8105 // to be an update. 8106 pkgSetting.lastUpdateTime = scanFileTime; 8107 } 8108 } 8109 8110 // Add the package's KeySets to the global KeySetManagerService 8111 ksms.addScannedPackageLPw(pkg); 8112 8113 int N = pkg.providers.size(); 8114 StringBuilder r = null; 8115 int i; 8116 for (i=0; i<N; i++) { 8117 PackageParser.Provider p = pkg.providers.get(i); 8118 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8119 p.info.processName, pkg.applicationInfo.uid); 8120 mProviders.addProvider(p); 8121 p.syncable = p.info.isSyncable; 8122 if (p.info.authority != null) { 8123 String names[] = p.info.authority.split(";"); 8124 p.info.authority = null; 8125 for (int j = 0; j < names.length; j++) { 8126 if (j == 1 && p.syncable) { 8127 // We only want the first authority for a provider to possibly be 8128 // syncable, so if we already added this provider using a different 8129 // authority clear the syncable flag. We copy the provider before 8130 // changing it because the mProviders object contains a reference 8131 // to a provider that we don't want to change. 8132 // Only do this for the second authority since the resulting provider 8133 // object can be the same for all future authorities for this provider. 8134 p = new PackageParser.Provider(p); 8135 p.syncable = false; 8136 } 8137 if (!mProvidersByAuthority.containsKey(names[j])) { 8138 mProvidersByAuthority.put(names[j], p); 8139 if (p.info.authority == null) { 8140 p.info.authority = names[j]; 8141 } else { 8142 p.info.authority = p.info.authority + ";" + names[j]; 8143 } 8144 if (DEBUG_PACKAGE_SCANNING) { 8145 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 8146 Log.d(TAG, "Registered content provider: " + names[j] 8147 + ", className = " + p.info.name + ", isSyncable = " 8148 + p.info.isSyncable); 8149 } 8150 } else { 8151 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8152 Slog.w(TAG, "Skipping provider name " + names[j] + 8153 " (in package " + pkg.applicationInfo.packageName + 8154 "): name already used by " 8155 + ((other != null && other.getComponentName() != null) 8156 ? other.getComponentName().getPackageName() : "?")); 8157 } 8158 } 8159 } 8160 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8161 if (r == null) { 8162 r = new StringBuilder(256); 8163 } else { 8164 r.append(' '); 8165 } 8166 r.append(p.info.name); 8167 } 8168 } 8169 if (r != null) { 8170 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8171 } 8172 8173 N = pkg.services.size(); 8174 r = null; 8175 for (i=0; i<N; i++) { 8176 PackageParser.Service s = pkg.services.get(i); 8177 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8178 s.info.processName, pkg.applicationInfo.uid); 8179 mServices.addService(s); 8180 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8181 if (r == null) { 8182 r = new StringBuilder(256); 8183 } else { 8184 r.append(' '); 8185 } 8186 r.append(s.info.name); 8187 } 8188 } 8189 if (r != null) { 8190 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8191 } 8192 8193 N = pkg.receivers.size(); 8194 r = null; 8195 for (i=0; i<N; i++) { 8196 PackageParser.Activity a = pkg.receivers.get(i); 8197 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8198 a.info.processName, pkg.applicationInfo.uid); 8199 mReceivers.addActivity(a, "receiver"); 8200 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8201 if (r == null) { 8202 r = new StringBuilder(256); 8203 } else { 8204 r.append(' '); 8205 } 8206 r.append(a.info.name); 8207 } 8208 } 8209 if (r != null) { 8210 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8211 } 8212 8213 N = pkg.activities.size(); 8214 r = null; 8215 for (i=0; i<N; i++) { 8216 PackageParser.Activity a = pkg.activities.get(i); 8217 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8218 a.info.processName, pkg.applicationInfo.uid); 8219 mActivities.addActivity(a, "activity"); 8220 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8221 if (r == null) { 8222 r = new StringBuilder(256); 8223 } else { 8224 r.append(' '); 8225 } 8226 r.append(a.info.name); 8227 } 8228 } 8229 if (r != null) { 8230 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8231 } 8232 8233 N = pkg.permissionGroups.size(); 8234 r = null; 8235 for (i=0; i<N; i++) { 8236 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8237 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8238 if (cur == null) { 8239 mPermissionGroups.put(pg.info.name, pg); 8240 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8241 if (r == null) { 8242 r = new StringBuilder(256); 8243 } else { 8244 r.append(' '); 8245 } 8246 r.append(pg.info.name); 8247 } 8248 } else { 8249 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8250 + pg.info.packageName + " ignored: original from " 8251 + cur.info.packageName); 8252 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8253 if (r == null) { 8254 r = new StringBuilder(256); 8255 } else { 8256 r.append(' '); 8257 } 8258 r.append("DUP:"); 8259 r.append(pg.info.name); 8260 } 8261 } 8262 } 8263 if (r != null) { 8264 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8265 } 8266 8267 N = pkg.permissions.size(); 8268 r = null; 8269 for (i=0; i<N; i++) { 8270 PackageParser.Permission p = pkg.permissions.get(i); 8271 8272 // Assume by default that we did not install this permission into the system. 8273 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8274 8275 // Now that permission groups have a special meaning, we ignore permission 8276 // groups for legacy apps to prevent unexpected behavior. In particular, 8277 // permissions for one app being granted to someone just becase they happen 8278 // to be in a group defined by another app (before this had no implications). 8279 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8280 p.group = mPermissionGroups.get(p.info.group); 8281 // Warn for a permission in an unknown group. 8282 if (p.info.group != null && p.group == null) { 8283 Slog.w(TAG, "Permission " + p.info.name + " from package " 8284 + p.info.packageName + " in an unknown group " + p.info.group); 8285 } 8286 } 8287 8288 ArrayMap<String, BasePermission> permissionMap = 8289 p.tree ? mSettings.mPermissionTrees 8290 : mSettings.mPermissions; 8291 BasePermission bp = permissionMap.get(p.info.name); 8292 8293 // Allow system apps to redefine non-system permissions 8294 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8295 final boolean currentOwnerIsSystem = (bp.perm != null 8296 && isSystemApp(bp.perm.owner)); 8297 if (isSystemApp(p.owner)) { 8298 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8299 // It's a built-in permission and no owner, take ownership now 8300 bp.packageSetting = pkgSetting; 8301 bp.perm = p; 8302 bp.uid = pkg.applicationInfo.uid; 8303 bp.sourcePackage = p.info.packageName; 8304 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8305 } else if (!currentOwnerIsSystem) { 8306 String msg = "New decl " + p.owner + " of permission " 8307 + p.info.name + " is system; overriding " + bp.sourcePackage; 8308 reportSettingsProblem(Log.WARN, msg); 8309 bp = null; 8310 } 8311 } 8312 } 8313 8314 if (bp == null) { 8315 bp = new BasePermission(p.info.name, p.info.packageName, 8316 BasePermission.TYPE_NORMAL); 8317 permissionMap.put(p.info.name, bp); 8318 } 8319 8320 if (bp.perm == null) { 8321 if (bp.sourcePackage == null 8322 || bp.sourcePackage.equals(p.info.packageName)) { 8323 BasePermission tree = findPermissionTreeLP(p.info.name); 8324 if (tree == null 8325 || tree.sourcePackage.equals(p.info.packageName)) { 8326 bp.packageSetting = pkgSetting; 8327 bp.perm = p; 8328 bp.uid = pkg.applicationInfo.uid; 8329 bp.sourcePackage = p.info.packageName; 8330 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8331 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8332 if (r == null) { 8333 r = new StringBuilder(256); 8334 } else { 8335 r.append(' '); 8336 } 8337 r.append(p.info.name); 8338 } 8339 } else { 8340 Slog.w(TAG, "Permission " + p.info.name + " from package " 8341 + p.info.packageName + " ignored: base tree " 8342 + tree.name + " is from package " 8343 + tree.sourcePackage); 8344 } 8345 } else { 8346 Slog.w(TAG, "Permission " + p.info.name + " from package " 8347 + p.info.packageName + " ignored: original from " 8348 + bp.sourcePackage); 8349 } 8350 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8351 if (r == null) { 8352 r = new StringBuilder(256); 8353 } else { 8354 r.append(' '); 8355 } 8356 r.append("DUP:"); 8357 r.append(p.info.name); 8358 } 8359 if (bp.perm == p) { 8360 bp.protectionLevel = p.info.protectionLevel; 8361 } 8362 } 8363 8364 if (r != null) { 8365 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8366 } 8367 8368 N = pkg.instrumentation.size(); 8369 r = null; 8370 for (i=0; i<N; i++) { 8371 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8372 a.info.packageName = pkg.applicationInfo.packageName; 8373 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8374 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8375 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8376 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8377 a.info.dataDir = pkg.applicationInfo.dataDir; 8378 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8379 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8380 8381 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8382 // need other information about the application, like the ABI and what not ? 8383 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8384 mInstrumentation.put(a.getComponentName(), a); 8385 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8386 if (r == null) { 8387 r = new StringBuilder(256); 8388 } else { 8389 r.append(' '); 8390 } 8391 r.append(a.info.name); 8392 } 8393 } 8394 if (r != null) { 8395 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8396 } 8397 8398 if (pkg.protectedBroadcasts != null) { 8399 N = pkg.protectedBroadcasts.size(); 8400 for (i=0; i<N; i++) { 8401 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8402 } 8403 } 8404 8405 pkgSetting.setTimeStamp(scanFileTime); 8406 8407 // Create idmap files for pairs of (packages, overlay packages). 8408 // Note: "android", ie framework-res.apk, is handled by native layers. 8409 if (pkg.mOverlayTarget != null) { 8410 // This is an overlay package. 8411 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8412 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8413 mOverlays.put(pkg.mOverlayTarget, 8414 new ArrayMap<String, PackageParser.Package>()); 8415 } 8416 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8417 map.put(pkg.packageName, pkg); 8418 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8419 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8420 createIdmapFailed = true; 8421 } 8422 } 8423 } else if (mOverlays.containsKey(pkg.packageName) && 8424 !pkg.packageName.equals("android")) { 8425 // This is a regular package, with one or more known overlay packages. 8426 createIdmapsForPackageLI(pkg); 8427 } 8428 } 8429 8430 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8431 8432 if (createIdmapFailed) { 8433 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8434 "scanPackageLI failed to createIdmap"); 8435 } 8436 return pkg; 8437 } 8438 8439 /** 8440 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8441 * is derived purely on the basis of the contents of {@code scanFile} and 8442 * {@code cpuAbiOverride}. 8443 * 8444 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8445 */ 8446 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8447 String cpuAbiOverride, boolean extractLibs) 8448 throws PackageManagerException { 8449 // TODO: We can probably be smarter about this stuff. For installed apps, 8450 // we can calculate this information at install time once and for all. For 8451 // system apps, we can probably assume that this information doesn't change 8452 // after the first boot scan. As things stand, we do lots of unnecessary work. 8453 8454 // Give ourselves some initial paths; we'll come back for another 8455 // pass once we've determined ABI below. 8456 setNativeLibraryPaths(pkg); 8457 8458 // We would never need to extract libs for forward-locked and external packages, 8459 // since the container service will do it for us. We shouldn't attempt to 8460 // extract libs from system app when it was not updated. 8461 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8462 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8463 extractLibs = false; 8464 } 8465 8466 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8467 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8468 8469 NativeLibraryHelper.Handle handle = null; 8470 try { 8471 handle = NativeLibraryHelper.Handle.create(pkg); 8472 // TODO(multiArch): This can be null for apps that didn't go through the 8473 // usual installation process. We can calculate it again, like we 8474 // do during install time. 8475 // 8476 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8477 // unnecessary. 8478 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8479 8480 // Null out the abis so that they can be recalculated. 8481 pkg.applicationInfo.primaryCpuAbi = null; 8482 pkg.applicationInfo.secondaryCpuAbi = null; 8483 if (isMultiArch(pkg.applicationInfo)) { 8484 // Warn if we've set an abiOverride for multi-lib packages.. 8485 // By definition, we need to copy both 32 and 64 bit libraries for 8486 // such packages. 8487 if (pkg.cpuAbiOverride != null 8488 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8489 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8490 } 8491 8492 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8493 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8494 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8495 if (extractLibs) { 8496 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8497 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8498 useIsaSpecificSubdirs); 8499 } else { 8500 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8501 } 8502 } 8503 8504 maybeThrowExceptionForMultiArchCopy( 8505 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8506 8507 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8508 if (extractLibs) { 8509 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8510 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8511 useIsaSpecificSubdirs); 8512 } else { 8513 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8514 } 8515 } 8516 8517 maybeThrowExceptionForMultiArchCopy( 8518 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8519 8520 if (abi64 >= 0) { 8521 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8522 } 8523 8524 if (abi32 >= 0) { 8525 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8526 if (abi64 >= 0) { 8527 if (cpuAbiOverride == null && pkg.use32bitAbi) { 8528 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8529 pkg.applicationInfo.primaryCpuAbi = abi; 8530 } else { 8531 pkg.applicationInfo.secondaryCpuAbi = abi; 8532 } 8533 } else { 8534 pkg.applicationInfo.primaryCpuAbi = abi; 8535 } 8536 } 8537 8538 } else { 8539 String[] abiList = (cpuAbiOverride != null) ? 8540 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8541 8542 // Enable gross and lame hacks for apps that are built with old 8543 // SDK tools. We must scan their APKs for renderscript bitcode and 8544 // not launch them if it's present. Don't bother checking on devices 8545 // that don't have 64 bit support. 8546 boolean needsRenderScriptOverride = false; 8547 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8548 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8549 abiList = Build.SUPPORTED_32_BIT_ABIS; 8550 needsRenderScriptOverride = true; 8551 } 8552 8553 final int copyRet; 8554 if (extractLibs) { 8555 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8556 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8557 } else { 8558 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8559 } 8560 8561 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8562 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8563 "Error unpackaging native libs for app, errorCode=" + copyRet); 8564 } 8565 8566 if (copyRet >= 0) { 8567 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8568 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8569 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8570 } else if (needsRenderScriptOverride) { 8571 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8572 } 8573 } 8574 } catch (IOException ioe) { 8575 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8576 } finally { 8577 IoUtils.closeQuietly(handle); 8578 } 8579 8580 // Now that we've calculated the ABIs and determined if it's an internal app, 8581 // we will go ahead and populate the nativeLibraryPath. 8582 setNativeLibraryPaths(pkg); 8583 } 8584 8585 /** 8586 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8587 * i.e, so that all packages can be run inside a single process if required. 8588 * 8589 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8590 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8591 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8592 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8593 * updating a package that belongs to a shared user. 8594 * 8595 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8596 * adds unnecessary complexity. 8597 */ 8598 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8599 PackageParser.Package scannedPackage, boolean bootComplete) { 8600 String requiredInstructionSet = null; 8601 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8602 requiredInstructionSet = VMRuntime.getInstructionSet( 8603 scannedPackage.applicationInfo.primaryCpuAbi); 8604 } 8605 8606 PackageSetting requirer = null; 8607 for (PackageSetting ps : packagesForUser) { 8608 // If packagesForUser contains scannedPackage, we skip it. This will happen 8609 // when scannedPackage is an update of an existing package. Without this check, 8610 // we will never be able to change the ABI of any package belonging to a shared 8611 // user, even if it's compatible with other packages. 8612 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8613 if (ps.primaryCpuAbiString == null) { 8614 continue; 8615 } 8616 8617 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8618 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8619 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8620 // this but there's not much we can do. 8621 String errorMessage = "Instruction set mismatch, " 8622 + ((requirer == null) ? "[caller]" : requirer) 8623 + " requires " + requiredInstructionSet + " whereas " + ps 8624 + " requires " + instructionSet; 8625 Slog.w(TAG, errorMessage); 8626 } 8627 8628 if (requiredInstructionSet == null) { 8629 requiredInstructionSet = instructionSet; 8630 requirer = ps; 8631 } 8632 } 8633 } 8634 8635 if (requiredInstructionSet != null) { 8636 String adjustedAbi; 8637 if (requirer != null) { 8638 // requirer != null implies that either scannedPackage was null or that scannedPackage 8639 // did not require an ABI, in which case we have to adjust scannedPackage to match 8640 // the ABI of the set (which is the same as requirer's ABI) 8641 adjustedAbi = requirer.primaryCpuAbiString; 8642 if (scannedPackage != null) { 8643 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8644 } 8645 } else { 8646 // requirer == null implies that we're updating all ABIs in the set to 8647 // match scannedPackage. 8648 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8649 } 8650 8651 for (PackageSetting ps : packagesForUser) { 8652 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8653 if (ps.primaryCpuAbiString != null) { 8654 continue; 8655 } 8656 8657 ps.primaryCpuAbiString = adjustedAbi; 8658 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8659 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8660 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8661 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8662 + " (requirer=" 8663 + (requirer == null ? "null" : requirer.pkg.packageName) 8664 + ", scannedPackage=" 8665 + (scannedPackage != null ? scannedPackage.packageName : "null") 8666 + ")"); 8667 try { 8668 mInstaller.rmdex(ps.codePathString, 8669 getDexCodeInstructionSet(getPreferredInstructionSet())); 8670 } catch (InstallerException ignored) { 8671 } 8672 } 8673 } 8674 } 8675 } 8676 } 8677 8678 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8679 synchronized (mPackages) { 8680 mResolverReplaced = true; 8681 // Set up information for custom user intent resolution activity. 8682 mResolveActivity.applicationInfo = pkg.applicationInfo; 8683 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8684 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8685 mResolveActivity.processName = pkg.applicationInfo.packageName; 8686 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8687 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8688 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8689 mResolveActivity.theme = 0; 8690 mResolveActivity.exported = true; 8691 mResolveActivity.enabled = true; 8692 mResolveInfo.activityInfo = mResolveActivity; 8693 mResolveInfo.priority = 0; 8694 mResolveInfo.preferredOrder = 0; 8695 mResolveInfo.match = 0; 8696 mResolveComponentName = mCustomResolverComponentName; 8697 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8698 mResolveComponentName); 8699 } 8700 } 8701 8702 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8703 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8704 8705 // Set up information for ephemeral installer activity 8706 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8707 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8708 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8709 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8710 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8711 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8712 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8713 mEphemeralInstallerActivity.theme = 0; 8714 mEphemeralInstallerActivity.exported = true; 8715 mEphemeralInstallerActivity.enabled = true; 8716 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8717 mEphemeralInstallerInfo.priority = 0; 8718 mEphemeralInstallerInfo.preferredOrder = 0; 8719 mEphemeralInstallerInfo.match = 0; 8720 8721 if (DEBUG_EPHEMERAL) { 8722 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8723 } 8724 } 8725 8726 private static String calculateBundledApkRoot(final String codePathString) { 8727 final File codePath = new File(codePathString); 8728 final File codeRoot; 8729 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8730 codeRoot = Environment.getRootDirectory(); 8731 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8732 codeRoot = Environment.getOemDirectory(); 8733 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8734 codeRoot = Environment.getVendorDirectory(); 8735 } else { 8736 // Unrecognized code path; take its top real segment as the apk root: 8737 // e.g. /something/app/blah.apk => /something 8738 try { 8739 File f = codePath.getCanonicalFile(); 8740 File parent = f.getParentFile(); // non-null because codePath is a file 8741 File tmp; 8742 while ((tmp = parent.getParentFile()) != null) { 8743 f = parent; 8744 parent = tmp; 8745 } 8746 codeRoot = f; 8747 Slog.w(TAG, "Unrecognized code path " 8748 + codePath + " - using " + codeRoot); 8749 } catch (IOException e) { 8750 // Can't canonicalize the code path -- shenanigans? 8751 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8752 return Environment.getRootDirectory().getPath(); 8753 } 8754 } 8755 return codeRoot.getPath(); 8756 } 8757 8758 /** 8759 * Derive and set the location of native libraries for the given package, 8760 * which varies depending on where and how the package was installed. 8761 */ 8762 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8763 final ApplicationInfo info = pkg.applicationInfo; 8764 final String codePath = pkg.codePath; 8765 final File codeFile = new File(codePath); 8766 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8767 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8768 8769 info.nativeLibraryRootDir = null; 8770 info.nativeLibraryRootRequiresIsa = false; 8771 info.nativeLibraryDir = null; 8772 info.secondaryNativeLibraryDir = null; 8773 8774 if (isApkFile(codeFile)) { 8775 // Monolithic install 8776 if (bundledApp) { 8777 // If "/system/lib64/apkname" exists, assume that is the per-package 8778 // native library directory to use; otherwise use "/system/lib/apkname". 8779 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8780 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8781 getPrimaryInstructionSet(info)); 8782 8783 // This is a bundled system app so choose the path based on the ABI. 8784 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8785 // is just the default path. 8786 final String apkName = deriveCodePathName(codePath); 8787 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8788 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8789 apkName).getAbsolutePath(); 8790 8791 if (info.secondaryCpuAbi != null) { 8792 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8793 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8794 secondaryLibDir, apkName).getAbsolutePath(); 8795 } 8796 } else if (asecApp) { 8797 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8798 .getAbsolutePath(); 8799 } else { 8800 final String apkName = deriveCodePathName(codePath); 8801 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8802 .getAbsolutePath(); 8803 } 8804 8805 info.nativeLibraryRootRequiresIsa = false; 8806 info.nativeLibraryDir = info.nativeLibraryRootDir; 8807 } else { 8808 // Cluster install 8809 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8810 info.nativeLibraryRootRequiresIsa = true; 8811 8812 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8813 getPrimaryInstructionSet(info)).getAbsolutePath(); 8814 8815 if (info.secondaryCpuAbi != null) { 8816 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8817 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8818 } 8819 } 8820 } 8821 8822 /** 8823 * Calculate the abis and roots for a bundled app. These can uniquely 8824 * be determined from the contents of the system partition, i.e whether 8825 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8826 * of this information, and instead assume that the system was built 8827 * sensibly. 8828 */ 8829 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8830 PackageSetting pkgSetting) { 8831 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8832 8833 // If "/system/lib64/apkname" exists, assume that is the per-package 8834 // native library directory to use; otherwise use "/system/lib/apkname". 8835 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8836 setBundledAppAbi(pkg, apkRoot, apkName); 8837 // pkgSetting might be null during rescan following uninstall of updates 8838 // to a bundled app, so accommodate that possibility. The settings in 8839 // that case will be established later from the parsed package. 8840 // 8841 // If the settings aren't null, sync them up with what we've just derived. 8842 // note that apkRoot isn't stored in the package settings. 8843 if (pkgSetting != null) { 8844 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8845 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8846 } 8847 } 8848 8849 /** 8850 * Deduces the ABI of a bundled app and sets the relevant fields on the 8851 * parsed pkg object. 8852 * 8853 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8854 * under which system libraries are installed. 8855 * @param apkName the name of the installed package. 8856 */ 8857 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8858 final File codeFile = new File(pkg.codePath); 8859 8860 final boolean has64BitLibs; 8861 final boolean has32BitLibs; 8862 if (isApkFile(codeFile)) { 8863 // Monolithic install 8864 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8865 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8866 } else { 8867 // Cluster install 8868 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8869 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8870 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8871 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8872 has64BitLibs = (new File(rootDir, isa)).exists(); 8873 } else { 8874 has64BitLibs = false; 8875 } 8876 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8877 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8878 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8879 has32BitLibs = (new File(rootDir, isa)).exists(); 8880 } else { 8881 has32BitLibs = false; 8882 } 8883 } 8884 8885 if (has64BitLibs && !has32BitLibs) { 8886 // The package has 64 bit libs, but not 32 bit libs. Its primary 8887 // ABI should be 64 bit. We can safely assume here that the bundled 8888 // native libraries correspond to the most preferred ABI in the list. 8889 8890 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8891 pkg.applicationInfo.secondaryCpuAbi = null; 8892 } else if (has32BitLibs && !has64BitLibs) { 8893 // The package has 32 bit libs but not 64 bit libs. Its primary 8894 // ABI should be 32 bit. 8895 8896 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8897 pkg.applicationInfo.secondaryCpuAbi = null; 8898 } else if (has32BitLibs && has64BitLibs) { 8899 // The application has both 64 and 32 bit bundled libraries. We check 8900 // here that the app declares multiArch support, and warn if it doesn't. 8901 // 8902 // We will be lenient here and record both ABIs. The primary will be the 8903 // ABI that's higher on the list, i.e, a device that's configured to prefer 8904 // 64 bit apps will see a 64 bit primary ABI, 8905 8906 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8907 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 8908 } 8909 8910 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8911 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8912 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8913 } else { 8914 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8915 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8916 } 8917 } else { 8918 pkg.applicationInfo.primaryCpuAbi = null; 8919 pkg.applicationInfo.secondaryCpuAbi = null; 8920 } 8921 } 8922 8923 private void killPackage(PackageParser.Package pkg, String reason) { 8924 // Kill the parent package 8925 killApplication(pkg.packageName, pkg.applicationInfo.uid, reason); 8926 // Kill the child packages 8927 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8928 for (int i = 0; i < childCount; i++) { 8929 PackageParser.Package childPkg = pkg.childPackages.get(i); 8930 killApplication(childPkg.packageName, childPkg.applicationInfo.uid, reason); 8931 } 8932 } 8933 8934 private void killApplication(String pkgName, int appId, String reason) { 8935 // Request the ActivityManager to kill the process(only for existing packages) 8936 // so that we do not end up in a confused state while the user is still using the older 8937 // version of the application while the new one gets installed. 8938 IActivityManager am = ActivityManagerNative.getDefault(); 8939 if (am != null) { 8940 try { 8941 am.killApplicationWithAppId(pkgName, appId, reason); 8942 } catch (RemoteException e) { 8943 } 8944 } 8945 } 8946 8947 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 8948 // Remove the parent package setting 8949 PackageSetting ps = (PackageSetting) pkg.mExtras; 8950 if (ps != null) { 8951 removePackageLI(ps, chatty); 8952 } 8953 // Remove the child package setting 8954 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8955 for (int i = 0; i < childCount; i++) { 8956 PackageParser.Package childPkg = pkg.childPackages.get(i); 8957 ps = (PackageSetting) childPkg.mExtras; 8958 if (ps != null) { 8959 removePackageLI(ps, chatty); 8960 } 8961 } 8962 } 8963 8964 void removePackageLI(PackageSetting ps, boolean chatty) { 8965 if (DEBUG_INSTALL) { 8966 if (chatty) 8967 Log.d(TAG, "Removing package " + ps.name); 8968 } 8969 8970 // writer 8971 synchronized (mPackages) { 8972 mPackages.remove(ps.name); 8973 final PackageParser.Package pkg = ps.pkg; 8974 if (pkg != null) { 8975 cleanPackageDataStructuresLILPw(pkg, chatty); 8976 } 8977 } 8978 } 8979 8980 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8981 if (DEBUG_INSTALL) { 8982 if (chatty) 8983 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8984 } 8985 8986 // writer 8987 synchronized (mPackages) { 8988 // Remove the parent package 8989 mPackages.remove(pkg.applicationInfo.packageName); 8990 cleanPackageDataStructuresLILPw(pkg, chatty); 8991 8992 // Remove the child packages 8993 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8994 for (int i = 0; i < childCount; i++) { 8995 PackageParser.Package childPkg = pkg.childPackages.get(i); 8996 mPackages.remove(childPkg.applicationInfo.packageName); 8997 cleanPackageDataStructuresLILPw(childPkg, chatty); 8998 } 8999 } 9000 } 9001 9002 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9003 int N = pkg.providers.size(); 9004 StringBuilder r = null; 9005 int i; 9006 for (i=0; i<N; i++) { 9007 PackageParser.Provider p = pkg.providers.get(i); 9008 mProviders.removeProvider(p); 9009 if (p.info.authority == null) { 9010 9011 /* There was another ContentProvider with this authority when 9012 * this app was installed so this authority is null, 9013 * Ignore it as we don't have to unregister the provider. 9014 */ 9015 continue; 9016 } 9017 String names[] = p.info.authority.split(";"); 9018 for (int j = 0; j < names.length; j++) { 9019 if (mProvidersByAuthority.get(names[j]) == p) { 9020 mProvidersByAuthority.remove(names[j]); 9021 if (DEBUG_REMOVE) { 9022 if (chatty) 9023 Log.d(TAG, "Unregistered content provider: " + names[j] 9024 + ", className = " + p.info.name + ", isSyncable = " 9025 + p.info.isSyncable); 9026 } 9027 } 9028 } 9029 if (DEBUG_REMOVE && chatty) { 9030 if (r == null) { 9031 r = new StringBuilder(256); 9032 } else { 9033 r.append(' '); 9034 } 9035 r.append(p.info.name); 9036 } 9037 } 9038 if (r != null) { 9039 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9040 } 9041 9042 N = pkg.services.size(); 9043 r = null; 9044 for (i=0; i<N; i++) { 9045 PackageParser.Service s = pkg.services.get(i); 9046 mServices.removeService(s); 9047 if (chatty) { 9048 if (r == null) { 9049 r = new StringBuilder(256); 9050 } else { 9051 r.append(' '); 9052 } 9053 r.append(s.info.name); 9054 } 9055 } 9056 if (r != null) { 9057 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9058 } 9059 9060 N = pkg.receivers.size(); 9061 r = null; 9062 for (i=0; i<N; i++) { 9063 PackageParser.Activity a = pkg.receivers.get(i); 9064 mReceivers.removeActivity(a, "receiver"); 9065 if (DEBUG_REMOVE && chatty) { 9066 if (r == null) { 9067 r = new StringBuilder(256); 9068 } else { 9069 r.append(' '); 9070 } 9071 r.append(a.info.name); 9072 } 9073 } 9074 if (r != null) { 9075 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9076 } 9077 9078 N = pkg.activities.size(); 9079 r = null; 9080 for (i=0; i<N; i++) { 9081 PackageParser.Activity a = pkg.activities.get(i); 9082 mActivities.removeActivity(a, "activity"); 9083 if (DEBUG_REMOVE && chatty) { 9084 if (r == null) { 9085 r = new StringBuilder(256); 9086 } else { 9087 r.append(' '); 9088 } 9089 r.append(a.info.name); 9090 } 9091 } 9092 if (r != null) { 9093 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9094 } 9095 9096 N = pkg.permissions.size(); 9097 r = null; 9098 for (i=0; i<N; i++) { 9099 PackageParser.Permission p = pkg.permissions.get(i); 9100 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9101 if (bp == null) { 9102 bp = mSettings.mPermissionTrees.get(p.info.name); 9103 } 9104 if (bp != null && bp.perm == p) { 9105 bp.perm = null; 9106 if (DEBUG_REMOVE && chatty) { 9107 if (r == null) { 9108 r = new StringBuilder(256); 9109 } else { 9110 r.append(' '); 9111 } 9112 r.append(p.info.name); 9113 } 9114 } 9115 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9116 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9117 if (appOpPkgs != null) { 9118 appOpPkgs.remove(pkg.packageName); 9119 } 9120 } 9121 } 9122 if (r != null) { 9123 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9124 } 9125 9126 N = pkg.requestedPermissions.size(); 9127 r = null; 9128 for (i=0; i<N; i++) { 9129 String perm = pkg.requestedPermissions.get(i); 9130 BasePermission bp = mSettings.mPermissions.get(perm); 9131 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9132 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9133 if (appOpPkgs != null) { 9134 appOpPkgs.remove(pkg.packageName); 9135 if (appOpPkgs.isEmpty()) { 9136 mAppOpPermissionPackages.remove(perm); 9137 } 9138 } 9139 } 9140 } 9141 if (r != null) { 9142 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9143 } 9144 9145 N = pkg.instrumentation.size(); 9146 r = null; 9147 for (i=0; i<N; i++) { 9148 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9149 mInstrumentation.remove(a.getComponentName()); 9150 if (DEBUG_REMOVE && chatty) { 9151 if (r == null) { 9152 r = new StringBuilder(256); 9153 } else { 9154 r.append(' '); 9155 } 9156 r.append(a.info.name); 9157 } 9158 } 9159 if (r != null) { 9160 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9161 } 9162 9163 r = null; 9164 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9165 // Only system apps can hold shared libraries. 9166 if (pkg.libraryNames != null) { 9167 for (i=0; i<pkg.libraryNames.size(); i++) { 9168 String name = pkg.libraryNames.get(i); 9169 SharedLibraryEntry cur = mSharedLibraries.get(name); 9170 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9171 mSharedLibraries.remove(name); 9172 if (DEBUG_REMOVE && chatty) { 9173 if (r == null) { 9174 r = new StringBuilder(256); 9175 } else { 9176 r.append(' '); 9177 } 9178 r.append(name); 9179 } 9180 } 9181 } 9182 } 9183 } 9184 if (r != null) { 9185 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9186 } 9187 } 9188 9189 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9190 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9191 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9192 return true; 9193 } 9194 } 9195 return false; 9196 } 9197 9198 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9199 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9200 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9201 9202 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9203 // Update the parent permissions 9204 updatePermissionsLPw(pkg.packageName, pkg, flags); 9205 // Update the child permissions 9206 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9207 for (int i = 0; i < childCount; i++) { 9208 PackageParser.Package childPkg = pkg.childPackages.get(i); 9209 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9210 } 9211 } 9212 9213 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9214 int flags) { 9215 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9216 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9217 } 9218 9219 private void updatePermissionsLPw(String changingPkg, 9220 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9221 // Make sure there are no dangling permission trees. 9222 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9223 while (it.hasNext()) { 9224 final BasePermission bp = it.next(); 9225 if (bp.packageSetting == null) { 9226 // We may not yet have parsed the package, so just see if 9227 // we still know about its settings. 9228 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9229 } 9230 if (bp.packageSetting == null) { 9231 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9232 + " from package " + bp.sourcePackage); 9233 it.remove(); 9234 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9235 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9236 Slog.i(TAG, "Removing old permission tree: " + bp.name 9237 + " from package " + bp.sourcePackage); 9238 flags |= UPDATE_PERMISSIONS_ALL; 9239 it.remove(); 9240 } 9241 } 9242 } 9243 9244 // Make sure all dynamic permissions have been assigned to a package, 9245 // and make sure there are no dangling permissions. 9246 it = mSettings.mPermissions.values().iterator(); 9247 while (it.hasNext()) { 9248 final BasePermission bp = it.next(); 9249 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9250 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9251 + bp.name + " pkg=" + bp.sourcePackage 9252 + " info=" + bp.pendingInfo); 9253 if (bp.packageSetting == null && bp.pendingInfo != null) { 9254 final BasePermission tree = findPermissionTreeLP(bp.name); 9255 if (tree != null && tree.perm != null) { 9256 bp.packageSetting = tree.packageSetting; 9257 bp.perm = new PackageParser.Permission(tree.perm.owner, 9258 new PermissionInfo(bp.pendingInfo)); 9259 bp.perm.info.packageName = tree.perm.info.packageName; 9260 bp.perm.info.name = bp.name; 9261 bp.uid = tree.uid; 9262 } 9263 } 9264 } 9265 if (bp.packageSetting == null) { 9266 // We may not yet have parsed the package, so just see if 9267 // we still know about its settings. 9268 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9269 } 9270 if (bp.packageSetting == null) { 9271 Slog.w(TAG, "Removing dangling permission: " + bp.name 9272 + " from package " + bp.sourcePackage); 9273 it.remove(); 9274 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9275 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9276 Slog.i(TAG, "Removing old permission: " + bp.name 9277 + " from package " + bp.sourcePackage); 9278 flags |= UPDATE_PERMISSIONS_ALL; 9279 it.remove(); 9280 } 9281 } 9282 } 9283 9284 // Now update the permissions for all packages, in particular 9285 // replace the granted permissions of the system packages. 9286 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9287 for (PackageParser.Package pkg : mPackages.values()) { 9288 if (pkg != pkgInfo) { 9289 // Only replace for packages on requested volume 9290 final String volumeUuid = getVolumeUuidForPackage(pkg); 9291 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9292 && Objects.equals(replaceVolumeUuid, volumeUuid); 9293 grantPermissionsLPw(pkg, replace, changingPkg); 9294 } 9295 } 9296 } 9297 9298 if (pkgInfo != null) { 9299 // Only replace for packages on requested volume 9300 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9301 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9302 && Objects.equals(replaceVolumeUuid, volumeUuid); 9303 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9304 } 9305 } 9306 9307 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9308 String packageOfInterest) { 9309 // IMPORTANT: There are two types of permissions: install and runtime. 9310 // Install time permissions are granted when the app is installed to 9311 // all device users and users added in the future. Runtime permissions 9312 // are granted at runtime explicitly to specific users. Normal and signature 9313 // protected permissions are install time permissions. Dangerous permissions 9314 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9315 // otherwise they are runtime permissions. This function does not manage 9316 // runtime permissions except for the case an app targeting Lollipop MR1 9317 // being upgraded to target a newer SDK, in which case dangerous permissions 9318 // are transformed from install time to runtime ones. 9319 9320 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9321 if (ps == null) { 9322 return; 9323 } 9324 9325 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9326 9327 PermissionsState permissionsState = ps.getPermissionsState(); 9328 PermissionsState origPermissions = permissionsState; 9329 9330 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9331 9332 boolean runtimePermissionsRevoked = false; 9333 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9334 9335 boolean changedInstallPermission = false; 9336 9337 if (replace) { 9338 ps.installPermissionsFixed = false; 9339 if (!ps.isSharedUser()) { 9340 origPermissions = new PermissionsState(permissionsState); 9341 permissionsState.reset(); 9342 } else { 9343 // We need to know only about runtime permission changes since the 9344 // calling code always writes the install permissions state but 9345 // the runtime ones are written only if changed. The only cases of 9346 // changed runtime permissions here are promotion of an install to 9347 // runtime and revocation of a runtime from a shared user. 9348 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9349 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9350 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9351 runtimePermissionsRevoked = true; 9352 } 9353 } 9354 } 9355 9356 permissionsState.setGlobalGids(mGlobalGids); 9357 9358 final int N = pkg.requestedPermissions.size(); 9359 for (int i=0; i<N; i++) { 9360 final String name = pkg.requestedPermissions.get(i); 9361 final BasePermission bp = mSettings.mPermissions.get(name); 9362 9363 if (DEBUG_INSTALL) { 9364 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9365 } 9366 9367 if (bp == null || bp.packageSetting == null) { 9368 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9369 Slog.w(TAG, "Unknown permission " + name 9370 + " in package " + pkg.packageName); 9371 } 9372 continue; 9373 } 9374 9375 final String perm = bp.name; 9376 boolean allowedSig = false; 9377 int grant = GRANT_DENIED; 9378 9379 // Keep track of app op permissions. 9380 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9381 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9382 if (pkgs == null) { 9383 pkgs = new ArraySet<>(); 9384 mAppOpPermissionPackages.put(bp.name, pkgs); 9385 } 9386 pkgs.add(pkg.packageName); 9387 } 9388 9389 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9390 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9391 >= Build.VERSION_CODES.M; 9392 switch (level) { 9393 case PermissionInfo.PROTECTION_NORMAL: { 9394 // For all apps normal permissions are install time ones. 9395 grant = GRANT_INSTALL; 9396 } break; 9397 9398 case PermissionInfo.PROTECTION_DANGEROUS: { 9399 // If a permission review is required for legacy apps we represent 9400 // their permissions as always granted runtime ones since we need 9401 // to keep the review required permission flag per user while an 9402 // install permission's state is shared across all users. 9403 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9404 // For legacy apps dangerous permissions are install time ones. 9405 grant = GRANT_INSTALL; 9406 } else if (origPermissions.hasInstallPermission(bp.name)) { 9407 // For legacy apps that became modern, install becomes runtime. 9408 grant = GRANT_UPGRADE; 9409 } else if (mPromoteSystemApps 9410 && isSystemApp(ps) 9411 && mExistingSystemPackages.contains(ps.name)) { 9412 // For legacy system apps, install becomes runtime. 9413 // We cannot check hasInstallPermission() for system apps since those 9414 // permissions were granted implicitly and not persisted pre-M. 9415 grant = GRANT_UPGRADE; 9416 } else { 9417 // For modern apps keep runtime permissions unchanged. 9418 grant = GRANT_RUNTIME; 9419 } 9420 } break; 9421 9422 case PermissionInfo.PROTECTION_SIGNATURE: { 9423 // For all apps signature permissions are install time ones. 9424 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9425 if (allowedSig) { 9426 grant = GRANT_INSTALL; 9427 } 9428 } break; 9429 } 9430 9431 if (DEBUG_INSTALL) { 9432 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9433 } 9434 9435 if (grant != GRANT_DENIED) { 9436 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9437 // If this is an existing, non-system package, then 9438 // we can't add any new permissions to it. 9439 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9440 // Except... if this is a permission that was added 9441 // to the platform (note: need to only do this when 9442 // updating the platform). 9443 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9444 grant = GRANT_DENIED; 9445 } 9446 } 9447 } 9448 9449 switch (grant) { 9450 case GRANT_INSTALL: { 9451 // Revoke this as runtime permission to handle the case of 9452 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 9453 for (int userId : UserManagerService.getInstance().getUserIds()) { 9454 if (origPermissions.getRuntimePermissionState( 9455 bp.name, userId) != null) { 9456 // Revoke the runtime permission and clear the flags. 9457 origPermissions.revokeRuntimePermission(bp, userId); 9458 origPermissions.updatePermissionFlags(bp, userId, 9459 PackageManager.MASK_PERMISSION_FLAGS, 0); 9460 // If we revoked a permission permission, we have to write. 9461 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9462 changedRuntimePermissionUserIds, userId); 9463 } 9464 } 9465 // Grant an install permission. 9466 if (permissionsState.grantInstallPermission(bp) != 9467 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9468 changedInstallPermission = true; 9469 } 9470 } break; 9471 9472 case GRANT_RUNTIME: { 9473 // Grant previously granted runtime permissions. 9474 for (int userId : UserManagerService.getInstance().getUserIds()) { 9475 PermissionState permissionState = origPermissions 9476 .getRuntimePermissionState(bp.name, userId); 9477 int flags = permissionState != null 9478 ? permissionState.getFlags() : 0; 9479 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9480 if (permissionsState.grantRuntimePermission(bp, userId) == 9481 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9482 // If we cannot put the permission as it was, we have to write. 9483 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9484 changedRuntimePermissionUserIds, userId); 9485 } 9486 // If the app supports runtime permissions no need for a review. 9487 if (Build.PERMISSIONS_REVIEW_REQUIRED 9488 && appSupportsRuntimePermissions 9489 && (flags & PackageManager 9490 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9491 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9492 // Since we changed the flags, we have to write. 9493 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9494 changedRuntimePermissionUserIds, userId); 9495 } 9496 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9497 && !appSupportsRuntimePermissions) { 9498 // For legacy apps that need a permission review, every new 9499 // runtime permission is granted but it is pending a review. 9500 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9501 permissionsState.grantRuntimePermission(bp, userId); 9502 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9503 // We changed the permission and flags, hence have to write. 9504 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9505 changedRuntimePermissionUserIds, userId); 9506 } 9507 } 9508 // Propagate the permission flags. 9509 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9510 } 9511 } break; 9512 9513 case GRANT_UPGRADE: { 9514 // Grant runtime permissions for a previously held install permission. 9515 PermissionState permissionState = origPermissions 9516 .getInstallPermissionState(bp.name); 9517 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9518 9519 if (origPermissions.revokeInstallPermission(bp) 9520 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9521 // We will be transferring the permission flags, so clear them. 9522 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9523 PackageManager.MASK_PERMISSION_FLAGS, 0); 9524 changedInstallPermission = true; 9525 } 9526 9527 // If the permission is not to be promoted to runtime we ignore it and 9528 // also its other flags as they are not applicable to install permissions. 9529 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9530 for (int userId : currentUserIds) { 9531 if (permissionsState.grantRuntimePermission(bp, userId) != 9532 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9533 // Transfer the permission flags. 9534 permissionsState.updatePermissionFlags(bp, userId, 9535 flags, flags); 9536 // If we granted the permission, we have to write. 9537 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9538 changedRuntimePermissionUserIds, userId); 9539 } 9540 } 9541 } 9542 } break; 9543 9544 default: { 9545 if (packageOfInterest == null 9546 || packageOfInterest.equals(pkg.packageName)) { 9547 Slog.w(TAG, "Not granting permission " + perm 9548 + " to package " + pkg.packageName 9549 + " because it was previously installed without"); 9550 } 9551 } break; 9552 } 9553 } else { 9554 if (permissionsState.revokeInstallPermission(bp) != 9555 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9556 // Also drop the permission flags. 9557 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9558 PackageManager.MASK_PERMISSION_FLAGS, 0); 9559 changedInstallPermission = true; 9560 Slog.i(TAG, "Un-granting permission " + perm 9561 + " from package " + pkg.packageName 9562 + " (protectionLevel=" + bp.protectionLevel 9563 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9564 + ")"); 9565 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9566 // Don't print warning for app op permissions, since it is fine for them 9567 // not to be granted, there is a UI for the user to decide. 9568 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9569 Slog.w(TAG, "Not granting permission " + perm 9570 + " to package " + pkg.packageName 9571 + " (protectionLevel=" + bp.protectionLevel 9572 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9573 + ")"); 9574 } 9575 } 9576 } 9577 } 9578 9579 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9580 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9581 // This is the first that we have heard about this package, so the 9582 // permissions we have now selected are fixed until explicitly 9583 // changed. 9584 ps.installPermissionsFixed = true; 9585 } 9586 9587 // Persist the runtime permissions state for users with changes. If permissions 9588 // were revoked because no app in the shared user declares them we have to 9589 // write synchronously to avoid losing runtime permissions state. 9590 for (int userId : changedRuntimePermissionUserIds) { 9591 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9592 } 9593 9594 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9595 } 9596 9597 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9598 boolean allowed = false; 9599 final int NP = PackageParser.NEW_PERMISSIONS.length; 9600 for (int ip=0; ip<NP; ip++) { 9601 final PackageParser.NewPermissionInfo npi 9602 = PackageParser.NEW_PERMISSIONS[ip]; 9603 if (npi.name.equals(perm) 9604 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9605 allowed = true; 9606 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9607 + pkg.packageName); 9608 break; 9609 } 9610 } 9611 return allowed; 9612 } 9613 9614 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9615 BasePermission bp, PermissionsState origPermissions) { 9616 boolean allowed; 9617 allowed = (compareSignatures( 9618 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9619 == PackageManager.SIGNATURE_MATCH) 9620 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9621 == PackageManager.SIGNATURE_MATCH); 9622 if (!allowed && (bp.protectionLevel 9623 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9624 if (isSystemApp(pkg)) { 9625 // For updated system applications, a system permission 9626 // is granted only if it had been defined by the original application. 9627 if (pkg.isUpdatedSystemApp()) { 9628 final PackageSetting sysPs = mSettings 9629 .getDisabledSystemPkgLPr(pkg.packageName); 9630 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9631 // If the original was granted this permission, we take 9632 // that grant decision as read and propagate it to the 9633 // update. 9634 if (sysPs.isPrivileged()) { 9635 allowed = true; 9636 } 9637 } else { 9638 // The system apk may have been updated with an older 9639 // version of the one on the data partition, but which 9640 // granted a new system permission that it didn't have 9641 // before. In this case we do want to allow the app to 9642 // now get the new permission if the ancestral apk is 9643 // privileged to get it. 9644 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9645 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9646 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9647 allowed = true; 9648 break; 9649 } 9650 } 9651 } 9652 // Also if a privileged parent package on the system image or any of 9653 // its children requested a privileged permission, the updated child 9654 // packages can also get the permission. 9655 if (pkg.parentPackage != null) { 9656 final PackageSetting disabledSysParentPs = mSettings 9657 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 9658 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 9659 && disabledSysParentPs.isPrivileged()) { 9660 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 9661 allowed = true; 9662 } else if (disabledSysParentPs.pkg.childPackages != null) { 9663 final int count = disabledSysParentPs.pkg.childPackages.size(); 9664 for (int i = 0; i < count; i++) { 9665 PackageParser.Package disabledSysChildPkg = 9666 disabledSysParentPs.pkg.childPackages.get(i); 9667 if (isPackageRequestingPermission(disabledSysChildPkg, 9668 perm)) { 9669 allowed = true; 9670 break; 9671 } 9672 } 9673 } 9674 } 9675 } 9676 } 9677 } else { 9678 allowed = isPrivilegedApp(pkg); 9679 } 9680 } 9681 } 9682 if (!allowed) { 9683 if (!allowed && (bp.protectionLevel 9684 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9685 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9686 // If this was a previously normal/dangerous permission that got moved 9687 // to a system permission as part of the runtime permission redesign, then 9688 // we still want to blindly grant it to old apps. 9689 allowed = true; 9690 } 9691 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9692 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9693 // If this permission is to be granted to the system installer and 9694 // this app is an installer, then it gets the permission. 9695 allowed = true; 9696 } 9697 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9698 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9699 // If this permission is to be granted to the system verifier and 9700 // this app is a verifier, then it gets the permission. 9701 allowed = true; 9702 } 9703 if (!allowed && (bp.protectionLevel 9704 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9705 && isSystemApp(pkg)) { 9706 // Any pre-installed system app is allowed to get this permission. 9707 allowed = true; 9708 } 9709 if (!allowed && (bp.protectionLevel 9710 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9711 // For development permissions, a development permission 9712 // is granted only if it was already granted. 9713 allowed = origPermissions.hasInstallPermission(perm); 9714 } 9715 } 9716 return allowed; 9717 } 9718 9719 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 9720 final int permCount = pkg.requestedPermissions.size(); 9721 for (int j = 0; j < permCount; j++) { 9722 String requestedPermission = pkg.requestedPermissions.get(j); 9723 if (permission.equals(requestedPermission)) { 9724 return true; 9725 } 9726 } 9727 return false; 9728 } 9729 9730 final class ActivityIntentResolver 9731 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9732 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9733 boolean defaultOnly, int userId) { 9734 if (!sUserManager.exists(userId)) return null; 9735 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9736 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9737 } 9738 9739 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9740 int userId) { 9741 if (!sUserManager.exists(userId)) return null; 9742 mFlags = flags; 9743 return super.queryIntent(intent, resolvedType, 9744 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9745 } 9746 9747 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9748 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9749 if (!sUserManager.exists(userId)) return null; 9750 if (packageActivities == null) { 9751 return null; 9752 } 9753 mFlags = flags; 9754 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9755 final int N = packageActivities.size(); 9756 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9757 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9758 9759 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9760 for (int i = 0; i < N; ++i) { 9761 intentFilters = packageActivities.get(i).intents; 9762 if (intentFilters != null && intentFilters.size() > 0) { 9763 PackageParser.ActivityIntentInfo[] array = 9764 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9765 intentFilters.toArray(array); 9766 listCut.add(array); 9767 } 9768 } 9769 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9770 } 9771 9772 public final void addActivity(PackageParser.Activity a, String type) { 9773 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 9774 mActivities.put(a.getComponentName(), a); 9775 if (DEBUG_SHOW_INFO) 9776 Log.v( 9777 TAG, " " + type + " " + 9778 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 9779 if (DEBUG_SHOW_INFO) 9780 Log.v(TAG, " Class=" + a.info.name); 9781 final int NI = a.intents.size(); 9782 for (int j=0; j<NI; j++) { 9783 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9784 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 9785 intent.setPriority(0); 9786 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 9787 + a.className + " with priority > 0, forcing to 0"); 9788 } 9789 if (DEBUG_SHOW_INFO) { 9790 Log.v(TAG, " IntentFilter:"); 9791 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9792 } 9793 if (!intent.debugCheck()) { 9794 Log.w(TAG, "==> For Activity " + a.info.name); 9795 } 9796 addFilter(intent); 9797 } 9798 } 9799 9800 public final void removeActivity(PackageParser.Activity a, String type) { 9801 mActivities.remove(a.getComponentName()); 9802 if (DEBUG_SHOW_INFO) { 9803 Log.v(TAG, " " + type + " " 9804 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 9805 : a.info.name) + ":"); 9806 Log.v(TAG, " Class=" + a.info.name); 9807 } 9808 final int NI = a.intents.size(); 9809 for (int j=0; j<NI; j++) { 9810 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9811 if (DEBUG_SHOW_INFO) { 9812 Log.v(TAG, " IntentFilter:"); 9813 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9814 } 9815 removeFilter(intent); 9816 } 9817 } 9818 9819 @Override 9820 protected boolean allowFilterResult( 9821 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 9822 ActivityInfo filterAi = filter.activity.info; 9823 for (int i=dest.size()-1; i>=0; i--) { 9824 ActivityInfo destAi = dest.get(i).activityInfo; 9825 if (destAi.name == filterAi.name 9826 && destAi.packageName == filterAi.packageName) { 9827 return false; 9828 } 9829 } 9830 return true; 9831 } 9832 9833 @Override 9834 protected ActivityIntentInfo[] newArray(int size) { 9835 return new ActivityIntentInfo[size]; 9836 } 9837 9838 @Override 9839 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 9840 if (!sUserManager.exists(userId)) return true; 9841 PackageParser.Package p = filter.activity.owner; 9842 if (p != null) { 9843 PackageSetting ps = (PackageSetting)p.mExtras; 9844 if (ps != null) { 9845 // System apps are never considered stopped for purposes of 9846 // filtering, because there may be no way for the user to 9847 // actually re-launch them. 9848 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 9849 && ps.getStopped(userId); 9850 } 9851 } 9852 return false; 9853 } 9854 9855 @Override 9856 protected boolean isPackageForFilter(String packageName, 9857 PackageParser.ActivityIntentInfo info) { 9858 return packageName.equals(info.activity.owner.packageName); 9859 } 9860 9861 @Override 9862 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 9863 int match, int userId) { 9864 if (!sUserManager.exists(userId)) return null; 9865 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 9866 return null; 9867 } 9868 final PackageParser.Activity activity = info.activity; 9869 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 9870 if (ps == null) { 9871 return null; 9872 } 9873 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 9874 ps.readUserState(userId), userId); 9875 if (ai == null) { 9876 return null; 9877 } 9878 final ResolveInfo res = new ResolveInfo(); 9879 res.activityInfo = ai; 9880 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9881 res.filter = info; 9882 } 9883 if (info != null) { 9884 res.handleAllWebDataURI = info.handleAllWebDataURI(); 9885 } 9886 res.priority = info.getPriority(); 9887 res.preferredOrder = activity.owner.mPreferredOrder; 9888 //System.out.println("Result: " + res.activityInfo.className + 9889 // " = " + res.priority); 9890 res.match = match; 9891 res.isDefault = info.hasDefault; 9892 res.labelRes = info.labelRes; 9893 res.nonLocalizedLabel = info.nonLocalizedLabel; 9894 if (userNeedsBadging(userId)) { 9895 res.noResourceId = true; 9896 } else { 9897 res.icon = info.icon; 9898 } 9899 res.iconResourceId = info.icon; 9900 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9901 return res; 9902 } 9903 9904 @Override 9905 protected void sortResults(List<ResolveInfo> results) { 9906 Collections.sort(results, mResolvePrioritySorter); 9907 } 9908 9909 @Override 9910 protected void dumpFilter(PrintWriter out, String prefix, 9911 PackageParser.ActivityIntentInfo filter) { 9912 out.print(prefix); out.print( 9913 Integer.toHexString(System.identityHashCode(filter.activity))); 9914 out.print(' '); 9915 filter.activity.printComponentShortName(out); 9916 out.print(" filter "); 9917 out.println(Integer.toHexString(System.identityHashCode(filter))); 9918 } 9919 9920 @Override 9921 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9922 return filter.activity; 9923 } 9924 9925 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9926 PackageParser.Activity activity = (PackageParser.Activity)label; 9927 out.print(prefix); out.print( 9928 Integer.toHexString(System.identityHashCode(activity))); 9929 out.print(' '); 9930 activity.printComponentShortName(out); 9931 if (count > 1) { 9932 out.print(" ("); out.print(count); out.print(" filters)"); 9933 } 9934 out.println(); 9935 } 9936 9937// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9938// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9939// final List<ResolveInfo> retList = Lists.newArrayList(); 9940// while (i.hasNext()) { 9941// final ResolveInfo resolveInfo = i.next(); 9942// if (isEnabledLP(resolveInfo.activityInfo)) { 9943// retList.add(resolveInfo); 9944// } 9945// } 9946// return retList; 9947// } 9948 9949 // Keys are String (activity class name), values are Activity. 9950 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9951 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9952 private int mFlags; 9953 } 9954 9955 private final class ServiceIntentResolver 9956 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9957 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9958 boolean defaultOnly, int userId) { 9959 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9960 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9961 } 9962 9963 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9964 int userId) { 9965 if (!sUserManager.exists(userId)) return null; 9966 mFlags = flags; 9967 return super.queryIntent(intent, resolvedType, 9968 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9969 } 9970 9971 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9972 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9973 if (!sUserManager.exists(userId)) return null; 9974 if (packageServices == null) { 9975 return null; 9976 } 9977 mFlags = flags; 9978 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9979 final int N = packageServices.size(); 9980 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9981 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9982 9983 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9984 for (int i = 0; i < N; ++i) { 9985 intentFilters = packageServices.get(i).intents; 9986 if (intentFilters != null && intentFilters.size() > 0) { 9987 PackageParser.ServiceIntentInfo[] array = 9988 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9989 intentFilters.toArray(array); 9990 listCut.add(array); 9991 } 9992 } 9993 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9994 } 9995 9996 public final void addService(PackageParser.Service s) { 9997 mServices.put(s.getComponentName(), s); 9998 if (DEBUG_SHOW_INFO) { 9999 Log.v(TAG, " " 10000 + (s.info.nonLocalizedLabel != null 10001 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10002 Log.v(TAG, " Class=" + s.info.name); 10003 } 10004 final int NI = s.intents.size(); 10005 int j; 10006 for (j=0; j<NI; j++) { 10007 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10008 if (DEBUG_SHOW_INFO) { 10009 Log.v(TAG, " IntentFilter:"); 10010 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10011 } 10012 if (!intent.debugCheck()) { 10013 Log.w(TAG, "==> For Service " + s.info.name); 10014 } 10015 addFilter(intent); 10016 } 10017 } 10018 10019 public final void removeService(PackageParser.Service s) { 10020 mServices.remove(s.getComponentName()); 10021 if (DEBUG_SHOW_INFO) { 10022 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10023 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10024 Log.v(TAG, " Class=" + s.info.name); 10025 } 10026 final int NI = s.intents.size(); 10027 int j; 10028 for (j=0; j<NI; j++) { 10029 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10030 if (DEBUG_SHOW_INFO) { 10031 Log.v(TAG, " IntentFilter:"); 10032 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10033 } 10034 removeFilter(intent); 10035 } 10036 } 10037 10038 @Override 10039 protected boolean allowFilterResult( 10040 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10041 ServiceInfo filterSi = filter.service.info; 10042 for (int i=dest.size()-1; i>=0; i--) { 10043 ServiceInfo destAi = dest.get(i).serviceInfo; 10044 if (destAi.name == filterSi.name 10045 && destAi.packageName == filterSi.packageName) { 10046 return false; 10047 } 10048 } 10049 return true; 10050 } 10051 10052 @Override 10053 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10054 return new PackageParser.ServiceIntentInfo[size]; 10055 } 10056 10057 @Override 10058 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10059 if (!sUserManager.exists(userId)) return true; 10060 PackageParser.Package p = filter.service.owner; 10061 if (p != null) { 10062 PackageSetting ps = (PackageSetting)p.mExtras; 10063 if (ps != null) { 10064 // System apps are never considered stopped for purposes of 10065 // filtering, because there may be no way for the user to 10066 // actually re-launch them. 10067 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10068 && ps.getStopped(userId); 10069 } 10070 } 10071 return false; 10072 } 10073 10074 @Override 10075 protected boolean isPackageForFilter(String packageName, 10076 PackageParser.ServiceIntentInfo info) { 10077 return packageName.equals(info.service.owner.packageName); 10078 } 10079 10080 @Override 10081 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10082 int match, int userId) { 10083 if (!sUserManager.exists(userId)) return null; 10084 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10085 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10086 return null; 10087 } 10088 final PackageParser.Service service = info.service; 10089 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10090 if (ps == null) { 10091 return null; 10092 } 10093 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10094 ps.readUserState(userId), userId); 10095 if (si == null) { 10096 return null; 10097 } 10098 final ResolveInfo res = new ResolveInfo(); 10099 res.serviceInfo = si; 10100 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10101 res.filter = filter; 10102 } 10103 res.priority = info.getPriority(); 10104 res.preferredOrder = service.owner.mPreferredOrder; 10105 res.match = match; 10106 res.isDefault = info.hasDefault; 10107 res.labelRes = info.labelRes; 10108 res.nonLocalizedLabel = info.nonLocalizedLabel; 10109 res.icon = info.icon; 10110 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10111 return res; 10112 } 10113 10114 @Override 10115 protected void sortResults(List<ResolveInfo> results) { 10116 Collections.sort(results, mResolvePrioritySorter); 10117 } 10118 10119 @Override 10120 protected void dumpFilter(PrintWriter out, String prefix, 10121 PackageParser.ServiceIntentInfo filter) { 10122 out.print(prefix); out.print( 10123 Integer.toHexString(System.identityHashCode(filter.service))); 10124 out.print(' '); 10125 filter.service.printComponentShortName(out); 10126 out.print(" filter "); 10127 out.println(Integer.toHexString(System.identityHashCode(filter))); 10128 } 10129 10130 @Override 10131 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10132 return filter.service; 10133 } 10134 10135 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10136 PackageParser.Service service = (PackageParser.Service)label; 10137 out.print(prefix); out.print( 10138 Integer.toHexString(System.identityHashCode(service))); 10139 out.print(' '); 10140 service.printComponentShortName(out); 10141 if (count > 1) { 10142 out.print(" ("); out.print(count); out.print(" filters)"); 10143 } 10144 out.println(); 10145 } 10146 10147// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10148// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10149// final List<ResolveInfo> retList = Lists.newArrayList(); 10150// while (i.hasNext()) { 10151// final ResolveInfo resolveInfo = (ResolveInfo) i; 10152// if (isEnabledLP(resolveInfo.serviceInfo)) { 10153// retList.add(resolveInfo); 10154// } 10155// } 10156// return retList; 10157// } 10158 10159 // Keys are String (activity class name), values are Activity. 10160 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10161 = new ArrayMap<ComponentName, PackageParser.Service>(); 10162 private int mFlags; 10163 }; 10164 10165 private final class ProviderIntentResolver 10166 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10167 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10168 boolean defaultOnly, int userId) { 10169 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10170 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10171 } 10172 10173 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10174 int userId) { 10175 if (!sUserManager.exists(userId)) 10176 return null; 10177 mFlags = flags; 10178 return super.queryIntent(intent, resolvedType, 10179 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10180 } 10181 10182 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10183 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10184 if (!sUserManager.exists(userId)) 10185 return null; 10186 if (packageProviders == null) { 10187 return null; 10188 } 10189 mFlags = flags; 10190 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10191 final int N = packageProviders.size(); 10192 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10193 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10194 10195 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10196 for (int i = 0; i < N; ++i) { 10197 intentFilters = packageProviders.get(i).intents; 10198 if (intentFilters != null && intentFilters.size() > 0) { 10199 PackageParser.ProviderIntentInfo[] array = 10200 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10201 intentFilters.toArray(array); 10202 listCut.add(array); 10203 } 10204 } 10205 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10206 } 10207 10208 public final void addProvider(PackageParser.Provider p) { 10209 if (mProviders.containsKey(p.getComponentName())) { 10210 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10211 return; 10212 } 10213 10214 mProviders.put(p.getComponentName(), p); 10215 if (DEBUG_SHOW_INFO) { 10216 Log.v(TAG, " " 10217 + (p.info.nonLocalizedLabel != null 10218 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10219 Log.v(TAG, " Class=" + p.info.name); 10220 } 10221 final int NI = p.intents.size(); 10222 int j; 10223 for (j = 0; j < NI; j++) { 10224 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10225 if (DEBUG_SHOW_INFO) { 10226 Log.v(TAG, " IntentFilter:"); 10227 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10228 } 10229 if (!intent.debugCheck()) { 10230 Log.w(TAG, "==> For Provider " + p.info.name); 10231 } 10232 addFilter(intent); 10233 } 10234 } 10235 10236 public final void removeProvider(PackageParser.Provider p) { 10237 mProviders.remove(p.getComponentName()); 10238 if (DEBUG_SHOW_INFO) { 10239 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10240 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10241 Log.v(TAG, " Class=" + p.info.name); 10242 } 10243 final int NI = p.intents.size(); 10244 int j; 10245 for (j = 0; j < NI; j++) { 10246 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10247 if (DEBUG_SHOW_INFO) { 10248 Log.v(TAG, " IntentFilter:"); 10249 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10250 } 10251 removeFilter(intent); 10252 } 10253 } 10254 10255 @Override 10256 protected boolean allowFilterResult( 10257 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10258 ProviderInfo filterPi = filter.provider.info; 10259 for (int i = dest.size() - 1; i >= 0; i--) { 10260 ProviderInfo destPi = dest.get(i).providerInfo; 10261 if (destPi.name == filterPi.name 10262 && destPi.packageName == filterPi.packageName) { 10263 return false; 10264 } 10265 } 10266 return true; 10267 } 10268 10269 @Override 10270 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10271 return new PackageParser.ProviderIntentInfo[size]; 10272 } 10273 10274 @Override 10275 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10276 if (!sUserManager.exists(userId)) 10277 return true; 10278 PackageParser.Package p = filter.provider.owner; 10279 if (p != null) { 10280 PackageSetting ps = (PackageSetting) p.mExtras; 10281 if (ps != null) { 10282 // System apps are never considered stopped for purposes of 10283 // filtering, because there may be no way for the user to 10284 // actually re-launch them. 10285 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10286 && ps.getStopped(userId); 10287 } 10288 } 10289 return false; 10290 } 10291 10292 @Override 10293 protected boolean isPackageForFilter(String packageName, 10294 PackageParser.ProviderIntentInfo info) { 10295 return packageName.equals(info.provider.owner.packageName); 10296 } 10297 10298 @Override 10299 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10300 int match, int userId) { 10301 if (!sUserManager.exists(userId)) 10302 return null; 10303 final PackageParser.ProviderIntentInfo info = filter; 10304 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10305 return null; 10306 } 10307 final PackageParser.Provider provider = info.provider; 10308 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10309 if (ps == null) { 10310 return null; 10311 } 10312 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10313 ps.readUserState(userId), userId); 10314 if (pi == null) { 10315 return null; 10316 } 10317 final ResolveInfo res = new ResolveInfo(); 10318 res.providerInfo = pi; 10319 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10320 res.filter = filter; 10321 } 10322 res.priority = info.getPriority(); 10323 res.preferredOrder = provider.owner.mPreferredOrder; 10324 res.match = match; 10325 res.isDefault = info.hasDefault; 10326 res.labelRes = info.labelRes; 10327 res.nonLocalizedLabel = info.nonLocalizedLabel; 10328 res.icon = info.icon; 10329 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10330 return res; 10331 } 10332 10333 @Override 10334 protected void sortResults(List<ResolveInfo> results) { 10335 Collections.sort(results, mResolvePrioritySorter); 10336 } 10337 10338 @Override 10339 protected void dumpFilter(PrintWriter out, String prefix, 10340 PackageParser.ProviderIntentInfo filter) { 10341 out.print(prefix); 10342 out.print( 10343 Integer.toHexString(System.identityHashCode(filter.provider))); 10344 out.print(' '); 10345 filter.provider.printComponentShortName(out); 10346 out.print(" filter "); 10347 out.println(Integer.toHexString(System.identityHashCode(filter))); 10348 } 10349 10350 @Override 10351 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 10352 return filter.provider; 10353 } 10354 10355 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10356 PackageParser.Provider provider = (PackageParser.Provider)label; 10357 out.print(prefix); out.print( 10358 Integer.toHexString(System.identityHashCode(provider))); 10359 out.print(' '); 10360 provider.printComponentShortName(out); 10361 if (count > 1) { 10362 out.print(" ("); out.print(count); out.print(" filters)"); 10363 } 10364 out.println(); 10365 } 10366 10367 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 10368 = new ArrayMap<ComponentName, PackageParser.Provider>(); 10369 private int mFlags; 10370 } 10371 10372 private static final class EphemeralIntentResolver 10373 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 10374 @Override 10375 protected EphemeralResolveIntentInfo[] newArray(int size) { 10376 return new EphemeralResolveIntentInfo[size]; 10377 } 10378 10379 @Override 10380 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 10381 return true; 10382 } 10383 10384 @Override 10385 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 10386 int userId) { 10387 if (!sUserManager.exists(userId)) { 10388 return null; 10389 } 10390 return info.getEphemeralResolveInfo(); 10391 } 10392 } 10393 10394 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 10395 new Comparator<ResolveInfo>() { 10396 public int compare(ResolveInfo r1, ResolveInfo r2) { 10397 int v1 = r1.priority; 10398 int v2 = r2.priority; 10399 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 10400 if (v1 != v2) { 10401 return (v1 > v2) ? -1 : 1; 10402 } 10403 v1 = r1.preferredOrder; 10404 v2 = r2.preferredOrder; 10405 if (v1 != v2) { 10406 return (v1 > v2) ? -1 : 1; 10407 } 10408 if (r1.isDefault != r2.isDefault) { 10409 return r1.isDefault ? -1 : 1; 10410 } 10411 v1 = r1.match; 10412 v2 = r2.match; 10413 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 10414 if (v1 != v2) { 10415 return (v1 > v2) ? -1 : 1; 10416 } 10417 if (r1.system != r2.system) { 10418 return r1.system ? -1 : 1; 10419 } 10420 if (r1.activityInfo != null) { 10421 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 10422 } 10423 if (r1.serviceInfo != null) { 10424 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 10425 } 10426 if (r1.providerInfo != null) { 10427 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 10428 } 10429 return 0; 10430 } 10431 }; 10432 10433 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 10434 new Comparator<ProviderInfo>() { 10435 public int compare(ProviderInfo p1, ProviderInfo p2) { 10436 final int v1 = p1.initOrder; 10437 final int v2 = p2.initOrder; 10438 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 10439 } 10440 }; 10441 10442 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 10443 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 10444 final int[] userIds) { 10445 mHandler.post(new Runnable() { 10446 @Override 10447 public void run() { 10448 try { 10449 final IActivityManager am = ActivityManagerNative.getDefault(); 10450 if (am == null) return; 10451 final int[] resolvedUserIds; 10452 if (userIds == null) { 10453 resolvedUserIds = am.getRunningUserIds(); 10454 } else { 10455 resolvedUserIds = userIds; 10456 } 10457 for (int id : resolvedUserIds) { 10458 final Intent intent = new Intent(action, 10459 pkg != null ? Uri.fromParts("package", pkg, null) : null); 10460 if (extras != null) { 10461 intent.putExtras(extras); 10462 } 10463 if (targetPkg != null) { 10464 intent.setPackage(targetPkg); 10465 } 10466 // Modify the UID when posting to other users 10467 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 10468 if (uid > 0 && UserHandle.getUserId(uid) != id) { 10469 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 10470 intent.putExtra(Intent.EXTRA_UID, uid); 10471 } 10472 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 10473 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 10474 if (DEBUG_BROADCASTS) { 10475 RuntimeException here = new RuntimeException("here"); 10476 here.fillInStackTrace(); 10477 Slog.d(TAG, "Sending to user " + id + ": " 10478 + intent.toShortString(false, true, false, false) 10479 + " " + intent.getExtras(), here); 10480 } 10481 am.broadcastIntent(null, intent, null, finishedReceiver, 10482 0, null, null, null, android.app.AppOpsManager.OP_NONE, 10483 null, finishedReceiver != null, false, id); 10484 } 10485 } catch (RemoteException ex) { 10486 } 10487 } 10488 }); 10489 } 10490 10491 /** 10492 * Check if the external storage media is available. This is true if there 10493 * is a mounted external storage medium or if the external storage is 10494 * emulated. 10495 */ 10496 private boolean isExternalMediaAvailable() { 10497 return mMediaMounted || Environment.isExternalStorageEmulated(); 10498 } 10499 10500 @Override 10501 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 10502 // writer 10503 synchronized (mPackages) { 10504 if (!isExternalMediaAvailable()) { 10505 // If the external storage is no longer mounted at this point, 10506 // the caller may not have been able to delete all of this 10507 // packages files and can not delete any more. Bail. 10508 return null; 10509 } 10510 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 10511 if (lastPackage != null) { 10512 pkgs.remove(lastPackage); 10513 } 10514 if (pkgs.size() > 0) { 10515 return pkgs.get(0); 10516 } 10517 } 10518 return null; 10519 } 10520 10521 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 10522 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 10523 userId, andCode ? 1 : 0, packageName); 10524 if (mSystemReady) { 10525 msg.sendToTarget(); 10526 } else { 10527 if (mPostSystemReadyMessages == null) { 10528 mPostSystemReadyMessages = new ArrayList<>(); 10529 } 10530 mPostSystemReadyMessages.add(msg); 10531 } 10532 } 10533 10534 void startCleaningPackages() { 10535 // reader 10536 if (!isExternalMediaAvailable()) { 10537 return; 10538 } 10539 synchronized (mPackages) { 10540 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 10541 return; 10542 } 10543 } 10544 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 10545 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 10546 IActivityManager am = ActivityManagerNative.getDefault(); 10547 if (am != null) { 10548 try { 10549 am.startService(null, intent, null, mContext.getOpPackageName(), 10550 UserHandle.USER_SYSTEM); 10551 } catch (RemoteException e) { 10552 } 10553 } 10554 } 10555 10556 @Override 10557 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 10558 int installFlags, String installerPackageName, int userId) { 10559 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 10560 10561 final int callingUid = Binder.getCallingUid(); 10562 enforceCrossUserPermission(callingUid, userId, 10563 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 10564 10565 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10566 try { 10567 if (observer != null) { 10568 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 10569 } 10570 } catch (RemoteException re) { 10571 } 10572 return; 10573 } 10574 10575 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 10576 installFlags |= PackageManager.INSTALL_FROM_ADB; 10577 10578 } else { 10579 // Caller holds INSTALL_PACKAGES permission, so we're less strict 10580 // about installerPackageName. 10581 10582 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 10583 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 10584 } 10585 10586 UserHandle user; 10587 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 10588 user = UserHandle.ALL; 10589 } else { 10590 user = new UserHandle(userId); 10591 } 10592 10593 // Only system components can circumvent runtime permissions when installing. 10594 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 10595 && mContext.checkCallingOrSelfPermission(Manifest.permission 10596 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 10597 throw new SecurityException("You need the " 10598 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 10599 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 10600 } 10601 10602 final File originFile = new File(originPath); 10603 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 10604 10605 final Message msg = mHandler.obtainMessage(INIT_COPY); 10606 final VerificationInfo verificationInfo = new VerificationInfo( 10607 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 10608 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 10609 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 10610 null /*packageAbiOverride*/, null /*grantedPermissions*/); 10611 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 10612 msg.obj = params; 10613 10614 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 10615 System.identityHashCode(msg.obj)); 10616 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10617 System.identityHashCode(msg.obj)); 10618 10619 mHandler.sendMessage(msg); 10620 } 10621 10622 void installStage(String packageName, File stagedDir, String stagedCid, 10623 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 10624 String installerPackageName, int installerUid, UserHandle user) { 10625 if (DEBUG_EPHEMERAL) { 10626 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10627 Slog.d(TAG, "Ephemeral install of " + packageName); 10628 } 10629 } 10630 final VerificationInfo verificationInfo = new VerificationInfo( 10631 sessionParams.originatingUri, sessionParams.referrerUri, 10632 sessionParams.originatingUid, installerUid); 10633 10634 final OriginInfo origin; 10635 if (stagedDir != null) { 10636 origin = OriginInfo.fromStagedFile(stagedDir); 10637 } else { 10638 origin = OriginInfo.fromStagedContainer(stagedCid); 10639 } 10640 10641 final Message msg = mHandler.obtainMessage(INIT_COPY); 10642 final InstallParams params = new InstallParams(origin, null, observer, 10643 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 10644 verificationInfo, user, sessionParams.abiOverride, 10645 sessionParams.grantedRuntimePermissions); 10646 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 10647 msg.obj = params; 10648 10649 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 10650 System.identityHashCode(msg.obj)); 10651 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10652 System.identityHashCode(msg.obj)); 10653 10654 mHandler.sendMessage(msg); 10655 } 10656 10657 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 10658 int userId) { 10659 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 10660 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 10661 } 10662 10663 private void sendPackageAddedForUser(String packageName, boolean isSystem, 10664 int appId, int userId) { 10665 Bundle extras = new Bundle(1); 10666 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 10667 10668 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 10669 packageName, extras, 0, null, null, new int[] {userId}); 10670 try { 10671 IActivityManager am = ActivityManagerNative.getDefault(); 10672 if (isSystem && am.isUserRunning(userId, 0)) { 10673 // The just-installed/enabled app is bundled on the system, so presumed 10674 // to be able to run automatically without needing an explicit launch. 10675 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 10676 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 10677 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 10678 .setPackage(packageName); 10679 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 10680 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 10681 } 10682 } catch (RemoteException e) { 10683 // shouldn't happen 10684 Slog.w(TAG, "Unable to bootstrap installed package", e); 10685 } 10686 } 10687 10688 @Override 10689 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 10690 int userId) { 10691 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10692 PackageSetting pkgSetting; 10693 final int uid = Binder.getCallingUid(); 10694 enforceCrossUserPermission(uid, userId, 10695 true /* requireFullPermission */, true /* checkShell */, 10696 "setApplicationHiddenSetting for user " + userId); 10697 10698 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 10699 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 10700 return false; 10701 } 10702 10703 long callingId = Binder.clearCallingIdentity(); 10704 try { 10705 boolean sendAdded = false; 10706 boolean sendRemoved = false; 10707 // writer 10708 synchronized (mPackages) { 10709 pkgSetting = mSettings.mPackages.get(packageName); 10710 if (pkgSetting == null) { 10711 return false; 10712 } 10713 if (pkgSetting.getHidden(userId) != hidden) { 10714 pkgSetting.setHidden(hidden, userId); 10715 mSettings.writePackageRestrictionsLPr(userId); 10716 if (hidden) { 10717 sendRemoved = true; 10718 } else { 10719 sendAdded = true; 10720 } 10721 } 10722 } 10723 if (sendAdded) { 10724 sendPackageAddedForUser(packageName, pkgSetting, userId); 10725 return true; 10726 } 10727 if (sendRemoved) { 10728 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 10729 "hiding pkg"); 10730 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 10731 return true; 10732 } 10733 } finally { 10734 Binder.restoreCallingIdentity(callingId); 10735 } 10736 return false; 10737 } 10738 10739 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 10740 int userId) { 10741 final PackageRemovedInfo info = new PackageRemovedInfo(); 10742 info.removedPackage = packageName; 10743 info.removedUsers = new int[] {userId}; 10744 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 10745 info.sendPackageRemovedBroadcasts(true /*killApp*/); 10746 } 10747 10748 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 10749 if (pkgList.length > 0) { 10750 Bundle extras = new Bundle(1); 10751 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 10752 10753 sendPackageBroadcast( 10754 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 10755 : Intent.ACTION_PACKAGES_UNSUSPENDED, 10756 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 10757 new int[] {userId}); 10758 } 10759 } 10760 10761 /** 10762 * Returns true if application is not found or there was an error. Otherwise it returns 10763 * the hidden state of the package for the given user. 10764 */ 10765 @Override 10766 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 10767 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10768 enforceCrossUserPermission(Binder.getCallingUid(), userId, 10769 true /* requireFullPermission */, false /* checkShell */, 10770 "getApplicationHidden for user " + userId); 10771 PackageSetting pkgSetting; 10772 long callingId = Binder.clearCallingIdentity(); 10773 try { 10774 // writer 10775 synchronized (mPackages) { 10776 pkgSetting = mSettings.mPackages.get(packageName); 10777 if (pkgSetting == null) { 10778 return true; 10779 } 10780 return pkgSetting.getHidden(userId); 10781 } 10782 } finally { 10783 Binder.restoreCallingIdentity(callingId); 10784 } 10785 } 10786 10787 /** 10788 * @hide 10789 */ 10790 @Override 10791 public int installExistingPackageAsUser(String packageName, int userId) { 10792 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 10793 null); 10794 PackageSetting pkgSetting; 10795 final int uid = Binder.getCallingUid(); 10796 enforceCrossUserPermission(uid, userId, 10797 true /* requireFullPermission */, true /* checkShell */, 10798 "installExistingPackage for user " + userId); 10799 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10800 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 10801 } 10802 10803 long callingId = Binder.clearCallingIdentity(); 10804 try { 10805 boolean installed = false; 10806 10807 // writer 10808 synchronized (mPackages) { 10809 pkgSetting = mSettings.mPackages.get(packageName); 10810 if (pkgSetting == null) { 10811 return PackageManager.INSTALL_FAILED_INVALID_URI; 10812 } 10813 if (!pkgSetting.getInstalled(userId)) { 10814 pkgSetting.setInstalled(true, userId); 10815 pkgSetting.setHidden(false, userId); 10816 mSettings.writePackageRestrictionsLPr(userId); 10817 installed = true; 10818 } 10819 } 10820 10821 if (installed) { 10822 if (pkgSetting.pkg != null) { 10823 prepareAppDataAfterInstall(pkgSetting.pkg); 10824 } 10825 sendPackageAddedForUser(packageName, pkgSetting, userId); 10826 } 10827 } finally { 10828 Binder.restoreCallingIdentity(callingId); 10829 } 10830 10831 return PackageManager.INSTALL_SUCCEEDED; 10832 } 10833 10834 boolean isUserRestricted(int userId, String restrictionKey) { 10835 Bundle restrictions = sUserManager.getUserRestrictions(userId); 10836 if (restrictions.getBoolean(restrictionKey, false)) { 10837 Log.w(TAG, "User is restricted: " + restrictionKey); 10838 return true; 10839 } 10840 return false; 10841 } 10842 10843 @Override 10844 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 10845 int userId) { 10846 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10847 enforceCrossUserPermission(Binder.getCallingUid(), userId, 10848 true /* requireFullPermission */, true /* checkShell */, 10849 "setPackagesSuspended for user " + userId); 10850 10851 if (ArrayUtils.isEmpty(packageNames)) { 10852 return packageNames; 10853 } 10854 10855 // List of package names for whom the suspended state has changed. 10856 List<String> changedPackages = new ArrayList<>(packageNames.length); 10857 // List of package names for whom the suspended state is not set as requested in this 10858 // method. 10859 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 10860 for (int i = 0; i < packageNames.length; i++) { 10861 String packageName = packageNames[i]; 10862 long callingId = Binder.clearCallingIdentity(); 10863 try { 10864 boolean changed = false; 10865 final int appId; 10866 synchronized (mPackages) { 10867 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10868 if (pkgSetting == null) { 10869 Slog.w(TAG, "Could not find package setting for package \"" + packageName 10870 + "\". Skipping suspending/un-suspending."); 10871 unactionedPackages.add(packageName); 10872 continue; 10873 } 10874 appId = pkgSetting.appId; 10875 if (pkgSetting.getSuspended(userId) != suspended) { 10876 if (!canSuspendPackageForUserLocked(packageName, userId)) { 10877 unactionedPackages.add(packageName); 10878 continue; 10879 } 10880 pkgSetting.setSuspended(suspended, userId); 10881 mSettings.writePackageRestrictionsLPr(userId); 10882 changed = true; 10883 changedPackages.add(packageName); 10884 } 10885 } 10886 10887 if (changed && suspended) { 10888 killApplication(packageName, UserHandle.getUid(userId, appId), 10889 "suspending package"); 10890 } 10891 } finally { 10892 Binder.restoreCallingIdentity(callingId); 10893 } 10894 } 10895 10896 if (!changedPackages.isEmpty()) { 10897 sendPackagesSuspendedForUser(changedPackages.toArray( 10898 new String[changedPackages.size()]), userId, suspended); 10899 } 10900 10901 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 10902 } 10903 10904 @Override 10905 public boolean isPackageSuspendedForUser(String packageName, int userId) { 10906 enforceCrossUserPermission(Binder.getCallingUid(), userId, 10907 true /* requireFullPermission */, false /* checkShell */, 10908 "isPackageSuspendedForUser for user " + userId); 10909 synchronized (mPackages) { 10910 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10911 return pkgSetting != null && pkgSetting.getSuspended(userId); 10912 } 10913 } 10914 10915 /** 10916 * TODO: cache and disallow blocking the active dialer. 10917 * 10918 * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions 10919 */ 10920 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 10921 if (isPackageDeviceAdmin(packageName, userId)) { 10922 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 10923 + "\": has an active device admin"); 10924 return false; 10925 } 10926 10927 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 10928 if (packageName.equals(activeLauncherPackageName)) { 10929 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 10930 + "\": contains the active launcher"); 10931 return false; 10932 } 10933 10934 if (packageName.equals(mRequiredInstallerPackage)) { 10935 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 10936 + "\": required for package installation"); 10937 return false; 10938 } 10939 10940 if (packageName.equals(mRequiredVerifierPackage)) { 10941 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 10942 + "\": required for package verification"); 10943 return false; 10944 } 10945 10946 final PackageParser.Package pkg = mPackages.get(packageName); 10947 if (pkg != null && isPrivilegedApp(pkg)) { 10948 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 10949 + "\": is a privileged app"); 10950 return false; 10951 } 10952 10953 return true; 10954 } 10955 10956 private String getActiveLauncherPackageName(int userId) { 10957 Intent intent = new Intent(Intent.ACTION_MAIN); 10958 intent.addCategory(Intent.CATEGORY_HOME); 10959 ResolveInfo resolveInfo = resolveIntent( 10960 intent, 10961 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 10962 PackageManager.MATCH_DEFAULT_ONLY, 10963 userId); 10964 10965 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 10966 } 10967 10968 @Override 10969 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 10970 mContext.enforceCallingOrSelfPermission( 10971 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10972 "Only package verification agents can verify applications"); 10973 10974 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10975 final PackageVerificationResponse response = new PackageVerificationResponse( 10976 verificationCode, Binder.getCallingUid()); 10977 msg.arg1 = id; 10978 msg.obj = response; 10979 mHandler.sendMessage(msg); 10980 } 10981 10982 @Override 10983 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 10984 long millisecondsToDelay) { 10985 mContext.enforceCallingOrSelfPermission( 10986 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10987 "Only package verification agents can extend verification timeouts"); 10988 10989 final PackageVerificationState state = mPendingVerification.get(id); 10990 final PackageVerificationResponse response = new PackageVerificationResponse( 10991 verificationCodeAtTimeout, Binder.getCallingUid()); 10992 10993 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 10994 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 10995 } 10996 if (millisecondsToDelay < 0) { 10997 millisecondsToDelay = 0; 10998 } 10999 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11000 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11001 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11002 } 11003 11004 if ((state != null) && !state.timeoutExtended()) { 11005 state.extendTimeout(); 11006 11007 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11008 msg.arg1 = id; 11009 msg.obj = response; 11010 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11011 } 11012 } 11013 11014 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11015 int verificationCode, UserHandle user) { 11016 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11017 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11018 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11019 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11020 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11021 11022 mContext.sendBroadcastAsUser(intent, user, 11023 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11024 } 11025 11026 private ComponentName matchComponentForVerifier(String packageName, 11027 List<ResolveInfo> receivers) { 11028 ActivityInfo targetReceiver = null; 11029 11030 final int NR = receivers.size(); 11031 for (int i = 0; i < NR; i++) { 11032 final ResolveInfo info = receivers.get(i); 11033 if (info.activityInfo == null) { 11034 continue; 11035 } 11036 11037 if (packageName.equals(info.activityInfo.packageName)) { 11038 targetReceiver = info.activityInfo; 11039 break; 11040 } 11041 } 11042 11043 if (targetReceiver == null) { 11044 return null; 11045 } 11046 11047 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11048 } 11049 11050 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11051 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11052 if (pkgInfo.verifiers.length == 0) { 11053 return null; 11054 } 11055 11056 final int N = pkgInfo.verifiers.length; 11057 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11058 for (int i = 0; i < N; i++) { 11059 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11060 11061 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11062 receivers); 11063 if (comp == null) { 11064 continue; 11065 } 11066 11067 final int verifierUid = getUidForVerifier(verifierInfo); 11068 if (verifierUid == -1) { 11069 continue; 11070 } 11071 11072 if (DEBUG_VERIFY) { 11073 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11074 + " with the correct signature"); 11075 } 11076 sufficientVerifiers.add(comp); 11077 verificationState.addSufficientVerifier(verifierUid); 11078 } 11079 11080 return sufficientVerifiers; 11081 } 11082 11083 private int getUidForVerifier(VerifierInfo verifierInfo) { 11084 synchronized (mPackages) { 11085 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11086 if (pkg == null) { 11087 return -1; 11088 } else if (pkg.mSignatures.length != 1) { 11089 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11090 + " has more than one signature; ignoring"); 11091 return -1; 11092 } 11093 11094 /* 11095 * If the public key of the package's signature does not match 11096 * our expected public key, then this is a different package and 11097 * we should skip. 11098 */ 11099 11100 final byte[] expectedPublicKey; 11101 try { 11102 final Signature verifierSig = pkg.mSignatures[0]; 11103 final PublicKey publicKey = verifierSig.getPublicKey(); 11104 expectedPublicKey = publicKey.getEncoded(); 11105 } catch (CertificateException e) { 11106 return -1; 11107 } 11108 11109 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11110 11111 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11112 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11113 + " does not have the expected public key; ignoring"); 11114 return -1; 11115 } 11116 11117 return pkg.applicationInfo.uid; 11118 } 11119 } 11120 11121 @Override 11122 public void finishPackageInstall(int token) { 11123 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11124 11125 if (DEBUG_INSTALL) { 11126 Slog.v(TAG, "BM finishing package install for " + token); 11127 } 11128 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11129 11130 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11131 mHandler.sendMessage(msg); 11132 } 11133 11134 /** 11135 * Get the verification agent timeout. 11136 * 11137 * @return verification timeout in milliseconds 11138 */ 11139 private long getVerificationTimeout() { 11140 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11141 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11142 DEFAULT_VERIFICATION_TIMEOUT); 11143 } 11144 11145 /** 11146 * Get the default verification agent response code. 11147 * 11148 * @return default verification response code 11149 */ 11150 private int getDefaultVerificationResponse() { 11151 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11152 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11153 DEFAULT_VERIFICATION_RESPONSE); 11154 } 11155 11156 /** 11157 * Check whether or not package verification has been enabled. 11158 * 11159 * @return true if verification should be performed 11160 */ 11161 private boolean isVerificationEnabled(int userId, int installFlags) { 11162 if (!DEFAULT_VERIFY_ENABLE) { 11163 return false; 11164 } 11165 // Ephemeral apps don't get the full verification treatment 11166 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11167 if (DEBUG_EPHEMERAL) { 11168 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11169 } 11170 return false; 11171 } 11172 11173 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11174 11175 // Check if installing from ADB 11176 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11177 // Do not run verification in a test harness environment 11178 if (ActivityManager.isRunningInTestHarness()) { 11179 return false; 11180 } 11181 if (ensureVerifyAppsEnabled) { 11182 return true; 11183 } 11184 // Check if the developer does not want package verification for ADB installs 11185 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11186 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11187 return false; 11188 } 11189 } 11190 11191 if (ensureVerifyAppsEnabled) { 11192 return true; 11193 } 11194 11195 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11196 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11197 } 11198 11199 @Override 11200 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11201 throws RemoteException { 11202 mContext.enforceCallingOrSelfPermission( 11203 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11204 "Only intentfilter verification agents can verify applications"); 11205 11206 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11207 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11208 Binder.getCallingUid(), verificationCode, failedDomains); 11209 msg.arg1 = id; 11210 msg.obj = response; 11211 mHandler.sendMessage(msg); 11212 } 11213 11214 @Override 11215 public int getIntentVerificationStatus(String packageName, int userId) { 11216 synchronized (mPackages) { 11217 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11218 } 11219 } 11220 11221 @Override 11222 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11223 mContext.enforceCallingOrSelfPermission( 11224 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11225 11226 boolean result = false; 11227 synchronized (mPackages) { 11228 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11229 } 11230 if (result) { 11231 scheduleWritePackageRestrictionsLocked(userId); 11232 } 11233 return result; 11234 } 11235 11236 @Override 11237 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11238 String packageName) { 11239 synchronized (mPackages) { 11240 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11241 } 11242 } 11243 11244 @Override 11245 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11246 if (TextUtils.isEmpty(packageName)) { 11247 return ParceledListSlice.emptyList(); 11248 } 11249 synchronized (mPackages) { 11250 PackageParser.Package pkg = mPackages.get(packageName); 11251 if (pkg == null || pkg.activities == null) { 11252 return ParceledListSlice.emptyList(); 11253 } 11254 final int count = pkg.activities.size(); 11255 ArrayList<IntentFilter> result = new ArrayList<>(); 11256 for (int n=0; n<count; n++) { 11257 PackageParser.Activity activity = pkg.activities.get(n); 11258 if (activity.intents != null && activity.intents.size() > 0) { 11259 result.addAll(activity.intents); 11260 } 11261 } 11262 return new ParceledListSlice<>(result); 11263 } 11264 } 11265 11266 @Override 11267 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11268 mContext.enforceCallingOrSelfPermission( 11269 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11270 11271 synchronized (mPackages) { 11272 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11273 if (packageName != null) { 11274 result |= updateIntentVerificationStatus(packageName, 11275 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11276 userId); 11277 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11278 packageName, userId); 11279 } 11280 return result; 11281 } 11282 } 11283 11284 @Override 11285 public String getDefaultBrowserPackageName(int userId) { 11286 synchronized (mPackages) { 11287 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11288 } 11289 } 11290 11291 /** 11292 * Get the "allow unknown sources" setting. 11293 * 11294 * @return the current "allow unknown sources" setting 11295 */ 11296 private int getUnknownSourcesSettings() { 11297 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11298 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 11299 -1); 11300 } 11301 11302 @Override 11303 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11304 final int uid = Binder.getCallingUid(); 11305 // writer 11306 synchronized (mPackages) { 11307 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11308 if (targetPackageSetting == null) { 11309 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11310 } 11311 11312 PackageSetting installerPackageSetting; 11313 if (installerPackageName != null) { 11314 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11315 if (installerPackageSetting == null) { 11316 throw new IllegalArgumentException("Unknown installer package: " 11317 + installerPackageName); 11318 } 11319 } else { 11320 installerPackageSetting = null; 11321 } 11322 11323 Signature[] callerSignature; 11324 Object obj = mSettings.getUserIdLPr(uid); 11325 if (obj != null) { 11326 if (obj instanceof SharedUserSetting) { 11327 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11328 } else if (obj instanceof PackageSetting) { 11329 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11330 } else { 11331 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11332 } 11333 } else { 11334 throw new SecurityException("Unknown calling UID: " + uid); 11335 } 11336 11337 // Verify: can't set installerPackageName to a package that is 11338 // not signed with the same cert as the caller. 11339 if (installerPackageSetting != null) { 11340 if (compareSignatures(callerSignature, 11341 installerPackageSetting.signatures.mSignatures) 11342 != PackageManager.SIGNATURE_MATCH) { 11343 throw new SecurityException( 11344 "Caller does not have same cert as new installer package " 11345 + installerPackageName); 11346 } 11347 } 11348 11349 // Verify: if target already has an installer package, it must 11350 // be signed with the same cert as the caller. 11351 if (targetPackageSetting.installerPackageName != null) { 11352 PackageSetting setting = mSettings.mPackages.get( 11353 targetPackageSetting.installerPackageName); 11354 // If the currently set package isn't valid, then it's always 11355 // okay to change it. 11356 if (setting != null) { 11357 if (compareSignatures(callerSignature, 11358 setting.signatures.mSignatures) 11359 != PackageManager.SIGNATURE_MATCH) { 11360 throw new SecurityException( 11361 "Caller does not have same cert as old installer package " 11362 + targetPackageSetting.installerPackageName); 11363 } 11364 } 11365 } 11366 11367 // Okay! 11368 targetPackageSetting.installerPackageName = installerPackageName; 11369 scheduleWriteSettingsLocked(); 11370 } 11371 } 11372 11373 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 11374 // Queue up an async operation since the package installation may take a little while. 11375 mHandler.post(new Runnable() { 11376 public void run() { 11377 mHandler.removeCallbacks(this); 11378 // Result object to be returned 11379 PackageInstalledInfo res = new PackageInstalledInfo(); 11380 res.setReturnCode(currentStatus); 11381 res.uid = -1; 11382 res.pkg = null; 11383 res.removedInfo = null; 11384 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11385 args.doPreInstall(res.returnCode); 11386 synchronized (mInstallLock) { 11387 installPackageTracedLI(args, res); 11388 } 11389 args.doPostInstall(res.returnCode, res.uid); 11390 } 11391 11392 // A restore should be performed at this point if (a) the install 11393 // succeeded, (b) the operation is not an update, and (c) the new 11394 // package has not opted out of backup participation. 11395 final boolean update = res.removedInfo != null 11396 && res.removedInfo.removedPackage != null; 11397 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 11398 boolean doRestore = !update 11399 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 11400 11401 // Set up the post-install work request bookkeeping. This will be used 11402 // and cleaned up by the post-install event handling regardless of whether 11403 // there's a restore pass performed. Token values are >= 1. 11404 int token; 11405 if (mNextInstallToken < 0) mNextInstallToken = 1; 11406 token = mNextInstallToken++; 11407 11408 PostInstallData data = new PostInstallData(args, res); 11409 mRunningInstalls.put(token, data); 11410 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 11411 11412 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 11413 // Pass responsibility to the Backup Manager. It will perform a 11414 // restore if appropriate, then pass responsibility back to the 11415 // Package Manager to run the post-install observer callbacks 11416 // and broadcasts. 11417 IBackupManager bm = IBackupManager.Stub.asInterface( 11418 ServiceManager.getService(Context.BACKUP_SERVICE)); 11419 if (bm != null) { 11420 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 11421 + " to BM for possible restore"); 11422 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11423 try { 11424 // TODO: http://b/22388012 11425 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 11426 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 11427 } else { 11428 doRestore = false; 11429 } 11430 } catch (RemoteException e) { 11431 // can't happen; the backup manager is local 11432 } catch (Exception e) { 11433 Slog.e(TAG, "Exception trying to enqueue restore", e); 11434 doRestore = false; 11435 } 11436 } else { 11437 Slog.e(TAG, "Backup Manager not found!"); 11438 doRestore = false; 11439 } 11440 } 11441 11442 if (!doRestore) { 11443 // No restore possible, or the Backup Manager was mysteriously not 11444 // available -- just fire the post-install work request directly. 11445 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 11446 11447 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 11448 11449 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11450 mHandler.sendMessage(msg); 11451 } 11452 } 11453 }); 11454 } 11455 11456 private abstract class HandlerParams { 11457 private static final int MAX_RETRIES = 4; 11458 11459 /** 11460 * Number of times startCopy() has been attempted and had a non-fatal 11461 * error. 11462 */ 11463 private int mRetries = 0; 11464 11465 /** User handle for the user requesting the information or installation. */ 11466 private final UserHandle mUser; 11467 String traceMethod; 11468 int traceCookie; 11469 11470 HandlerParams(UserHandle user) { 11471 mUser = user; 11472 } 11473 11474 UserHandle getUser() { 11475 return mUser; 11476 } 11477 11478 HandlerParams setTraceMethod(String traceMethod) { 11479 this.traceMethod = traceMethod; 11480 return this; 11481 } 11482 11483 HandlerParams setTraceCookie(int traceCookie) { 11484 this.traceCookie = traceCookie; 11485 return this; 11486 } 11487 11488 final boolean startCopy() { 11489 boolean res; 11490 try { 11491 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 11492 11493 if (++mRetries > MAX_RETRIES) { 11494 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 11495 mHandler.sendEmptyMessage(MCS_GIVE_UP); 11496 handleServiceError(); 11497 return false; 11498 } else { 11499 handleStartCopy(); 11500 res = true; 11501 } 11502 } catch (RemoteException e) { 11503 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 11504 mHandler.sendEmptyMessage(MCS_RECONNECT); 11505 res = false; 11506 } 11507 handleReturnCode(); 11508 return res; 11509 } 11510 11511 final void serviceError() { 11512 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 11513 handleServiceError(); 11514 handleReturnCode(); 11515 } 11516 11517 abstract void handleStartCopy() throws RemoteException; 11518 abstract void handleServiceError(); 11519 abstract void handleReturnCode(); 11520 } 11521 11522 class MeasureParams extends HandlerParams { 11523 private final PackageStats mStats; 11524 private boolean mSuccess; 11525 11526 private final IPackageStatsObserver mObserver; 11527 11528 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 11529 super(new UserHandle(stats.userHandle)); 11530 mObserver = observer; 11531 mStats = stats; 11532 } 11533 11534 @Override 11535 public String toString() { 11536 return "MeasureParams{" 11537 + Integer.toHexString(System.identityHashCode(this)) 11538 + " " + mStats.packageName + "}"; 11539 } 11540 11541 @Override 11542 void handleStartCopy() throws RemoteException { 11543 synchronized (mInstallLock) { 11544 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 11545 } 11546 11547 if (mSuccess) { 11548 final boolean mounted; 11549 if (Environment.isExternalStorageEmulated()) { 11550 mounted = true; 11551 } else { 11552 final String status = Environment.getExternalStorageState(); 11553 mounted = (Environment.MEDIA_MOUNTED.equals(status) 11554 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 11555 } 11556 11557 if (mounted) { 11558 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 11559 11560 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 11561 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 11562 11563 mStats.externalDataSize = calculateDirectorySize(mContainerService, 11564 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 11565 11566 // Always subtract cache size, since it's a subdirectory 11567 mStats.externalDataSize -= mStats.externalCacheSize; 11568 11569 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 11570 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 11571 11572 mStats.externalObbSize = calculateDirectorySize(mContainerService, 11573 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 11574 } 11575 } 11576 } 11577 11578 @Override 11579 void handleReturnCode() { 11580 if (mObserver != null) { 11581 try { 11582 mObserver.onGetStatsCompleted(mStats, mSuccess); 11583 } catch (RemoteException e) { 11584 Slog.i(TAG, "Observer no longer exists."); 11585 } 11586 } 11587 } 11588 11589 @Override 11590 void handleServiceError() { 11591 Slog.e(TAG, "Could not measure application " + mStats.packageName 11592 + " external storage"); 11593 } 11594 } 11595 11596 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 11597 throws RemoteException { 11598 long result = 0; 11599 for (File path : paths) { 11600 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 11601 } 11602 return result; 11603 } 11604 11605 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 11606 for (File path : paths) { 11607 try { 11608 mcs.clearDirectory(path.getAbsolutePath()); 11609 } catch (RemoteException e) { 11610 } 11611 } 11612 } 11613 11614 static class OriginInfo { 11615 /** 11616 * Location where install is coming from, before it has been 11617 * copied/renamed into place. This could be a single monolithic APK 11618 * file, or a cluster directory. This location may be untrusted. 11619 */ 11620 final File file; 11621 final String cid; 11622 11623 /** 11624 * Flag indicating that {@link #file} or {@link #cid} has already been 11625 * staged, meaning downstream users don't need to defensively copy the 11626 * contents. 11627 */ 11628 final boolean staged; 11629 11630 /** 11631 * Flag indicating that {@link #file} or {@link #cid} is an already 11632 * installed app that is being moved. 11633 */ 11634 final boolean existing; 11635 11636 final String resolvedPath; 11637 final File resolvedFile; 11638 11639 static OriginInfo fromNothing() { 11640 return new OriginInfo(null, null, false, false); 11641 } 11642 11643 static OriginInfo fromUntrustedFile(File file) { 11644 return new OriginInfo(file, null, false, false); 11645 } 11646 11647 static OriginInfo fromExistingFile(File file) { 11648 return new OriginInfo(file, null, false, true); 11649 } 11650 11651 static OriginInfo fromStagedFile(File file) { 11652 return new OriginInfo(file, null, true, false); 11653 } 11654 11655 static OriginInfo fromStagedContainer(String cid) { 11656 return new OriginInfo(null, cid, true, false); 11657 } 11658 11659 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 11660 this.file = file; 11661 this.cid = cid; 11662 this.staged = staged; 11663 this.existing = existing; 11664 11665 if (cid != null) { 11666 resolvedPath = PackageHelper.getSdDir(cid); 11667 resolvedFile = new File(resolvedPath); 11668 } else if (file != null) { 11669 resolvedPath = file.getAbsolutePath(); 11670 resolvedFile = file; 11671 } else { 11672 resolvedPath = null; 11673 resolvedFile = null; 11674 } 11675 } 11676 } 11677 11678 static class MoveInfo { 11679 final int moveId; 11680 final String fromUuid; 11681 final String toUuid; 11682 final String packageName; 11683 final String dataAppName; 11684 final int appId; 11685 final String seinfo; 11686 final int targetSdkVersion; 11687 11688 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 11689 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 11690 this.moveId = moveId; 11691 this.fromUuid = fromUuid; 11692 this.toUuid = toUuid; 11693 this.packageName = packageName; 11694 this.dataAppName = dataAppName; 11695 this.appId = appId; 11696 this.seinfo = seinfo; 11697 this.targetSdkVersion = targetSdkVersion; 11698 } 11699 } 11700 11701 static class VerificationInfo { 11702 /** A constant used to indicate that a uid value is not present. */ 11703 public static final int NO_UID = -1; 11704 11705 /** URI referencing where the package was downloaded from. */ 11706 final Uri originatingUri; 11707 11708 /** HTTP referrer URI associated with the originatingURI. */ 11709 final Uri referrer; 11710 11711 /** UID of the application that the install request originated from. */ 11712 final int originatingUid; 11713 11714 /** UID of application requesting the install */ 11715 final int installerUid; 11716 11717 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 11718 this.originatingUri = originatingUri; 11719 this.referrer = referrer; 11720 this.originatingUid = originatingUid; 11721 this.installerUid = installerUid; 11722 } 11723 } 11724 11725 class InstallParams extends HandlerParams { 11726 final OriginInfo origin; 11727 final MoveInfo move; 11728 final IPackageInstallObserver2 observer; 11729 int installFlags; 11730 final String installerPackageName; 11731 final String volumeUuid; 11732 private InstallArgs mArgs; 11733 private int mRet; 11734 final String packageAbiOverride; 11735 final String[] grantedRuntimePermissions; 11736 final VerificationInfo verificationInfo; 11737 11738 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11739 int installFlags, String installerPackageName, String volumeUuid, 11740 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 11741 String[] grantedPermissions) { 11742 super(user); 11743 this.origin = origin; 11744 this.move = move; 11745 this.observer = observer; 11746 this.installFlags = installFlags; 11747 this.installerPackageName = installerPackageName; 11748 this.volumeUuid = volumeUuid; 11749 this.verificationInfo = verificationInfo; 11750 this.packageAbiOverride = packageAbiOverride; 11751 this.grantedRuntimePermissions = grantedPermissions; 11752 } 11753 11754 @Override 11755 public String toString() { 11756 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 11757 + " file=" + origin.file + " cid=" + origin.cid + "}"; 11758 } 11759 11760 private int installLocationPolicy(PackageInfoLite pkgLite) { 11761 String packageName = pkgLite.packageName; 11762 int installLocation = pkgLite.installLocation; 11763 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11764 // reader 11765 synchronized (mPackages) { 11766 // Currently installed package which the new package is attempting to replace or 11767 // null if no such package is installed. 11768 PackageParser.Package installedPkg = mPackages.get(packageName); 11769 // Package which currently owns the data which the new package will own if installed. 11770 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 11771 // will be null whereas dataOwnerPkg will contain information about the package 11772 // which was uninstalled while keeping its data. 11773 PackageParser.Package dataOwnerPkg = installedPkg; 11774 if (dataOwnerPkg == null) { 11775 PackageSetting ps = mSettings.mPackages.get(packageName); 11776 if (ps != null) { 11777 dataOwnerPkg = ps.pkg; 11778 } 11779 } 11780 11781 if (dataOwnerPkg != null) { 11782 // If installed, the package will get access to data left on the device by its 11783 // predecessor. As a security measure, this is permited only if this is not a 11784 // version downgrade or if the predecessor package is marked as debuggable and 11785 // a downgrade is explicitly requested. 11786 if (((dataOwnerPkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) 11787 || ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0)) { 11788 try { 11789 checkDowngrade(dataOwnerPkg, pkgLite); 11790 } catch (PackageManagerException e) { 11791 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 11792 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 11793 } 11794 } 11795 } 11796 11797 if (installedPkg != null) { 11798 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11799 // Check for updated system application. 11800 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11801 if (onSd) { 11802 Slog.w(TAG, "Cannot install update to system app on sdcard"); 11803 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 11804 } 11805 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11806 } else { 11807 if (onSd) { 11808 // Install flag overrides everything. 11809 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11810 } 11811 // If current upgrade specifies particular preference 11812 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 11813 // Application explicitly specified internal. 11814 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11815 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 11816 // App explictly prefers external. Let policy decide 11817 } else { 11818 // Prefer previous location 11819 if (isExternal(installedPkg)) { 11820 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11821 } 11822 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11823 } 11824 } 11825 } else { 11826 // Invalid install. Return error code 11827 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 11828 } 11829 } 11830 } 11831 // All the special cases have been taken care of. 11832 // Return result based on recommended install location. 11833 if (onSd) { 11834 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11835 } 11836 return pkgLite.recommendedInstallLocation; 11837 } 11838 11839 /* 11840 * Invoke remote method to get package information and install 11841 * location values. Override install location based on default 11842 * policy if needed and then create install arguments based 11843 * on the install location. 11844 */ 11845 public void handleStartCopy() throws RemoteException { 11846 int ret = PackageManager.INSTALL_SUCCEEDED; 11847 11848 // If we're already staged, we've firmly committed to an install location 11849 if (origin.staged) { 11850 if (origin.file != null) { 11851 installFlags |= PackageManager.INSTALL_INTERNAL; 11852 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11853 } else if (origin.cid != null) { 11854 installFlags |= PackageManager.INSTALL_EXTERNAL; 11855 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11856 } else { 11857 throw new IllegalStateException("Invalid stage location"); 11858 } 11859 } 11860 11861 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11862 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 11863 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11864 PackageInfoLite pkgLite = null; 11865 11866 if (onInt && onSd) { 11867 // Check if both bits are set. 11868 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 11869 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11870 } else if (onSd && ephemeral) { 11871 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 11872 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11873 } else { 11874 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 11875 packageAbiOverride); 11876 11877 if (DEBUG_EPHEMERAL && ephemeral) { 11878 Slog.v(TAG, "pkgLite for install: " + pkgLite); 11879 } 11880 11881 /* 11882 * If we have too little free space, try to free cache 11883 * before giving up. 11884 */ 11885 if (!origin.staged && pkgLite.recommendedInstallLocation 11886 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11887 // TODO: focus freeing disk space on the target device 11888 final StorageManager storage = StorageManager.from(mContext); 11889 final long lowThreshold = storage.getStorageLowBytes( 11890 Environment.getDataDirectory()); 11891 11892 final long sizeBytes = mContainerService.calculateInstalledSize( 11893 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 11894 11895 try { 11896 mInstaller.freeCache(null, sizeBytes + lowThreshold); 11897 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 11898 installFlags, packageAbiOverride); 11899 } catch (InstallerException e) { 11900 Slog.w(TAG, "Failed to free cache", e); 11901 } 11902 11903 /* 11904 * The cache free must have deleted the file we 11905 * downloaded to install. 11906 * 11907 * TODO: fix the "freeCache" call to not delete 11908 * the file we care about. 11909 */ 11910 if (pkgLite.recommendedInstallLocation 11911 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11912 pkgLite.recommendedInstallLocation 11913 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 11914 } 11915 } 11916 } 11917 11918 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11919 int loc = pkgLite.recommendedInstallLocation; 11920 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 11921 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11922 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 11923 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 11924 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11925 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11926 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 11927 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 11928 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11929 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 11930 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 11931 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 11932 } else { 11933 // Override with defaults if needed. 11934 loc = installLocationPolicy(pkgLite); 11935 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 11936 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 11937 } else if (!onSd && !onInt) { 11938 // Override install location with flags 11939 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 11940 // Set the flag to install on external media. 11941 installFlags |= PackageManager.INSTALL_EXTERNAL; 11942 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11943 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 11944 if (DEBUG_EPHEMERAL) { 11945 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 11946 } 11947 installFlags |= PackageManager.INSTALL_EPHEMERAL; 11948 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 11949 |PackageManager.INSTALL_INTERNAL); 11950 } else { 11951 // Make sure the flag for installing on external 11952 // media is unset 11953 installFlags |= PackageManager.INSTALL_INTERNAL; 11954 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11955 } 11956 } 11957 } 11958 } 11959 11960 final InstallArgs args = createInstallArgs(this); 11961 mArgs = args; 11962 11963 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11964 // TODO: http://b/22976637 11965 // Apps installed for "all" users use the device owner to verify the app 11966 UserHandle verifierUser = getUser(); 11967 if (verifierUser == UserHandle.ALL) { 11968 verifierUser = UserHandle.SYSTEM; 11969 } 11970 11971 /* 11972 * Determine if we have any installed package verifiers. If we 11973 * do, then we'll defer to them to verify the packages. 11974 */ 11975 final int requiredUid = mRequiredVerifierPackage == null ? -1 11976 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 11977 verifierUser.getIdentifier()); 11978 if (!origin.existing && requiredUid != -1 11979 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 11980 final Intent verification = new Intent( 11981 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 11982 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 11983 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 11984 PACKAGE_MIME_TYPE); 11985 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11986 11987 // Query all live verifiers based on current user state 11988 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 11989 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 11990 11991 if (DEBUG_VERIFY) { 11992 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 11993 + verification.toString() + " with " + pkgLite.verifiers.length 11994 + " optional verifiers"); 11995 } 11996 11997 final int verificationId = mPendingVerificationToken++; 11998 11999 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12000 12001 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12002 installerPackageName); 12003 12004 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12005 installFlags); 12006 12007 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12008 pkgLite.packageName); 12009 12010 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12011 pkgLite.versionCode); 12012 12013 if (verificationInfo != null) { 12014 if (verificationInfo.originatingUri != null) { 12015 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12016 verificationInfo.originatingUri); 12017 } 12018 if (verificationInfo.referrer != null) { 12019 verification.putExtra(Intent.EXTRA_REFERRER, 12020 verificationInfo.referrer); 12021 } 12022 if (verificationInfo.originatingUid >= 0) { 12023 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12024 verificationInfo.originatingUid); 12025 } 12026 if (verificationInfo.installerUid >= 0) { 12027 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12028 verificationInfo.installerUid); 12029 } 12030 } 12031 12032 final PackageVerificationState verificationState = new PackageVerificationState( 12033 requiredUid, args); 12034 12035 mPendingVerification.append(verificationId, verificationState); 12036 12037 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12038 receivers, verificationState); 12039 12040 /* 12041 * If any sufficient verifiers were listed in the package 12042 * manifest, attempt to ask them. 12043 */ 12044 if (sufficientVerifiers != null) { 12045 final int N = sufficientVerifiers.size(); 12046 if (N == 0) { 12047 Slog.i(TAG, "Additional verifiers required, but none installed."); 12048 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12049 } else { 12050 for (int i = 0; i < N; i++) { 12051 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12052 12053 final Intent sufficientIntent = new Intent(verification); 12054 sufficientIntent.setComponent(verifierComponent); 12055 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12056 } 12057 } 12058 } 12059 12060 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12061 mRequiredVerifierPackage, receivers); 12062 if (ret == PackageManager.INSTALL_SUCCEEDED 12063 && mRequiredVerifierPackage != null) { 12064 Trace.asyncTraceBegin( 12065 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12066 /* 12067 * Send the intent to the required verification agent, 12068 * but only start the verification timeout after the 12069 * target BroadcastReceivers have run. 12070 */ 12071 verification.setComponent(requiredVerifierComponent); 12072 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12073 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12074 new BroadcastReceiver() { 12075 @Override 12076 public void onReceive(Context context, Intent intent) { 12077 final Message msg = mHandler 12078 .obtainMessage(CHECK_PENDING_VERIFICATION); 12079 msg.arg1 = verificationId; 12080 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12081 } 12082 }, null, 0, null, null); 12083 12084 /* 12085 * We don't want the copy to proceed until verification 12086 * succeeds, so null out this field. 12087 */ 12088 mArgs = null; 12089 } 12090 } else { 12091 /* 12092 * No package verification is enabled, so immediately start 12093 * the remote call to initiate copy using temporary file. 12094 */ 12095 ret = args.copyApk(mContainerService, true); 12096 } 12097 } 12098 12099 mRet = ret; 12100 } 12101 12102 @Override 12103 void handleReturnCode() { 12104 // If mArgs is null, then MCS couldn't be reached. When it 12105 // reconnects, it will try again to install. At that point, this 12106 // will succeed. 12107 if (mArgs != null) { 12108 processPendingInstall(mArgs, mRet); 12109 } 12110 } 12111 12112 @Override 12113 void handleServiceError() { 12114 mArgs = createInstallArgs(this); 12115 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12116 } 12117 12118 public boolean isForwardLocked() { 12119 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12120 } 12121 } 12122 12123 /** 12124 * Used during creation of InstallArgs 12125 * 12126 * @param installFlags package installation flags 12127 * @return true if should be installed on external storage 12128 */ 12129 private static boolean installOnExternalAsec(int installFlags) { 12130 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12131 return false; 12132 } 12133 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12134 return true; 12135 } 12136 return false; 12137 } 12138 12139 /** 12140 * Used during creation of InstallArgs 12141 * 12142 * @param installFlags package installation flags 12143 * @return true if should be installed as forward locked 12144 */ 12145 private static boolean installForwardLocked(int installFlags) { 12146 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12147 } 12148 12149 private InstallArgs createInstallArgs(InstallParams params) { 12150 if (params.move != null) { 12151 return new MoveInstallArgs(params); 12152 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12153 return new AsecInstallArgs(params); 12154 } else { 12155 return new FileInstallArgs(params); 12156 } 12157 } 12158 12159 /** 12160 * Create args that describe an existing installed package. Typically used 12161 * when cleaning up old installs, or used as a move source. 12162 */ 12163 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12164 String resourcePath, String[] instructionSets) { 12165 final boolean isInAsec; 12166 if (installOnExternalAsec(installFlags)) { 12167 /* Apps on SD card are always in ASEC containers. */ 12168 isInAsec = true; 12169 } else if (installForwardLocked(installFlags) 12170 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12171 /* 12172 * Forward-locked apps are only in ASEC containers if they're the 12173 * new style 12174 */ 12175 isInAsec = true; 12176 } else { 12177 isInAsec = false; 12178 } 12179 12180 if (isInAsec) { 12181 return new AsecInstallArgs(codePath, instructionSets, 12182 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12183 } else { 12184 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12185 } 12186 } 12187 12188 static abstract class InstallArgs { 12189 /** @see InstallParams#origin */ 12190 final OriginInfo origin; 12191 /** @see InstallParams#move */ 12192 final MoveInfo move; 12193 12194 final IPackageInstallObserver2 observer; 12195 // Always refers to PackageManager flags only 12196 final int installFlags; 12197 final String installerPackageName; 12198 final String volumeUuid; 12199 final UserHandle user; 12200 final String abiOverride; 12201 final String[] installGrantPermissions; 12202 /** If non-null, drop an async trace when the install completes */ 12203 final String traceMethod; 12204 final int traceCookie; 12205 12206 // The list of instruction sets supported by this app. This is currently 12207 // only used during the rmdex() phase to clean up resources. We can get rid of this 12208 // if we move dex files under the common app path. 12209 /* nullable */ String[] instructionSets; 12210 12211 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12212 int installFlags, String installerPackageName, String volumeUuid, 12213 UserHandle user, String[] instructionSets, 12214 String abiOverride, String[] installGrantPermissions, 12215 String traceMethod, int traceCookie) { 12216 this.origin = origin; 12217 this.move = move; 12218 this.installFlags = installFlags; 12219 this.observer = observer; 12220 this.installerPackageName = installerPackageName; 12221 this.volumeUuid = volumeUuid; 12222 this.user = user; 12223 this.instructionSets = instructionSets; 12224 this.abiOverride = abiOverride; 12225 this.installGrantPermissions = installGrantPermissions; 12226 this.traceMethod = traceMethod; 12227 this.traceCookie = traceCookie; 12228 } 12229 12230 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12231 abstract int doPreInstall(int status); 12232 12233 /** 12234 * Rename package into final resting place. All paths on the given 12235 * scanned package should be updated to reflect the rename. 12236 */ 12237 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12238 abstract int doPostInstall(int status, int uid); 12239 12240 /** @see PackageSettingBase#codePathString */ 12241 abstract String getCodePath(); 12242 /** @see PackageSettingBase#resourcePathString */ 12243 abstract String getResourcePath(); 12244 12245 // Need installer lock especially for dex file removal. 12246 abstract void cleanUpResourcesLI(); 12247 abstract boolean doPostDeleteLI(boolean delete); 12248 12249 /** 12250 * Called before the source arguments are copied. This is used mostly 12251 * for MoveParams when it needs to read the source file to put it in the 12252 * destination. 12253 */ 12254 int doPreCopy() { 12255 return PackageManager.INSTALL_SUCCEEDED; 12256 } 12257 12258 /** 12259 * Called after the source arguments are copied. This is used mostly for 12260 * MoveParams when it needs to read the source file to put it in the 12261 * destination. 12262 * 12263 * @return 12264 */ 12265 int doPostCopy(int uid) { 12266 return PackageManager.INSTALL_SUCCEEDED; 12267 } 12268 12269 protected boolean isFwdLocked() { 12270 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12271 } 12272 12273 protected boolean isExternalAsec() { 12274 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12275 } 12276 12277 protected boolean isEphemeral() { 12278 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12279 } 12280 12281 UserHandle getUser() { 12282 return user; 12283 } 12284 } 12285 12286 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 12287 if (!allCodePaths.isEmpty()) { 12288 if (instructionSets == null) { 12289 throw new IllegalStateException("instructionSet == null"); 12290 } 12291 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 12292 for (String codePath : allCodePaths) { 12293 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 12294 try { 12295 mInstaller.rmdex(codePath, dexCodeInstructionSet); 12296 } catch (InstallerException ignored) { 12297 } 12298 } 12299 } 12300 } 12301 } 12302 12303 /** 12304 * Logic to handle installation of non-ASEC applications, including copying 12305 * and renaming logic. 12306 */ 12307 class FileInstallArgs extends InstallArgs { 12308 private File codeFile; 12309 private File resourceFile; 12310 12311 // Example topology: 12312 // /data/app/com.example/base.apk 12313 // /data/app/com.example/split_foo.apk 12314 // /data/app/com.example/lib/arm/libfoo.so 12315 // /data/app/com.example/lib/arm64/libfoo.so 12316 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 12317 12318 /** New install */ 12319 FileInstallArgs(InstallParams params) { 12320 super(params.origin, params.move, params.observer, params.installFlags, 12321 params.installerPackageName, params.volumeUuid, 12322 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12323 params.grantedRuntimePermissions, 12324 params.traceMethod, params.traceCookie); 12325 if (isFwdLocked()) { 12326 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 12327 } 12328 } 12329 12330 /** Existing install */ 12331 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 12332 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 12333 null, null, null, 0); 12334 this.codeFile = (codePath != null) ? new File(codePath) : null; 12335 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 12336 } 12337 12338 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12339 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 12340 try { 12341 return doCopyApk(imcs, temp); 12342 } finally { 12343 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12344 } 12345 } 12346 12347 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12348 if (origin.staged) { 12349 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 12350 codeFile = origin.file; 12351 resourceFile = origin.file; 12352 return PackageManager.INSTALL_SUCCEEDED; 12353 } 12354 12355 try { 12356 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12357 final File tempDir = 12358 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 12359 codeFile = tempDir; 12360 resourceFile = tempDir; 12361 } catch (IOException e) { 12362 Slog.w(TAG, "Failed to create copy file: " + e); 12363 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12364 } 12365 12366 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 12367 @Override 12368 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 12369 if (!FileUtils.isValidExtFilename(name)) { 12370 throw new IllegalArgumentException("Invalid filename: " + name); 12371 } 12372 try { 12373 final File file = new File(codeFile, name); 12374 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 12375 O_RDWR | O_CREAT, 0644); 12376 Os.chmod(file.getAbsolutePath(), 0644); 12377 return new ParcelFileDescriptor(fd); 12378 } catch (ErrnoException e) { 12379 throw new RemoteException("Failed to open: " + e.getMessage()); 12380 } 12381 } 12382 }; 12383 12384 int ret = PackageManager.INSTALL_SUCCEEDED; 12385 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 12386 if (ret != PackageManager.INSTALL_SUCCEEDED) { 12387 Slog.e(TAG, "Failed to copy package"); 12388 return ret; 12389 } 12390 12391 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 12392 NativeLibraryHelper.Handle handle = null; 12393 try { 12394 handle = NativeLibraryHelper.Handle.create(codeFile); 12395 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 12396 abiOverride); 12397 } catch (IOException e) { 12398 Slog.e(TAG, "Copying native libraries failed", e); 12399 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12400 } finally { 12401 IoUtils.closeQuietly(handle); 12402 } 12403 12404 return ret; 12405 } 12406 12407 int doPreInstall(int status) { 12408 if (status != PackageManager.INSTALL_SUCCEEDED) { 12409 cleanUp(); 12410 } 12411 return status; 12412 } 12413 12414 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12415 if (status != PackageManager.INSTALL_SUCCEEDED) { 12416 cleanUp(); 12417 return false; 12418 } 12419 12420 final File targetDir = codeFile.getParentFile(); 12421 final File beforeCodeFile = codeFile; 12422 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 12423 12424 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 12425 try { 12426 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 12427 } catch (ErrnoException e) { 12428 Slog.w(TAG, "Failed to rename", e); 12429 return false; 12430 } 12431 12432 if (!SELinux.restoreconRecursive(afterCodeFile)) { 12433 Slog.w(TAG, "Failed to restorecon"); 12434 return false; 12435 } 12436 12437 // Reflect the rename internally 12438 codeFile = afterCodeFile; 12439 resourceFile = afterCodeFile; 12440 12441 // Reflect the rename in scanned details 12442 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12443 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12444 afterCodeFile, pkg.baseCodePath)); 12445 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12446 afterCodeFile, pkg.splitCodePaths)); 12447 12448 // Reflect the rename in app info 12449 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12450 pkg.setApplicationInfoCodePath(pkg.codePath); 12451 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12452 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12453 pkg.setApplicationInfoResourcePath(pkg.codePath); 12454 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12455 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12456 12457 return true; 12458 } 12459 12460 int doPostInstall(int status, int uid) { 12461 if (status != PackageManager.INSTALL_SUCCEEDED) { 12462 cleanUp(); 12463 } 12464 return status; 12465 } 12466 12467 @Override 12468 String getCodePath() { 12469 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12470 } 12471 12472 @Override 12473 String getResourcePath() { 12474 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12475 } 12476 12477 private boolean cleanUp() { 12478 if (codeFile == null || !codeFile.exists()) { 12479 return false; 12480 } 12481 12482 removeCodePathLI(codeFile); 12483 12484 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 12485 resourceFile.delete(); 12486 } 12487 12488 return true; 12489 } 12490 12491 void cleanUpResourcesLI() { 12492 // Try enumerating all code paths before deleting 12493 List<String> allCodePaths = Collections.EMPTY_LIST; 12494 if (codeFile != null && codeFile.exists()) { 12495 try { 12496 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12497 allCodePaths = pkg.getAllCodePaths(); 12498 } catch (PackageParserException e) { 12499 // Ignored; we tried our best 12500 } 12501 } 12502 12503 cleanUp(); 12504 removeDexFiles(allCodePaths, instructionSets); 12505 } 12506 12507 boolean doPostDeleteLI(boolean delete) { 12508 // XXX err, shouldn't we respect the delete flag? 12509 cleanUpResourcesLI(); 12510 return true; 12511 } 12512 } 12513 12514 private boolean isAsecExternal(String cid) { 12515 final String asecPath = PackageHelper.getSdFilesystem(cid); 12516 return !asecPath.startsWith(mAsecInternalPath); 12517 } 12518 12519 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 12520 PackageManagerException { 12521 if (copyRet < 0) { 12522 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 12523 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 12524 throw new PackageManagerException(copyRet, message); 12525 } 12526 } 12527 } 12528 12529 /** 12530 * Extract the MountService "container ID" from the full code path of an 12531 * .apk. 12532 */ 12533 static String cidFromCodePath(String fullCodePath) { 12534 int eidx = fullCodePath.lastIndexOf("/"); 12535 String subStr1 = fullCodePath.substring(0, eidx); 12536 int sidx = subStr1.lastIndexOf("/"); 12537 return subStr1.substring(sidx+1, eidx); 12538 } 12539 12540 /** 12541 * Logic to handle installation of ASEC applications, including copying and 12542 * renaming logic. 12543 */ 12544 class AsecInstallArgs extends InstallArgs { 12545 static final String RES_FILE_NAME = "pkg.apk"; 12546 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 12547 12548 String cid; 12549 String packagePath; 12550 String resourcePath; 12551 12552 /** New install */ 12553 AsecInstallArgs(InstallParams params) { 12554 super(params.origin, params.move, params.observer, params.installFlags, 12555 params.installerPackageName, params.volumeUuid, 12556 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12557 params.grantedRuntimePermissions, 12558 params.traceMethod, params.traceCookie); 12559 } 12560 12561 /** Existing install */ 12562 AsecInstallArgs(String fullCodePath, String[] instructionSets, 12563 boolean isExternal, boolean isForwardLocked) { 12564 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 12565 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12566 instructionSets, null, null, null, 0); 12567 // Hackily pretend we're still looking at a full code path 12568 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 12569 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 12570 } 12571 12572 // Extract cid from fullCodePath 12573 int eidx = fullCodePath.lastIndexOf("/"); 12574 String subStr1 = fullCodePath.substring(0, eidx); 12575 int sidx = subStr1.lastIndexOf("/"); 12576 cid = subStr1.substring(sidx+1, eidx); 12577 setMountPath(subStr1); 12578 } 12579 12580 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 12581 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 12582 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12583 instructionSets, null, null, null, 0); 12584 this.cid = cid; 12585 setMountPath(PackageHelper.getSdDir(cid)); 12586 } 12587 12588 void createCopyFile() { 12589 cid = mInstallerService.allocateExternalStageCidLegacy(); 12590 } 12591 12592 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12593 if (origin.staged && origin.cid != null) { 12594 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 12595 cid = origin.cid; 12596 setMountPath(PackageHelper.getSdDir(cid)); 12597 return PackageManager.INSTALL_SUCCEEDED; 12598 } 12599 12600 if (temp) { 12601 createCopyFile(); 12602 } else { 12603 /* 12604 * Pre-emptively destroy the container since it's destroyed if 12605 * copying fails due to it existing anyway. 12606 */ 12607 PackageHelper.destroySdDir(cid); 12608 } 12609 12610 final String newMountPath = imcs.copyPackageToContainer( 12611 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 12612 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 12613 12614 if (newMountPath != null) { 12615 setMountPath(newMountPath); 12616 return PackageManager.INSTALL_SUCCEEDED; 12617 } else { 12618 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12619 } 12620 } 12621 12622 @Override 12623 String getCodePath() { 12624 return packagePath; 12625 } 12626 12627 @Override 12628 String getResourcePath() { 12629 return resourcePath; 12630 } 12631 12632 int doPreInstall(int status) { 12633 if (status != PackageManager.INSTALL_SUCCEEDED) { 12634 // Destroy container 12635 PackageHelper.destroySdDir(cid); 12636 } else { 12637 boolean mounted = PackageHelper.isContainerMounted(cid); 12638 if (!mounted) { 12639 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 12640 Process.SYSTEM_UID); 12641 if (newMountPath != null) { 12642 setMountPath(newMountPath); 12643 } else { 12644 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12645 } 12646 } 12647 } 12648 return status; 12649 } 12650 12651 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12652 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 12653 String newMountPath = null; 12654 if (PackageHelper.isContainerMounted(cid)) { 12655 // Unmount the container 12656 if (!PackageHelper.unMountSdDir(cid)) { 12657 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 12658 return false; 12659 } 12660 } 12661 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 12662 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 12663 " which might be stale. Will try to clean up."); 12664 // Clean up the stale container and proceed to recreate. 12665 if (!PackageHelper.destroySdDir(newCacheId)) { 12666 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 12667 return false; 12668 } 12669 // Successfully cleaned up stale container. Try to rename again. 12670 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 12671 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 12672 + " inspite of cleaning it up."); 12673 return false; 12674 } 12675 } 12676 if (!PackageHelper.isContainerMounted(newCacheId)) { 12677 Slog.w(TAG, "Mounting container " + newCacheId); 12678 newMountPath = PackageHelper.mountSdDir(newCacheId, 12679 getEncryptKey(), Process.SYSTEM_UID); 12680 } else { 12681 newMountPath = PackageHelper.getSdDir(newCacheId); 12682 } 12683 if (newMountPath == null) { 12684 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 12685 return false; 12686 } 12687 Log.i(TAG, "Succesfully renamed " + cid + 12688 " to " + newCacheId + 12689 " at new path: " + newMountPath); 12690 cid = newCacheId; 12691 12692 final File beforeCodeFile = new File(packagePath); 12693 setMountPath(newMountPath); 12694 final File afterCodeFile = new File(packagePath); 12695 12696 // Reflect the rename in scanned details 12697 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12698 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12699 afterCodeFile, pkg.baseCodePath)); 12700 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12701 afterCodeFile, pkg.splitCodePaths)); 12702 12703 // Reflect the rename in app info 12704 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12705 pkg.setApplicationInfoCodePath(pkg.codePath); 12706 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12707 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12708 pkg.setApplicationInfoResourcePath(pkg.codePath); 12709 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12710 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12711 12712 return true; 12713 } 12714 12715 private void setMountPath(String mountPath) { 12716 final File mountFile = new File(mountPath); 12717 12718 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 12719 if (monolithicFile.exists()) { 12720 packagePath = monolithicFile.getAbsolutePath(); 12721 if (isFwdLocked()) { 12722 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 12723 } else { 12724 resourcePath = packagePath; 12725 } 12726 } else { 12727 packagePath = mountFile.getAbsolutePath(); 12728 resourcePath = packagePath; 12729 } 12730 } 12731 12732 int doPostInstall(int status, int uid) { 12733 if (status != PackageManager.INSTALL_SUCCEEDED) { 12734 cleanUp(); 12735 } else { 12736 final int groupOwner; 12737 final String protectedFile; 12738 if (isFwdLocked()) { 12739 groupOwner = UserHandle.getSharedAppGid(uid); 12740 protectedFile = RES_FILE_NAME; 12741 } else { 12742 groupOwner = -1; 12743 protectedFile = null; 12744 } 12745 12746 if (uid < Process.FIRST_APPLICATION_UID 12747 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 12748 Slog.e(TAG, "Failed to finalize " + cid); 12749 PackageHelper.destroySdDir(cid); 12750 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12751 } 12752 12753 boolean mounted = PackageHelper.isContainerMounted(cid); 12754 if (!mounted) { 12755 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 12756 } 12757 } 12758 return status; 12759 } 12760 12761 private void cleanUp() { 12762 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 12763 12764 // Destroy secure container 12765 PackageHelper.destroySdDir(cid); 12766 } 12767 12768 private List<String> getAllCodePaths() { 12769 final File codeFile = new File(getCodePath()); 12770 if (codeFile != null && codeFile.exists()) { 12771 try { 12772 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12773 return pkg.getAllCodePaths(); 12774 } catch (PackageParserException e) { 12775 // Ignored; we tried our best 12776 } 12777 } 12778 return Collections.EMPTY_LIST; 12779 } 12780 12781 void cleanUpResourcesLI() { 12782 // Enumerate all code paths before deleting 12783 cleanUpResourcesLI(getAllCodePaths()); 12784 } 12785 12786 private void cleanUpResourcesLI(List<String> allCodePaths) { 12787 cleanUp(); 12788 removeDexFiles(allCodePaths, instructionSets); 12789 } 12790 12791 String getPackageName() { 12792 return getAsecPackageName(cid); 12793 } 12794 12795 boolean doPostDeleteLI(boolean delete) { 12796 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 12797 final List<String> allCodePaths = getAllCodePaths(); 12798 boolean mounted = PackageHelper.isContainerMounted(cid); 12799 if (mounted) { 12800 // Unmount first 12801 if (PackageHelper.unMountSdDir(cid)) { 12802 mounted = false; 12803 } 12804 } 12805 if (!mounted && delete) { 12806 cleanUpResourcesLI(allCodePaths); 12807 } 12808 return !mounted; 12809 } 12810 12811 @Override 12812 int doPreCopy() { 12813 if (isFwdLocked()) { 12814 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 12815 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 12816 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12817 } 12818 } 12819 12820 return PackageManager.INSTALL_SUCCEEDED; 12821 } 12822 12823 @Override 12824 int doPostCopy(int uid) { 12825 if (isFwdLocked()) { 12826 if (uid < Process.FIRST_APPLICATION_UID 12827 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 12828 RES_FILE_NAME)) { 12829 Slog.e(TAG, "Failed to finalize " + cid); 12830 PackageHelper.destroySdDir(cid); 12831 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12832 } 12833 } 12834 12835 return PackageManager.INSTALL_SUCCEEDED; 12836 } 12837 } 12838 12839 /** 12840 * Logic to handle movement of existing installed applications. 12841 */ 12842 class MoveInstallArgs extends InstallArgs { 12843 private File codeFile; 12844 private File resourceFile; 12845 12846 /** New install */ 12847 MoveInstallArgs(InstallParams params) { 12848 super(params.origin, params.move, params.observer, params.installFlags, 12849 params.installerPackageName, params.volumeUuid, 12850 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12851 params.grantedRuntimePermissions, 12852 params.traceMethod, params.traceCookie); 12853 } 12854 12855 int copyApk(IMediaContainerService imcs, boolean temp) { 12856 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 12857 + move.fromUuid + " to " + move.toUuid); 12858 synchronized (mInstaller) { 12859 try { 12860 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 12861 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 12862 } catch (InstallerException e) { 12863 Slog.w(TAG, "Failed to move app", e); 12864 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12865 } 12866 } 12867 12868 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 12869 resourceFile = codeFile; 12870 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 12871 12872 return PackageManager.INSTALL_SUCCEEDED; 12873 } 12874 12875 int doPreInstall(int status) { 12876 if (status != PackageManager.INSTALL_SUCCEEDED) { 12877 cleanUp(move.toUuid); 12878 } 12879 return status; 12880 } 12881 12882 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12883 if (status != PackageManager.INSTALL_SUCCEEDED) { 12884 cleanUp(move.toUuid); 12885 return false; 12886 } 12887 12888 // Reflect the move in app info 12889 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12890 pkg.setApplicationInfoCodePath(pkg.codePath); 12891 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12892 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12893 pkg.setApplicationInfoResourcePath(pkg.codePath); 12894 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12895 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12896 12897 return true; 12898 } 12899 12900 int doPostInstall(int status, int uid) { 12901 if (status == PackageManager.INSTALL_SUCCEEDED) { 12902 cleanUp(move.fromUuid); 12903 } else { 12904 cleanUp(move.toUuid); 12905 } 12906 return status; 12907 } 12908 12909 @Override 12910 String getCodePath() { 12911 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12912 } 12913 12914 @Override 12915 String getResourcePath() { 12916 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12917 } 12918 12919 private boolean cleanUp(String volumeUuid) { 12920 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 12921 move.dataAppName); 12922 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 12923 synchronized (mInstallLock) { 12924 // Clean up both app data and code 12925 removeDataDirsLI(volumeUuid, move.packageName); 12926 removeCodePathLI(codeFile); 12927 } 12928 return true; 12929 } 12930 12931 void cleanUpResourcesLI() { 12932 throw new UnsupportedOperationException(); 12933 } 12934 12935 boolean doPostDeleteLI(boolean delete) { 12936 throw new UnsupportedOperationException(); 12937 } 12938 } 12939 12940 static String getAsecPackageName(String packageCid) { 12941 int idx = packageCid.lastIndexOf("-"); 12942 if (idx == -1) { 12943 return packageCid; 12944 } 12945 return packageCid.substring(0, idx); 12946 } 12947 12948 // Utility method used to create code paths based on package name and available index. 12949 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 12950 String idxStr = ""; 12951 int idx = 1; 12952 // Fall back to default value of idx=1 if prefix is not 12953 // part of oldCodePath 12954 if (oldCodePath != null) { 12955 String subStr = oldCodePath; 12956 // Drop the suffix right away 12957 if (suffix != null && subStr.endsWith(suffix)) { 12958 subStr = subStr.substring(0, subStr.length() - suffix.length()); 12959 } 12960 // If oldCodePath already contains prefix find out the 12961 // ending index to either increment or decrement. 12962 int sidx = subStr.lastIndexOf(prefix); 12963 if (sidx != -1) { 12964 subStr = subStr.substring(sidx + prefix.length()); 12965 if (subStr != null) { 12966 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 12967 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 12968 } 12969 try { 12970 idx = Integer.parseInt(subStr); 12971 if (idx <= 1) { 12972 idx++; 12973 } else { 12974 idx--; 12975 } 12976 } catch(NumberFormatException e) { 12977 } 12978 } 12979 } 12980 } 12981 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 12982 return prefix + idxStr; 12983 } 12984 12985 private File getNextCodePath(File targetDir, String packageName) { 12986 int suffix = 1; 12987 File result; 12988 do { 12989 result = new File(targetDir, packageName + "-" + suffix); 12990 suffix++; 12991 } while (result.exists()); 12992 return result; 12993 } 12994 12995 // Utility method that returns the relative package path with respect 12996 // to the installation directory. Like say for /data/data/com.test-1.apk 12997 // string com.test-1 is returned. 12998 static String deriveCodePathName(String codePath) { 12999 if (codePath == null) { 13000 return null; 13001 } 13002 final File codeFile = new File(codePath); 13003 final String name = codeFile.getName(); 13004 if (codeFile.isDirectory()) { 13005 return name; 13006 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13007 final int lastDot = name.lastIndexOf('.'); 13008 return name.substring(0, lastDot); 13009 } else { 13010 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13011 return null; 13012 } 13013 } 13014 13015 static class PackageInstalledInfo { 13016 String name; 13017 int uid; 13018 // The set of users that originally had this package installed. 13019 int[] origUsers; 13020 // The set of users that now have this package installed. 13021 int[] newUsers; 13022 PackageParser.Package pkg; 13023 int returnCode; 13024 String returnMsg; 13025 PackageRemovedInfo removedInfo; 13026 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13027 13028 public void setError(int code, String msg) { 13029 setReturnCode(code); 13030 setReturnMessage(msg); 13031 Slog.w(TAG, msg); 13032 } 13033 13034 public void setError(String msg, PackageParserException e) { 13035 setReturnCode(e.error); 13036 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13037 Slog.w(TAG, msg, e); 13038 } 13039 13040 public void setError(String msg, PackageManagerException e) { 13041 returnCode = e.error; 13042 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13043 Slog.w(TAG, msg, e); 13044 } 13045 13046 public void setReturnCode(int returnCode) { 13047 this.returnCode = returnCode; 13048 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13049 for (int i = 0; i < childCount; i++) { 13050 addedChildPackages.valueAt(i).returnCode = returnCode; 13051 } 13052 } 13053 13054 private void setReturnMessage(String returnMsg) { 13055 this.returnMsg = returnMsg; 13056 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13057 for (int i = 0; i < childCount; i++) { 13058 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13059 } 13060 } 13061 13062 // In some error cases we want to convey more info back to the observer 13063 String origPackage; 13064 String origPermission; 13065 } 13066 13067 /* 13068 * Install a non-existing package. 13069 */ 13070 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 13071 UserHandle user, String installerPackageName, String volumeUuid, 13072 PackageInstalledInfo res) { 13073 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13074 13075 // Remember this for later, in case we need to rollback this install 13076 String pkgName = pkg.packageName; 13077 13078 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13079 13080 synchronized(mPackages) { 13081 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13082 // A package with the same name is already installed, though 13083 // it has been renamed to an older name. The package we 13084 // are trying to install should be installed as an update to 13085 // the existing one, but that has not been requested, so bail. 13086 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13087 + " without first uninstalling package running as " 13088 + mSettings.mRenamedPackages.get(pkgName)); 13089 return; 13090 } 13091 if (mPackages.containsKey(pkgName)) { 13092 // Don't allow installation over an existing package with the same name. 13093 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13094 + " without first uninstalling."); 13095 return; 13096 } 13097 } 13098 13099 try { 13100 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 13101 System.currentTimeMillis(), user); 13102 13103 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13104 13105 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13106 prepareAppDataAfterInstall(newPackage); 13107 13108 } else { 13109 // Remove package from internal structures, but keep around any 13110 // data that might have already existed 13111 deletePackageLI(pkgName, UserHandle.ALL, false, null, 13112 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13113 } 13114 } catch (PackageManagerException e) { 13115 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13116 } 13117 13118 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13119 } 13120 13121 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13122 // Can't rotate keys during boot or if sharedUser. 13123 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13124 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13125 return false; 13126 } 13127 // app is using upgradeKeySets; make sure all are valid 13128 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13129 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13130 for (int i = 0; i < upgradeKeySets.length; i++) { 13131 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13132 Slog.wtf(TAG, "Package " 13133 + (oldPs.name != null ? oldPs.name : "<null>") 13134 + " contains upgrade-key-set reference to unknown key-set: " 13135 + upgradeKeySets[i] 13136 + " reverting to signatures check."); 13137 return false; 13138 } 13139 } 13140 return true; 13141 } 13142 13143 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13144 // Upgrade keysets are being used. Determine if new package has a superset of the 13145 // required keys. 13146 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13147 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13148 for (int i = 0; i < upgradeKeySets.length; i++) { 13149 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13150 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13151 return true; 13152 } 13153 } 13154 return false; 13155 } 13156 13157 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 13158 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13159 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13160 13161 final PackageParser.Package oldPackage; 13162 final String pkgName = pkg.packageName; 13163 final int[] allUsers; 13164 final boolean weFroze; 13165 13166 // First find the old package info and check signatures 13167 synchronized(mPackages) { 13168 oldPackage = mPackages.get(pkgName); 13169 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13170 if (isEphemeral && !oldIsEphemeral) { 13171 // can't downgrade from full to ephemeral 13172 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13173 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13174 return; 13175 } 13176 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13177 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13178 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13179 if (!checkUpgradeKeySetLP(ps, pkg)) { 13180 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13181 "New package not signed by keys specified by upgrade-keysets: " 13182 + pkgName); 13183 return; 13184 } 13185 } else { 13186 // default to original signature matching 13187 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13188 != PackageManager.SIGNATURE_MATCH) { 13189 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13190 "New package has a different signature: " + pkgName); 13191 return; 13192 } 13193 } 13194 13195 // In case of rollback, remember per-user/profile install state 13196 allUsers = sUserManager.getUserIds(); 13197 13198 // Mark the app as frozen to prevent launching during the upgrade 13199 // process, and then kill all running instances 13200 if (!ps.frozen) { 13201 ps.frozen = true; 13202 weFroze = true; 13203 } else { 13204 weFroze = false; 13205 } 13206 } 13207 13208 try { 13209 replacePackageDirtyLI(pkg, oldPackage, parseFlags, scanFlags, user, allUsers, 13210 installerPackageName, res); 13211 } finally { 13212 // Regardless of success or failure of upgrade steps above, always 13213 // unfreeze the package if we froze it 13214 if (weFroze) { 13215 unfreezePackage(pkgName); 13216 } 13217 } 13218 } 13219 13220 private void replacePackageDirtyLI(PackageParser.Package pkg, PackageParser.Package oldPackage, 13221 int parseFlags, int scanFlags, UserHandle user, int[] allUsers, 13222 String installerPackageName, PackageInstalledInfo res) { 13223 // Update what is removed 13224 res.removedInfo = new PackageRemovedInfo(); 13225 res.removedInfo.uid = oldPackage.applicationInfo.uid; 13226 res.removedInfo.removedPackage = oldPackage.packageName; 13227 res.removedInfo.isUpdate = true; 13228 final int childCount = (oldPackage.childPackages != null) 13229 ? oldPackage.childPackages.size() : 0; 13230 for (int i = 0; i < childCount; i++) { 13231 boolean childPackageUpdated = false; 13232 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 13233 if (res.addedChildPackages != null) { 13234 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13235 if (childRes != null) { 13236 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 13237 childRes.removedInfo.removedPackage = childPkg.packageName; 13238 childRes.removedInfo.isUpdate = true; 13239 childPackageUpdated = true; 13240 } 13241 } 13242 if (!childPackageUpdated) { 13243 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 13244 childRemovedRes.removedPackage = childPkg.packageName; 13245 childRemovedRes.isUpdate = false; 13246 childRemovedRes.dataRemoved = true; 13247 synchronized (mPackages) { 13248 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13249 if (childPs != null) { 13250 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 13251 } 13252 } 13253 if (res.removedInfo.removedChildPackages == null) { 13254 res.removedInfo.removedChildPackages = new ArrayMap<>(); 13255 } 13256 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 13257 } 13258 } 13259 13260 boolean sysPkg = (isSystemApp(oldPackage)); 13261 if (sysPkg) { 13262 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 13263 user, allUsers, installerPackageName, res); 13264 } else { 13265 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 13266 user, allUsers, installerPackageName, res); 13267 } 13268 } 13269 13270 public List<String> getPreviousCodePaths(String packageName) { 13271 final PackageSetting ps = mSettings.mPackages.get(packageName); 13272 final List<String> result = new ArrayList<String>(); 13273 if (ps != null && ps.oldCodePaths != null) { 13274 result.addAll(ps.oldCodePaths); 13275 } 13276 return result; 13277 } 13278 13279 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 13280 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13281 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13282 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 13283 + deletedPackage); 13284 13285 String pkgName = deletedPackage.packageName; 13286 boolean deletedPkg = true; 13287 boolean addedPkg = false; 13288 boolean updatedSettings = false; 13289 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 13290 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 13291 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 13292 13293 final long origUpdateTime = (pkg.mExtras != null) 13294 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 13295 13296 // First delete the existing package while retaining the data directory 13297 if (!deletePackageLI(pkgName, null, true, allUsers, deleteFlags, 13298 res.removedInfo, true, pkg)) { 13299 // If the existing package wasn't successfully deleted 13300 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 13301 deletedPkg = false; 13302 } else { 13303 // Successfully deleted the old package; proceed with replace. 13304 13305 // If deleted package lived in a container, give users a chance to 13306 // relinquish resources before killing. 13307 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 13308 if (DEBUG_INSTALL) { 13309 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 13310 } 13311 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 13312 final ArrayList<String> pkgList = new ArrayList<String>(1); 13313 pkgList.add(deletedPackage.applicationInfo.packageName); 13314 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 13315 } 13316 13317 deleteCodeCacheDirsLI(pkg); 13318 deleteProfilesLI(pkg, /*destroy*/ false); 13319 13320 try { 13321 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 13322 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 13323 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13324 13325 // Update the in-memory copy of the previous code paths. 13326 PackageSetting ps = mSettings.mPackages.get(pkgName); 13327 if (!killApp) { 13328 if (ps.oldCodePaths == null) { 13329 ps.oldCodePaths = new ArraySet<>(); 13330 } 13331 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 13332 if (deletedPackage.splitCodePaths != null) { 13333 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 13334 } 13335 } else { 13336 ps.oldCodePaths = null; 13337 } 13338 if (ps.childPackageNames != null) { 13339 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 13340 final String childPkgName = ps.childPackageNames.get(i); 13341 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 13342 childPs.oldCodePaths = ps.oldCodePaths; 13343 } 13344 } 13345 prepareAppDataAfterInstall(newPackage); 13346 addedPkg = true; 13347 } catch (PackageManagerException e) { 13348 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13349 } 13350 } 13351 13352 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13353 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 13354 13355 // Revert all internal state mutations and added folders for the failed install 13356 if (addedPkg) { 13357 deletePackageLI(pkgName, null, true, allUsers, deleteFlags, 13358 res.removedInfo, true, null); 13359 } 13360 13361 // Restore the old package 13362 if (deletedPkg) { 13363 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 13364 File restoreFile = new File(deletedPackage.codePath); 13365 // Parse old package 13366 boolean oldExternal = isExternal(deletedPackage); 13367 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 13368 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 13369 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 13370 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 13371 try { 13372 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 13373 null); 13374 } catch (PackageManagerException e) { 13375 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 13376 + e.getMessage()); 13377 return; 13378 } 13379 13380 synchronized (mPackages) { 13381 // Ensure the installer package name up to date 13382 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13383 13384 // Update permissions for restored package 13385 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13386 13387 mSettings.writeLPr(); 13388 } 13389 13390 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 13391 } 13392 } else { 13393 synchronized (mPackages) { 13394 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 13395 if (ps != null) { 13396 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 13397 if (res.removedInfo.removedChildPackages != null) { 13398 final int childCount = res.removedInfo.removedChildPackages.size(); 13399 // Iterate in reverse as we may modify the collection 13400 for (int i = childCount - 1; i >= 0; i--) { 13401 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 13402 if (res.addedChildPackages.containsKey(childPackageName)) { 13403 res.removedInfo.removedChildPackages.removeAt(i); 13404 } else { 13405 PackageRemovedInfo childInfo = res.removedInfo 13406 .removedChildPackages.valueAt(i); 13407 childInfo.removedForAllUsers = mPackages.get( 13408 childInfo.removedPackage) == null; 13409 } 13410 } 13411 } 13412 } 13413 } 13414 } 13415 } 13416 13417 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 13418 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13419 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13420 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 13421 + ", old=" + deletedPackage); 13422 13423 final boolean disabledSystem; 13424 13425 // Set the system/privileged flags as needed 13426 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 13427 if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 13428 != 0) { 13429 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13430 } 13431 13432 // Kill package processes including services, providers, etc. 13433 killPackage(deletedPackage, "replace sys pkg"); 13434 13435 // Remove existing system package 13436 removePackageLI(deletedPackage, true); 13437 13438 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 13439 if (!disabledSystem) { 13440 // We didn't need to disable the .apk as a current system package, 13441 // which means we are replacing another update that is already 13442 // installed. We need to make sure to delete the older one's .apk. 13443 res.removedInfo.args = createInstallArgsForExisting(0, 13444 deletedPackage.applicationInfo.getCodePath(), 13445 deletedPackage.applicationInfo.getResourcePath(), 13446 getAppDexInstructionSets(deletedPackage.applicationInfo)); 13447 } else { 13448 res.removedInfo.args = null; 13449 } 13450 13451 // Successfully disabled the old package. Now proceed with re-installation 13452 deleteCodeCacheDirsLI(pkg); 13453 deleteProfilesLI(pkg, /*destroy*/ false); 13454 13455 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13456 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 13457 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 13458 13459 PackageParser.Package newPackage = null; 13460 try { 13461 // Add the package to the internal data structures 13462 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 13463 13464 // Set the update and install times 13465 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 13466 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 13467 System.currentTimeMillis()); 13468 13469 // Check for shared user id changes 13470 String invalidPackageName = getParentOrChildPackageChangedSharedUser( 13471 deletedPackage, newPackage); 13472 if (invalidPackageName != null) { 13473 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13474 "Forbidding shared user change from " + deletedPkgSetting.sharedUser 13475 + " to " + invalidPackageName); 13476 } 13477 13478 // Update the package dynamic state if succeeded 13479 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13480 // Now that the install succeeded make sure we remove data 13481 // directories for any child package the update removed. 13482 final int deletedChildCount = (deletedPackage.childPackages != null) 13483 ? deletedPackage.childPackages.size() : 0; 13484 final int newChildCount = (newPackage.childPackages != null) 13485 ? newPackage.childPackages.size() : 0; 13486 for (int i = 0; i < deletedChildCount; i++) { 13487 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 13488 boolean childPackageDeleted = true; 13489 for (int j = 0; j < newChildCount; j++) { 13490 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 13491 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 13492 childPackageDeleted = false; 13493 break; 13494 } 13495 } 13496 if (childPackageDeleted) { 13497 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 13498 deletedChildPkg.packageName); 13499 if (ps != null && res.removedInfo.removedChildPackages != null) { 13500 PackageRemovedInfo removedChildRes = res.removedInfo 13501 .removedChildPackages.get(deletedChildPkg.packageName); 13502 removePackageDataLI(ps, allUsers, removedChildRes, 0, false); 13503 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 13504 } 13505 } 13506 } 13507 13508 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13509 prepareAppDataAfterInstall(newPackage); 13510 } 13511 } catch (PackageManagerException e) { 13512 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 13513 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13514 } 13515 13516 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13517 // Re installation failed. Restore old information 13518 // Remove new pkg information 13519 if (newPackage != null) { 13520 removeInstalledPackageLI(newPackage, true); 13521 } 13522 // Add back the old system package 13523 try { 13524 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 13525 } catch (PackageManagerException e) { 13526 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 13527 } 13528 13529 synchronized (mPackages) { 13530 if (disabledSystem) { 13531 enableSystemPackageLPw(deletedPackage); 13532 } 13533 13534 // Ensure the installer package name up to date 13535 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13536 13537 // Update permissions for restored package 13538 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13539 13540 mSettings.writeLPr(); 13541 } 13542 13543 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 13544 + " after failed upgrade"); 13545 } 13546 } 13547 13548 /** 13549 * Checks whether the parent or any of the child packages have a change shared 13550 * user. For a package to be a valid update the shred users of the parent and 13551 * the children should match. We may later support changing child shared users. 13552 * @param oldPkg The updated package. 13553 * @param newPkg The update package. 13554 * @return The shared user that change between the versions. 13555 */ 13556 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 13557 PackageParser.Package newPkg) { 13558 // Check parent shared user 13559 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 13560 return newPkg.packageName; 13561 } 13562 // Check child shared users 13563 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13564 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 13565 for (int i = 0; i < newChildCount; i++) { 13566 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 13567 // If this child was present, did it have the same shared user? 13568 for (int j = 0; j < oldChildCount; j++) { 13569 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 13570 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 13571 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 13572 return newChildPkg.packageName; 13573 } 13574 } 13575 } 13576 return null; 13577 } 13578 13579 private void removeNativeBinariesLI(PackageSetting ps) { 13580 // Remove the lib path for the parent package 13581 if (ps != null) { 13582 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 13583 // Remove the lib path for the child packages 13584 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 13585 for (int i = 0; i < childCount; i++) { 13586 PackageSetting childPs = null; 13587 synchronized (mPackages) { 13588 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 13589 } 13590 if (childPs != null) { 13591 NativeLibraryHelper.removeNativeBinariesLI(childPs 13592 .legacyNativeLibraryPathString); 13593 } 13594 } 13595 } 13596 } 13597 13598 private void enableSystemPackageLPw(PackageParser.Package pkg) { 13599 // Enable the parent package 13600 mSettings.enableSystemPackageLPw(pkg.packageName); 13601 // Enable the child packages 13602 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13603 for (int i = 0; i < childCount; i++) { 13604 PackageParser.Package childPkg = pkg.childPackages.get(i); 13605 mSettings.enableSystemPackageLPw(childPkg.packageName); 13606 } 13607 } 13608 13609 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 13610 PackageParser.Package newPkg) { 13611 // Disable the parent package (parent always replaced) 13612 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 13613 // Disable the child packages 13614 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13615 for (int i = 0; i < childCount; i++) { 13616 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 13617 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 13618 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 13619 } 13620 return disabled; 13621 } 13622 13623 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 13624 String installerPackageName) { 13625 // Enable the parent package 13626 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 13627 // Enable the child packages 13628 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13629 for (int i = 0; i < childCount; i++) { 13630 PackageParser.Package childPkg = pkg.childPackages.get(i); 13631 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 13632 } 13633 } 13634 13635 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 13636 // Collect all used permissions in the UID 13637 ArraySet<String> usedPermissions = new ArraySet<>(); 13638 final int packageCount = su.packages.size(); 13639 for (int i = 0; i < packageCount; i++) { 13640 PackageSetting ps = su.packages.valueAt(i); 13641 if (ps.pkg == null) { 13642 continue; 13643 } 13644 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 13645 for (int j = 0; j < requestedPermCount; j++) { 13646 String permission = ps.pkg.requestedPermissions.get(j); 13647 BasePermission bp = mSettings.mPermissions.get(permission); 13648 if (bp != null) { 13649 usedPermissions.add(permission); 13650 } 13651 } 13652 } 13653 13654 PermissionsState permissionsState = su.getPermissionsState(); 13655 // Prune install permissions 13656 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 13657 final int installPermCount = installPermStates.size(); 13658 for (int i = installPermCount - 1; i >= 0; i--) { 13659 PermissionState permissionState = installPermStates.get(i); 13660 if (!usedPermissions.contains(permissionState.getName())) { 13661 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 13662 if (bp != null) { 13663 permissionsState.revokeInstallPermission(bp); 13664 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 13665 PackageManager.MASK_PERMISSION_FLAGS, 0); 13666 } 13667 } 13668 } 13669 13670 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 13671 13672 // Prune runtime permissions 13673 for (int userId : allUserIds) { 13674 List<PermissionState> runtimePermStates = permissionsState 13675 .getRuntimePermissionStates(userId); 13676 final int runtimePermCount = runtimePermStates.size(); 13677 for (int i = runtimePermCount - 1; i >= 0; i--) { 13678 PermissionState permissionState = runtimePermStates.get(i); 13679 if (!usedPermissions.contains(permissionState.getName())) { 13680 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 13681 if (bp != null) { 13682 permissionsState.revokeRuntimePermission(bp, userId); 13683 permissionsState.updatePermissionFlags(bp, userId, 13684 PackageManager.MASK_PERMISSION_FLAGS, 0); 13685 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 13686 runtimePermissionChangedUserIds, userId); 13687 } 13688 } 13689 } 13690 } 13691 13692 return runtimePermissionChangedUserIds; 13693 } 13694 13695 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 13696 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 13697 // Update the parent package setting 13698 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 13699 res, user); 13700 // Update the child packages setting 13701 final int childCount = (newPackage.childPackages != null) 13702 ? newPackage.childPackages.size() : 0; 13703 for (int i = 0; i < childCount; i++) { 13704 PackageParser.Package childPackage = newPackage.childPackages.get(i); 13705 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 13706 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 13707 childRes.origUsers, childRes, user); 13708 } 13709 } 13710 13711 private void updateSettingsInternalLI(PackageParser.Package newPackage, 13712 String installerPackageName, int[] allUsers, int[] installedForUsers, 13713 PackageInstalledInfo res, UserHandle user) { 13714 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 13715 13716 String pkgName = newPackage.packageName; 13717 synchronized (mPackages) { 13718 //write settings. the installStatus will be incomplete at this stage. 13719 //note that the new package setting would have already been 13720 //added to mPackages. It hasn't been persisted yet. 13721 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 13722 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 13723 mSettings.writeLPr(); 13724 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13725 } 13726 13727 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 13728 synchronized (mPackages) { 13729 updatePermissionsLPw(newPackage.packageName, newPackage, 13730 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 13731 ? UPDATE_PERMISSIONS_ALL : 0)); 13732 // For system-bundled packages, we assume that installing an upgraded version 13733 // of the package implies that the user actually wants to run that new code, 13734 // so we enable the package. 13735 PackageSetting ps = mSettings.mPackages.get(pkgName); 13736 final int userId = user.getIdentifier(); 13737 if (ps != null) { 13738 if (isSystemApp(newPackage)) { 13739 if (DEBUG_INSTALL) { 13740 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 13741 } 13742 // Enable system package for requested users 13743 if (res.origUsers != null) { 13744 for (int origUserId : res.origUsers) { 13745 if (userId == UserHandle.USER_ALL || userId == origUserId) { 13746 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 13747 origUserId, installerPackageName); 13748 } 13749 } 13750 } 13751 // Also convey the prior install/uninstall state 13752 if (allUsers != null && installedForUsers != null) { 13753 for (int currentUserId : allUsers) { 13754 final boolean installed = ArrayUtils.contains( 13755 installedForUsers, currentUserId); 13756 if (DEBUG_INSTALL) { 13757 Slog.d(TAG, " user " + currentUserId + " => " + installed); 13758 } 13759 ps.setInstalled(installed, currentUserId); 13760 } 13761 // these install state changes will be persisted in the 13762 // upcoming call to mSettings.writeLPr(). 13763 } 13764 } 13765 // It's implied that when a user requests installation, they want the app to be 13766 // installed and enabled. 13767 if (userId != UserHandle.USER_ALL) { 13768 ps.setInstalled(true, userId); 13769 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 13770 } 13771 } 13772 res.name = pkgName; 13773 res.uid = newPackage.applicationInfo.uid; 13774 res.pkg = newPackage; 13775 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 13776 mSettings.setInstallerPackageName(pkgName, installerPackageName); 13777 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13778 //to update install status 13779 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 13780 mSettings.writeLPr(); 13781 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13782 } 13783 13784 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13785 } 13786 13787 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 13788 try { 13789 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 13790 installPackageLI(args, res); 13791 } finally { 13792 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13793 } 13794 } 13795 13796 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 13797 final int installFlags = args.installFlags; 13798 final String installerPackageName = args.installerPackageName; 13799 final String volumeUuid = args.volumeUuid; 13800 final File tmpPackageFile = new File(args.getCodePath()); 13801 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 13802 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 13803 || (args.volumeUuid != null)); 13804 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 13805 boolean replace = false; 13806 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 13807 if (args.move != null) { 13808 // moving a complete application; perform an initial scan on the new install location 13809 scanFlags |= SCAN_INITIAL; 13810 } 13811 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 13812 scanFlags |= SCAN_DONT_KILL_APP; 13813 } 13814 13815 // Result object to be returned 13816 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13817 13818 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 13819 13820 // Sanity check 13821 if (ephemeral && (forwardLocked || onExternal)) { 13822 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 13823 + " external=" + onExternal); 13824 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13825 return; 13826 } 13827 13828 // Retrieve PackageSettings and parse package 13829 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 13830 | PackageParser.PARSE_ENFORCE_CODE 13831 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 13832 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 13833 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 13834 PackageParser pp = new PackageParser(); 13835 pp.setSeparateProcesses(mSeparateProcesses); 13836 pp.setDisplayMetrics(mMetrics); 13837 13838 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 13839 final PackageParser.Package pkg; 13840 try { 13841 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 13842 } catch (PackageParserException e) { 13843 res.setError("Failed parse during installPackageLI", e); 13844 return; 13845 } finally { 13846 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13847 } 13848 13849 // If we are installing a clustered package add results for the children 13850 if (pkg.childPackages != null) { 13851 synchronized (mPackages) { 13852 final int childCount = pkg.childPackages.size(); 13853 for (int i = 0; i < childCount; i++) { 13854 PackageParser.Package childPkg = pkg.childPackages.get(i); 13855 PackageInstalledInfo childRes = new PackageInstalledInfo(); 13856 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13857 childRes.pkg = childPkg; 13858 childRes.name = childPkg.packageName; 13859 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13860 if (childPs != null) { 13861 childRes.origUsers = childPs.queryInstalledUsers( 13862 sUserManager.getUserIds(), true); 13863 } 13864 if ((mPackages.containsKey(childPkg.packageName))) { 13865 childRes.removedInfo = new PackageRemovedInfo(); 13866 childRes.removedInfo.removedPackage = childPkg.packageName; 13867 } 13868 if (res.addedChildPackages == null) { 13869 res.addedChildPackages = new ArrayMap<>(); 13870 } 13871 res.addedChildPackages.put(childPkg.packageName, childRes); 13872 } 13873 } 13874 } 13875 13876 // If package doesn't declare API override, mark that we have an install 13877 // time CPU ABI override. 13878 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 13879 pkg.cpuAbiOverride = args.abiOverride; 13880 } 13881 13882 String pkgName = res.name = pkg.packageName; 13883 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 13884 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 13885 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 13886 return; 13887 } 13888 } 13889 13890 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 13891 try { 13892 PackageParser.collectCertificates(pkg, parseFlags); 13893 } catch (PackageParserException e) { 13894 res.setError("Failed collect during installPackageLI", e); 13895 return; 13896 } finally { 13897 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13898 } 13899 13900 // Get rid of all references to package scan path via parser. 13901 pp = null; 13902 String oldCodePath = null; 13903 boolean systemApp = false; 13904 synchronized (mPackages) { 13905 // Check if installing already existing package 13906 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 13907 String oldName = mSettings.mRenamedPackages.get(pkgName); 13908 if (pkg.mOriginalPackages != null 13909 && pkg.mOriginalPackages.contains(oldName) 13910 && mPackages.containsKey(oldName)) { 13911 // This package is derived from an original package, 13912 // and this device has been updating from that original 13913 // name. We must continue using the original name, so 13914 // rename the new package here. 13915 pkg.setPackageName(oldName); 13916 pkgName = pkg.packageName; 13917 replace = true; 13918 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 13919 + oldName + " pkgName=" + pkgName); 13920 } else if (mPackages.containsKey(pkgName)) { 13921 // This package, under its official name, already exists 13922 // on the device; we should replace it. 13923 replace = true; 13924 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 13925 } 13926 13927 // Child packages are installed through the parent package 13928 if (pkg.parentPackage != null) { 13929 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 13930 "Package " + pkg.packageName + " is child of package " 13931 + pkg.parentPackage.parentPackage + ". Child packages " 13932 + "can be updated only through the parent package."); 13933 return; 13934 } 13935 13936 if (replace) { 13937 // Prevent apps opting out from runtime permissions 13938 PackageParser.Package oldPackage = mPackages.get(pkgName); 13939 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 13940 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 13941 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 13942 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 13943 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 13944 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 13945 + " doesn't support runtime permissions but the old" 13946 + " target SDK " + oldTargetSdk + " does."); 13947 return; 13948 } 13949 13950 // Prevent installing of child packages 13951 if (oldPackage.parentPackage != null) { 13952 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 13953 "Package " + pkg.packageName + " is child of package " 13954 + oldPackage.parentPackage + ". Child packages " 13955 + "can be updated only through the parent package."); 13956 return; 13957 } 13958 } 13959 } 13960 13961 PackageSetting ps = mSettings.mPackages.get(pkgName); 13962 if (ps != null) { 13963 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 13964 13965 // Quick sanity check that we're signed correctly if updating; 13966 // we'll check this again later when scanning, but we want to 13967 // bail early here before tripping over redefined permissions. 13968 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13969 if (!checkUpgradeKeySetLP(ps, pkg)) { 13970 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 13971 + pkg.packageName + " upgrade keys do not match the " 13972 + "previously installed version"); 13973 return; 13974 } 13975 } else { 13976 try { 13977 verifySignaturesLP(ps, pkg); 13978 } catch (PackageManagerException e) { 13979 res.setError(e.error, e.getMessage()); 13980 return; 13981 } 13982 } 13983 13984 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 13985 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 13986 systemApp = (ps.pkg.applicationInfo.flags & 13987 ApplicationInfo.FLAG_SYSTEM) != 0; 13988 } 13989 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13990 } 13991 13992 // Check whether the newly-scanned package wants to define an already-defined perm 13993 int N = pkg.permissions.size(); 13994 for (int i = N-1; i >= 0; i--) { 13995 PackageParser.Permission perm = pkg.permissions.get(i); 13996 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 13997 if (bp != null) { 13998 // If the defining package is signed with our cert, it's okay. This 13999 // also includes the "updating the same package" case, of course. 14000 // "updating same package" could also involve key-rotation. 14001 final boolean sigsOk; 14002 if (bp.sourcePackage.equals(pkg.packageName) 14003 && (bp.packageSetting instanceof PackageSetting) 14004 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14005 scanFlags))) { 14006 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14007 } else { 14008 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14009 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14010 } 14011 if (!sigsOk) { 14012 // If the owning package is the system itself, we log but allow 14013 // install to proceed; we fail the install on all other permission 14014 // redefinitions. 14015 if (!bp.sourcePackage.equals("android")) { 14016 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14017 + pkg.packageName + " attempting to redeclare permission " 14018 + perm.info.name + " already owned by " + bp.sourcePackage); 14019 res.origPermission = perm.info.name; 14020 res.origPackage = bp.sourcePackage; 14021 return; 14022 } else { 14023 Slog.w(TAG, "Package " + pkg.packageName 14024 + " attempting to redeclare system permission " 14025 + perm.info.name + "; ignoring new declaration"); 14026 pkg.permissions.remove(i); 14027 } 14028 } 14029 } 14030 } 14031 } 14032 14033 if (systemApp) { 14034 if (onExternal) { 14035 // Abort update; system app can't be replaced with app on sdcard 14036 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14037 "Cannot install updates to system apps on sdcard"); 14038 return; 14039 } else if (ephemeral) { 14040 // Abort update; system app can't be replaced with an ephemeral app 14041 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14042 "Cannot update a system app with an ephemeral app"); 14043 return; 14044 } 14045 } 14046 14047 if (args.move != null) { 14048 // We did an in-place move, so dex is ready to roll 14049 scanFlags |= SCAN_NO_DEX; 14050 scanFlags |= SCAN_MOVE; 14051 14052 synchronized (mPackages) { 14053 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14054 if (ps == null) { 14055 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14056 "Missing settings for moved package " + pkgName); 14057 } 14058 14059 // We moved the entire application as-is, so bring over the 14060 // previously derived ABI information. 14061 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14062 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14063 } 14064 14065 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14066 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14067 scanFlags |= SCAN_NO_DEX; 14068 14069 try { 14070 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14071 args.abiOverride : pkg.cpuAbiOverride); 14072 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14073 true /* extract libs */); 14074 } catch (PackageManagerException pme) { 14075 Slog.e(TAG, "Error deriving application ABI", pme); 14076 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14077 return; 14078 } 14079 14080 14081 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14082 // Do not run PackageDexOptimizer through the local performDexOpt 14083 // method because `pkg` is not in `mPackages` yet. 14084 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 14085 false /* checkProfiles */, getCompilerFilterForReason(REASON_INSTALL)); 14086 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14087 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14088 String msg = "Extracking package failed for " + pkgName; 14089 res.setError(INSTALL_FAILED_DEXOPT, msg); 14090 return; 14091 } 14092 } 14093 14094 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14095 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14096 return; 14097 } 14098 14099 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14100 14101 if (replace) { 14102 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14103 installerPackageName, res); 14104 } else { 14105 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14106 args.user, installerPackageName, volumeUuid, res); 14107 } 14108 synchronized (mPackages) { 14109 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14110 if (ps != null) { 14111 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14112 } 14113 14114 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14115 for (int i = 0; i < childCount; i++) { 14116 PackageParser.Package childPkg = pkg.childPackages.get(i); 14117 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14118 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14119 if (childPs != null) { 14120 childRes.newUsers = childPs.queryInstalledUsers( 14121 sUserManager.getUserIds(), true); 14122 } 14123 } 14124 } 14125 } 14126 14127 private void startIntentFilterVerifications(int userId, boolean replacing, 14128 PackageParser.Package pkg) { 14129 if (mIntentFilterVerifierComponent == null) { 14130 Slog.w(TAG, "No IntentFilter verification will not be done as " 14131 + "there is no IntentFilterVerifier available!"); 14132 return; 14133 } 14134 14135 final int verifierUid = getPackageUid( 14136 mIntentFilterVerifierComponent.getPackageName(), 14137 MATCH_DEBUG_TRIAGED_MISSING, 14138 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 14139 14140 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14141 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14142 mHandler.sendMessage(msg); 14143 14144 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14145 for (int i = 0; i < childCount; i++) { 14146 PackageParser.Package childPkg = pkg.childPackages.get(i); 14147 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14148 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 14149 mHandler.sendMessage(msg); 14150 } 14151 } 14152 14153 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 14154 PackageParser.Package pkg) { 14155 int size = pkg.activities.size(); 14156 if (size == 0) { 14157 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14158 "No activity, so no need to verify any IntentFilter!"); 14159 return; 14160 } 14161 14162 final boolean hasDomainURLs = hasDomainURLs(pkg); 14163 if (!hasDomainURLs) { 14164 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14165 "No domain URLs, so no need to verify any IntentFilter!"); 14166 return; 14167 } 14168 14169 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 14170 + " if any IntentFilter from the " + size 14171 + " Activities needs verification ..."); 14172 14173 int count = 0; 14174 final String packageName = pkg.packageName; 14175 14176 synchronized (mPackages) { 14177 // If this is a new install and we see that we've already run verification for this 14178 // package, we have nothing to do: it means the state was restored from backup. 14179 if (!replacing) { 14180 IntentFilterVerificationInfo ivi = 14181 mSettings.getIntentFilterVerificationLPr(packageName); 14182 if (ivi != null) { 14183 if (DEBUG_DOMAIN_VERIFICATION) { 14184 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 14185 + ivi.getStatusString()); 14186 } 14187 return; 14188 } 14189 } 14190 14191 // If any filters need to be verified, then all need to be. 14192 boolean needToVerify = false; 14193 for (PackageParser.Activity a : pkg.activities) { 14194 for (ActivityIntentInfo filter : a.intents) { 14195 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 14196 if (DEBUG_DOMAIN_VERIFICATION) { 14197 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 14198 } 14199 needToVerify = true; 14200 break; 14201 } 14202 } 14203 } 14204 14205 if (needToVerify) { 14206 final int verificationId = mIntentFilterVerificationToken++; 14207 for (PackageParser.Activity a : pkg.activities) { 14208 for (ActivityIntentInfo filter : a.intents) { 14209 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 14210 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14211 "Verification needed for IntentFilter:" + filter.toString()); 14212 mIntentFilterVerifier.addOneIntentFilterVerification( 14213 verifierUid, userId, verificationId, filter, packageName); 14214 count++; 14215 } 14216 } 14217 } 14218 } 14219 } 14220 14221 if (count > 0) { 14222 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 14223 + " IntentFilter verification" + (count > 1 ? "s" : "") 14224 + " for userId:" + userId); 14225 mIntentFilterVerifier.startVerifications(userId); 14226 } else { 14227 if (DEBUG_DOMAIN_VERIFICATION) { 14228 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 14229 } 14230 } 14231 } 14232 14233 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 14234 final ComponentName cn = filter.activity.getComponentName(); 14235 final String packageName = cn.getPackageName(); 14236 14237 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 14238 packageName); 14239 if (ivi == null) { 14240 return true; 14241 } 14242 int status = ivi.getStatus(); 14243 switch (status) { 14244 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 14245 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 14246 return true; 14247 14248 default: 14249 // Nothing to do 14250 return false; 14251 } 14252 } 14253 14254 private static boolean isMultiArch(ApplicationInfo info) { 14255 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 14256 } 14257 14258 private static boolean isExternal(PackageParser.Package pkg) { 14259 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14260 } 14261 14262 private static boolean isExternal(PackageSetting ps) { 14263 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14264 } 14265 14266 private static boolean isEphemeral(PackageParser.Package pkg) { 14267 return pkg.applicationInfo.isEphemeralApp(); 14268 } 14269 14270 private static boolean isEphemeral(PackageSetting ps) { 14271 return ps.pkg != null && isEphemeral(ps.pkg); 14272 } 14273 14274 private static boolean isSystemApp(PackageParser.Package pkg) { 14275 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 14276 } 14277 14278 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 14279 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14280 } 14281 14282 private static boolean hasDomainURLs(PackageParser.Package pkg) { 14283 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 14284 } 14285 14286 private static boolean isSystemApp(PackageSetting ps) { 14287 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 14288 } 14289 14290 private static boolean isUpdatedSystemApp(PackageSetting ps) { 14291 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 14292 } 14293 14294 private int packageFlagsToInstallFlags(PackageSetting ps) { 14295 int installFlags = 0; 14296 if (isEphemeral(ps)) { 14297 installFlags |= PackageManager.INSTALL_EPHEMERAL; 14298 } 14299 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 14300 // This existing package was an external ASEC install when we have 14301 // the external flag without a UUID 14302 installFlags |= PackageManager.INSTALL_EXTERNAL; 14303 } 14304 if (ps.isForwardLocked()) { 14305 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 14306 } 14307 return installFlags; 14308 } 14309 14310 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 14311 if (isExternal(pkg)) { 14312 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14313 return StorageManager.UUID_PRIMARY_PHYSICAL; 14314 } else { 14315 return pkg.volumeUuid; 14316 } 14317 } else { 14318 return StorageManager.UUID_PRIVATE_INTERNAL; 14319 } 14320 } 14321 14322 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 14323 if (isExternal(pkg)) { 14324 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14325 return mSettings.getExternalVersion(); 14326 } else { 14327 return mSettings.findOrCreateVersion(pkg.volumeUuid); 14328 } 14329 } else { 14330 return mSettings.getInternalVersion(); 14331 } 14332 } 14333 14334 private void deleteTempPackageFiles() { 14335 final FilenameFilter filter = new FilenameFilter() { 14336 public boolean accept(File dir, String name) { 14337 return name.startsWith("vmdl") && name.endsWith(".tmp"); 14338 } 14339 }; 14340 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 14341 file.delete(); 14342 } 14343 } 14344 14345 @Override 14346 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 14347 int flags) { 14348 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 14349 flags); 14350 } 14351 14352 @Override 14353 public void deletePackage(final String packageName, 14354 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 14355 mContext.enforceCallingOrSelfPermission( 14356 android.Manifest.permission.DELETE_PACKAGES, null); 14357 Preconditions.checkNotNull(packageName); 14358 Preconditions.checkNotNull(observer); 14359 final int uid = Binder.getCallingUid(); 14360 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 14361 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 14362 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 14363 mContext.enforceCallingOrSelfPermission( 14364 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14365 "deletePackage for user " + userId); 14366 } 14367 14368 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 14369 try { 14370 observer.onPackageDeleted(packageName, 14371 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 14372 } catch (RemoteException re) { 14373 } 14374 return; 14375 } 14376 14377 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 14378 try { 14379 observer.onPackageDeleted(packageName, 14380 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 14381 } catch (RemoteException re) { 14382 } 14383 return; 14384 } 14385 14386 if (DEBUG_REMOVE) { 14387 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 14388 + " deleteAllUsers: " + deleteAllUsers ); 14389 } 14390 // Queue up an async operation since the package deletion may take a little while. 14391 mHandler.post(new Runnable() { 14392 public void run() { 14393 mHandler.removeCallbacks(this); 14394 int returnCode; 14395 if (!deleteAllUsers) { 14396 returnCode = deletePackageX(packageName, userId, flags); 14397 } else { 14398 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 14399 // If nobody is blocking uninstall, proceed with delete for all users 14400 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 14401 returnCode = deletePackageX(packageName, userId, flags); 14402 } else { 14403 // Otherwise uninstall individually for users with blockUninstalls=false 14404 final int userFlags = flags & ~PackageManager.DELETE_ALL_USERS; 14405 for (int userId : users) { 14406 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 14407 returnCode = deletePackageX(packageName, userId, userFlags); 14408 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 14409 Slog.w(TAG, "Package delete failed for user " + userId 14410 + ", returnCode " + returnCode); 14411 } 14412 } 14413 } 14414 // The app has only been marked uninstalled for certain users. 14415 // We still need to report that delete was blocked 14416 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 14417 } 14418 } 14419 try { 14420 observer.onPackageDeleted(packageName, returnCode, null); 14421 } catch (RemoteException e) { 14422 Log.i(TAG, "Observer no longer exists."); 14423 } //end catch 14424 } //end run 14425 }); 14426 } 14427 14428 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 14429 int[] result = EMPTY_INT_ARRAY; 14430 for (int userId : userIds) { 14431 if (getBlockUninstallForUser(packageName, userId)) { 14432 result = ArrayUtils.appendInt(result, userId); 14433 } 14434 } 14435 return result; 14436 } 14437 14438 @Override 14439 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 14440 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 14441 } 14442 14443 private boolean isPackageDeviceAdmin(String packageName, int userId) { 14444 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 14445 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 14446 try { 14447 if (dpm != null) { 14448 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 14449 /* callingUserOnly =*/ false); 14450 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 14451 : deviceOwnerComponentName.getPackageName(); 14452 // Does the package contains the device owner? 14453 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 14454 // this check is probably not needed, since DO should be registered as a device 14455 // admin on some user too. (Original bug for this: b/17657954) 14456 if (packageName.equals(deviceOwnerPackageName)) { 14457 return true; 14458 } 14459 // Does it contain a device admin for any user? 14460 int[] users; 14461 if (userId == UserHandle.USER_ALL) { 14462 users = sUserManager.getUserIds(); 14463 } else { 14464 users = new int[]{userId}; 14465 } 14466 for (int i = 0; i < users.length; ++i) { 14467 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 14468 return true; 14469 } 14470 } 14471 } 14472 } catch (RemoteException e) { 14473 } 14474 return false; 14475 } 14476 14477 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 14478 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 14479 } 14480 14481 /** 14482 * This method is an internal method that could be get invoked either 14483 * to delete an installed package or to clean up a failed installation. 14484 * After deleting an installed package, a broadcast is sent to notify any 14485 * listeners that the package has been installed. For cleaning up a failed 14486 * installation, the broadcast is not necessary since the package's 14487 * installation wouldn't have sent the initial broadcast either 14488 * The key steps in deleting a package are 14489 * deleting the package information in internal structures like mPackages, 14490 * deleting the packages base directories through installd 14491 * updating mSettings to reflect current status 14492 * persisting settings for later use 14493 * sending a broadcast if necessary 14494 */ 14495 private int deletePackageX(String packageName, int userId, int flags) { 14496 final PackageRemovedInfo info = new PackageRemovedInfo(); 14497 final boolean res; 14498 14499 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 14500 ? UserHandle.ALL : new UserHandle(userId); 14501 14502 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 14503 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 14504 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 14505 } 14506 14507 PackageSetting uninstalledPs = null; 14508 14509 // for the uninstall-updates case and restricted profiles, remember the per- 14510 // user handle installed state 14511 int[] allUsers; 14512 synchronized (mPackages) { 14513 uninstalledPs = mSettings.mPackages.get(packageName); 14514 if (uninstalledPs == null) { 14515 Slog.w(TAG, "Not removing non-existent package " + packageName); 14516 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14517 } 14518 allUsers = sUserManager.getUserIds(); 14519 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 14520 } 14521 14522 synchronized (mInstallLock) { 14523 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 14524 res = deletePackageLI(packageName, removeForUser, true, allUsers, 14525 flags | REMOVE_CHATTY, info, true, null); 14526 deleteProfilesLI(packageName, /*destroy*/ true); 14527 synchronized (mPackages) { 14528 if (res) { 14529 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 14530 } 14531 } 14532 } 14533 14534 if (res) { 14535 final boolean killApp = (flags & PackageManager.INSTALL_DONT_KILL_APP) == 0; 14536 info.sendPackageRemovedBroadcasts(killApp); 14537 info.sendSystemPackageUpdatedBroadcasts(); 14538 info.sendSystemPackageAppearedBroadcasts(); 14539 } 14540 // Force a gc here. 14541 Runtime.getRuntime().gc(); 14542 // Delete the resources here after sending the broadcast to let 14543 // other processes clean up before deleting resources. 14544 if (info.args != null) { 14545 synchronized (mInstallLock) { 14546 info.args.doPostDeleteLI(true); 14547 } 14548 } 14549 14550 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14551 } 14552 14553 class PackageRemovedInfo { 14554 String removedPackage; 14555 int uid = -1; 14556 int removedAppId = -1; 14557 int[] origUsers; 14558 int[] removedUsers = null; 14559 boolean isRemovedPackageSystemUpdate = false; 14560 boolean isUpdate; 14561 boolean dataRemoved; 14562 boolean removedForAllUsers; 14563 // Clean up resources deleted packages. 14564 InstallArgs args = null; 14565 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 14566 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 14567 14568 void sendPackageRemovedBroadcasts(boolean killApp) { 14569 sendPackageRemovedBroadcastInternal(killApp); 14570 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 14571 for (int i = 0; i < childCount; i++) { 14572 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 14573 childInfo.sendPackageRemovedBroadcastInternal(killApp); 14574 } 14575 } 14576 14577 void sendSystemPackageUpdatedBroadcasts() { 14578 if (isRemovedPackageSystemUpdate) { 14579 sendSystemPackageUpdatedBroadcastsInternal(); 14580 final int childCount = (removedChildPackages != null) 14581 ? removedChildPackages.size() : 0; 14582 for (int i = 0; i < childCount; i++) { 14583 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 14584 if (childInfo.isRemovedPackageSystemUpdate) { 14585 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 14586 } 14587 } 14588 } 14589 } 14590 14591 void sendSystemPackageAppearedBroadcasts() { 14592 final int packageCount = (appearedChildPackages != null) 14593 ? appearedChildPackages.size() : 0; 14594 for (int i = 0; i < packageCount; i++) { 14595 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 14596 for (int userId : installedInfo.newUsers) { 14597 sendPackageAddedForUser(installedInfo.name, true, 14598 UserHandle.getAppId(installedInfo.uid), userId); 14599 } 14600 } 14601 } 14602 14603 private void sendSystemPackageUpdatedBroadcastsInternal() { 14604 Bundle extras = new Bundle(2); 14605 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 14606 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14607 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 14608 extras, 0, null, null, null); 14609 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 14610 extras, 0, null, null, null); 14611 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 14612 null, 0, removedPackage, null, null); 14613 } 14614 14615 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 14616 Bundle extras = new Bundle(2); 14617 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 14618 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 14619 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 14620 if (isUpdate || isRemovedPackageSystemUpdate) { 14621 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14622 } 14623 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 14624 if (removedPackage != null) { 14625 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 14626 extras, 0, null, null, removedUsers); 14627 if (dataRemoved && !isRemovedPackageSystemUpdate) { 14628 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 14629 removedPackage, extras, 0, null, null, removedUsers); 14630 } 14631 } 14632 if (removedAppId >= 0) { 14633 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 14634 removedUsers); 14635 } 14636 } 14637 } 14638 14639 /* 14640 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 14641 * flag is not set, the data directory is removed as well. 14642 * make sure this flag is set for partially installed apps. If not its meaningless to 14643 * delete a partially installed application. 14644 */ 14645 private void removePackageDataLI(PackageSetting ps, int[] allUserHandles, 14646 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 14647 String packageName = ps.name; 14648 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 14649 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 14650 // Retrieve object to delete permissions for shared user later on 14651 final PackageSetting deletedPs; 14652 // reader 14653 synchronized (mPackages) { 14654 deletedPs = mSettings.mPackages.get(packageName); 14655 if (outInfo != null) { 14656 outInfo.removedPackage = packageName; 14657 outInfo.removedUsers = deletedPs != null 14658 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 14659 : null; 14660 } 14661 } 14662 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 14663 removeDataDirsLI(ps.volumeUuid, packageName); 14664 if (outInfo != null) { 14665 outInfo.dataRemoved = true; 14666 } 14667 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 14668 } 14669 // writer 14670 synchronized (mPackages) { 14671 if (deletedPs != null) { 14672 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 14673 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 14674 clearDefaultBrowserIfNeeded(packageName); 14675 if (outInfo != null) { 14676 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 14677 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 14678 } 14679 updatePermissionsLPw(deletedPs.name, null, 0); 14680 if (deletedPs.sharedUser != null) { 14681 // Remove permissions associated with package. Since runtime 14682 // permissions are per user we have to kill the removed package 14683 // or packages running under the shared user of the removed 14684 // package if revoking the permissions requested only by the removed 14685 // package is successful and this causes a change in gids. 14686 for (int userId : UserManagerService.getInstance().getUserIds()) { 14687 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 14688 userId); 14689 if (userIdToKill == UserHandle.USER_ALL 14690 || userIdToKill >= UserHandle.USER_SYSTEM) { 14691 // If gids changed for this user, kill all affected packages. 14692 mHandler.post(new Runnable() { 14693 @Override 14694 public void run() { 14695 // This has to happen with no lock held. 14696 killApplication(deletedPs.name, deletedPs.appId, 14697 KILL_APP_REASON_GIDS_CHANGED); 14698 } 14699 }); 14700 break; 14701 } 14702 } 14703 } 14704 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 14705 } 14706 // make sure to preserve per-user disabled state if this removal was just 14707 // a downgrade of a system app to the factory package 14708 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 14709 if (DEBUG_REMOVE) { 14710 Slog.d(TAG, "Propagating install state across downgrade"); 14711 } 14712 for (int userId : allUserHandles) { 14713 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 14714 if (DEBUG_REMOVE) { 14715 Slog.d(TAG, " user " + userId + " => " + installed); 14716 } 14717 ps.setInstalled(installed, userId); 14718 } 14719 } 14720 } 14721 // can downgrade to reader 14722 if (writeSettings) { 14723 // Save settings now 14724 mSettings.writeLPr(); 14725 } 14726 } 14727 if (outInfo != null) { 14728 // A user ID was deleted here. Go through all users and remove it 14729 // from KeyStore. 14730 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 14731 } 14732 } 14733 14734 static boolean locationIsPrivileged(File path) { 14735 try { 14736 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 14737 .getCanonicalPath(); 14738 return path.getCanonicalPath().startsWith(privilegedAppDir); 14739 } catch (IOException e) { 14740 Slog.e(TAG, "Unable to access code path " + path); 14741 } 14742 return false; 14743 } 14744 14745 /* 14746 * Tries to delete system package. 14747 */ 14748 private boolean deleteSystemPackageLI(PackageParser.Package deletedPkg, 14749 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 14750 boolean writeSettings) { 14751 if (deletedPs.parentPackageName != null) { 14752 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 14753 return false; 14754 } 14755 14756 final boolean applyUserRestrictions 14757 = (allUserHandles != null) && (outInfo.origUsers != null); 14758 final PackageSetting disabledPs; 14759 // Confirm if the system package has been updated 14760 // An updated system app can be deleted. This will also have to restore 14761 // the system pkg from system partition 14762 // reader 14763 synchronized (mPackages) { 14764 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 14765 } 14766 14767 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 14768 + " disabledPs=" + disabledPs); 14769 14770 if (disabledPs == null) { 14771 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 14772 return false; 14773 } else if (DEBUG_REMOVE) { 14774 Slog.d(TAG, "Deleting system pkg from data partition"); 14775 } 14776 14777 if (DEBUG_REMOVE) { 14778 if (applyUserRestrictions) { 14779 Slog.d(TAG, "Remembering install states:"); 14780 for (int userId : allUserHandles) { 14781 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 14782 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 14783 } 14784 } 14785 } 14786 14787 // Delete the updated package 14788 outInfo.isRemovedPackageSystemUpdate = true; 14789 if (outInfo.removedChildPackages != null) { 14790 final int childCount = (deletedPs.childPackageNames != null) 14791 ? deletedPs.childPackageNames.size() : 0; 14792 for (int i = 0; i < childCount; i++) { 14793 String childPackageName = deletedPs.childPackageNames.get(i); 14794 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 14795 .contains(childPackageName)) { 14796 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 14797 childPackageName); 14798 if (childInfo != null) { 14799 childInfo.isRemovedPackageSystemUpdate = true; 14800 } 14801 } 14802 } 14803 } 14804 14805 if (disabledPs.versionCode < deletedPs.versionCode) { 14806 // Delete data for downgrades 14807 flags &= ~PackageManager.DELETE_KEEP_DATA; 14808 } else { 14809 // Preserve data by setting flag 14810 flags |= PackageManager.DELETE_KEEP_DATA; 14811 } 14812 14813 boolean ret = deleteInstalledPackageLI(deletedPs, true, flags, allUserHandles, 14814 outInfo, writeSettings, disabledPs.pkg); 14815 if (!ret) { 14816 return false; 14817 } 14818 14819 // writer 14820 synchronized (mPackages) { 14821 // Reinstate the old system package 14822 enableSystemPackageLPw(disabledPs.pkg); 14823 // Remove any native libraries from the upgraded package. 14824 removeNativeBinariesLI(deletedPs); 14825 } 14826 14827 // Install the system package 14828 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 14829 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 14830 if (locationIsPrivileged(disabledPs.codePath)) { 14831 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 14832 } 14833 14834 final PackageParser.Package newPkg; 14835 try { 14836 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 14837 } catch (PackageManagerException e) { 14838 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 14839 + e.getMessage()); 14840 return false; 14841 } 14842 14843 prepareAppDataAfterInstall(newPkg); 14844 14845 // writer 14846 synchronized (mPackages) { 14847 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 14848 14849 // Propagate the permissions state as we do not want to drop on the floor 14850 // runtime permissions. The update permissions method below will take 14851 // care of removing obsolete permissions and grant install permissions. 14852 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 14853 updatePermissionsLPw(newPkg.packageName, newPkg, 14854 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 14855 14856 if (applyUserRestrictions) { 14857 if (DEBUG_REMOVE) { 14858 Slog.d(TAG, "Propagating install state across reinstall"); 14859 } 14860 for (int userId : allUserHandles) { 14861 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 14862 if (DEBUG_REMOVE) { 14863 Slog.d(TAG, " user " + userId + " => " + installed); 14864 } 14865 ps.setInstalled(installed, userId); 14866 14867 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 14868 } 14869 // Regardless of writeSettings we need to ensure that this restriction 14870 // state propagation is persisted 14871 mSettings.writeAllUsersPackageRestrictionsLPr(); 14872 } 14873 // can downgrade to reader here 14874 if (writeSettings) { 14875 mSettings.writeLPr(); 14876 } 14877 } 14878 return true; 14879 } 14880 14881 private boolean deleteInstalledPackageLI(PackageSetting ps, 14882 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 14883 PackageRemovedInfo outInfo, boolean writeSettings, 14884 PackageParser.Package replacingPackage) { 14885 synchronized (mPackages) { 14886 if (outInfo != null) { 14887 outInfo.uid = ps.appId; 14888 } 14889 14890 if (outInfo != null && outInfo.removedChildPackages != null) { 14891 final int childCount = (ps.childPackageNames != null) 14892 ? ps.childPackageNames.size() : 0; 14893 for (int i = 0; i < childCount; i++) { 14894 String childPackageName = ps.childPackageNames.get(i); 14895 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 14896 if (childPs == null) { 14897 return false; 14898 } 14899 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 14900 childPackageName); 14901 if (childInfo != null) { 14902 childInfo.uid = childPs.appId; 14903 } 14904 } 14905 } 14906 } 14907 14908 // Delete package data from internal structures and also remove data if flag is set 14909 removePackageDataLI(ps, allUserHandles, outInfo, flags, writeSettings); 14910 14911 // Delete the child packages data 14912 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14913 for (int i = 0; i < childCount; i++) { 14914 PackageSetting childPs; 14915 synchronized (mPackages) { 14916 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14917 } 14918 if (childPs != null) { 14919 PackageRemovedInfo childOutInfo = (outInfo != null 14920 && outInfo.removedChildPackages != null) 14921 ? outInfo.removedChildPackages.get(childPs.name) : null; 14922 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 14923 && (replacingPackage != null 14924 && !replacingPackage.hasChildPackage(childPs.name)) 14925 ? flags & ~DELETE_KEEP_DATA : flags; 14926 removePackageDataLI(childPs, allUserHandles, childOutInfo, 14927 deleteFlags, writeSettings); 14928 } 14929 } 14930 14931 // Delete application code and resources only for parent packages 14932 if (ps.parentPackageName == null) { 14933 if (deleteCodeAndResources && (outInfo != null)) { 14934 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 14935 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 14936 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 14937 } 14938 } 14939 14940 return true; 14941 } 14942 14943 @Override 14944 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 14945 int userId) { 14946 mContext.enforceCallingOrSelfPermission( 14947 android.Manifest.permission.DELETE_PACKAGES, null); 14948 synchronized (mPackages) { 14949 PackageSetting ps = mSettings.mPackages.get(packageName); 14950 if (ps == null) { 14951 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 14952 return false; 14953 } 14954 if (!ps.getInstalled(userId)) { 14955 // Can't block uninstall for an app that is not installed or enabled. 14956 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 14957 return false; 14958 } 14959 ps.setBlockUninstall(blockUninstall, userId); 14960 mSettings.writePackageRestrictionsLPr(userId); 14961 } 14962 return true; 14963 } 14964 14965 @Override 14966 public boolean getBlockUninstallForUser(String packageName, int userId) { 14967 synchronized (mPackages) { 14968 PackageSetting ps = mSettings.mPackages.get(packageName); 14969 if (ps == null) { 14970 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 14971 return false; 14972 } 14973 return ps.getBlockUninstall(userId); 14974 } 14975 } 14976 14977 @Override 14978 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 14979 int callingUid = Binder.getCallingUid(); 14980 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 14981 throw new SecurityException( 14982 "setRequiredForSystemUser can only be run by the system or root"); 14983 } 14984 synchronized (mPackages) { 14985 PackageSetting ps = mSettings.mPackages.get(packageName); 14986 if (ps == null) { 14987 Log.w(TAG, "Package doesn't exist: " + packageName); 14988 return false; 14989 } 14990 if (systemUserApp) { 14991 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 14992 } else { 14993 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 14994 } 14995 mSettings.writeLPr(); 14996 } 14997 return true; 14998 } 14999 15000 /* 15001 * This method handles package deletion in general 15002 */ 15003 private boolean deletePackageLI(String packageName, UserHandle user, 15004 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15005 PackageRemovedInfo outInfo, boolean writeSettings, 15006 PackageParser.Package replacingPackage) { 15007 if (packageName == null) { 15008 Slog.w(TAG, "Attempt to delete null packageName."); 15009 return false; 15010 } 15011 15012 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15013 15014 PackageSetting ps; 15015 15016 synchronized (mPackages) { 15017 ps = mSettings.mPackages.get(packageName); 15018 if (ps == null) { 15019 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15020 return false; 15021 } 15022 15023 if (ps.parentPackageName != null && (!isSystemApp(ps) 15024 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15025 if (DEBUG_REMOVE) { 15026 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15027 + ((user == null) ? UserHandle.USER_ALL : user)); 15028 } 15029 final int removedUserId = (user != null) ? user.getIdentifier() 15030 : UserHandle.USER_ALL; 15031 if (!clearPackageStateForUser(ps, removedUserId, outInfo)) { 15032 return false; 15033 } 15034 markPackageUninstalledForUserLPw(ps, user); 15035 scheduleWritePackageRestrictionsLocked(user); 15036 return true; 15037 } 15038 } 15039 15040 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15041 && user.getIdentifier() != UserHandle.USER_ALL)) { 15042 // The caller is asking that the package only be deleted for a single 15043 // user. To do this, we just mark its uninstalled state and delete 15044 // its data. If this is a system app, we only allow this to happen if 15045 // they have set the special DELETE_SYSTEM_APP which requests different 15046 // semantics than normal for uninstalling system apps. 15047 markPackageUninstalledForUserLPw(ps, user); 15048 15049 if (!isSystemApp(ps)) { 15050 // Do not uninstall the APK if an app should be cached 15051 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15052 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15053 // Other user still have this package installed, so all 15054 // we need to do is clear this user's data and save that 15055 // it is uninstalled. 15056 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15057 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 15058 return false; 15059 } 15060 scheduleWritePackageRestrictionsLocked(user); 15061 return true; 15062 } else { 15063 // We need to set it back to 'installed' so the uninstall 15064 // broadcasts will be sent correctly. 15065 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15066 ps.setInstalled(true, user.getIdentifier()); 15067 } 15068 } else { 15069 // This is a system app, so we assume that the 15070 // other users still have this package installed, so all 15071 // we need to do is clear this user's data and save that 15072 // it is uninstalled. 15073 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15074 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 15075 return false; 15076 } 15077 scheduleWritePackageRestrictionsLocked(user); 15078 return true; 15079 } 15080 } 15081 15082 // If we are deleting a composite package for all users, keep track 15083 // of result for each child. 15084 if (ps.childPackageNames != null && outInfo != null) { 15085 synchronized (mPackages) { 15086 final int childCount = ps.childPackageNames.size(); 15087 outInfo.removedChildPackages = new ArrayMap<>(childCount); 15088 for (int i = 0; i < childCount; i++) { 15089 String childPackageName = ps.childPackageNames.get(i); 15090 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 15091 childInfo.removedPackage = childPackageName; 15092 outInfo.removedChildPackages.put(childPackageName, childInfo); 15093 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15094 if (childPs != null) { 15095 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 15096 } 15097 } 15098 } 15099 } 15100 15101 boolean ret = false; 15102 if (isSystemApp(ps)) { 15103 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 15104 // When an updated system application is deleted we delete the existing resources 15105 // as well and fall back to existing code in system partition 15106 ret = deleteSystemPackageLI(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 15107 } else { 15108 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 15109 // Kill application pre-emptively especially for apps on sd. 15110 final boolean killApp = (flags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15111 if (killApp) { 15112 killApplication(packageName, ps.appId, "uninstall pkg"); 15113 } 15114 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, allUserHandles, 15115 outInfo, writeSettings, replacingPackage); 15116 } 15117 15118 // Take a note whether we deleted the package for all users 15119 if (outInfo != null) { 15120 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15121 if (outInfo.removedChildPackages != null) { 15122 synchronized (mPackages) { 15123 final int childCount = outInfo.removedChildPackages.size(); 15124 for (int i = 0; i < childCount; i++) { 15125 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 15126 if (childInfo != null) { 15127 childInfo.removedForAllUsers = mPackages.get( 15128 childInfo.removedPackage) == null; 15129 } 15130 } 15131 } 15132 } 15133 // If we uninstalled an update to a system app there may be some 15134 // child packages that appeared as they are declared in the system 15135 // app but were not declared in the update. 15136 if (isSystemApp(ps)) { 15137 synchronized (mPackages) { 15138 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 15139 final int childCount = (updatedPs.childPackageNames != null) 15140 ? updatedPs.childPackageNames.size() : 0; 15141 for (int i = 0; i < childCount; i++) { 15142 String childPackageName = updatedPs.childPackageNames.get(i); 15143 if (outInfo.removedChildPackages == null 15144 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 15145 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15146 if (childPs == null) { 15147 continue; 15148 } 15149 PackageInstalledInfo installRes = new PackageInstalledInfo(); 15150 installRes.name = childPackageName; 15151 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 15152 installRes.pkg = mPackages.get(childPackageName); 15153 installRes.uid = childPs.pkg.applicationInfo.uid; 15154 if (outInfo.appearedChildPackages == null) { 15155 outInfo.appearedChildPackages = new ArrayMap<>(); 15156 } 15157 outInfo.appearedChildPackages.put(childPackageName, installRes); 15158 } 15159 } 15160 } 15161 } 15162 } 15163 15164 return ret; 15165 } 15166 15167 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 15168 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 15169 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 15170 for (int nextUserId : userIds) { 15171 if (DEBUG_REMOVE) { 15172 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 15173 } 15174 ps.setUserState(nextUserId, COMPONENT_ENABLED_STATE_DEFAULT, 15175 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 15176 false /*hidden*/, false /*suspended*/, null, null, null, 15177 false /*blockUninstall*/, 15178 ps.readUserState(nextUserId).domainVerificationStatus, 0); 15179 } 15180 } 15181 15182 private boolean clearPackageStateForUser(PackageSetting ps, int userId, 15183 PackageRemovedInfo outInfo) { 15184 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 15185 : new int[] {userId}; 15186 for (int nextUserId : userIds) { 15187 if (DEBUG_REMOVE) { 15188 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 15189 + nextUserId); 15190 } 15191 final int flags = StorageManager.FLAG_STORAGE_CE| StorageManager.FLAG_STORAGE_DE; 15192 try { 15193 mInstaller.destroyAppData(ps.volumeUuid, ps.name, nextUserId, flags); 15194 } catch (InstallerException e) { 15195 Slog.w(TAG, "Couldn't remove cache files for package " + ps.name, e); 15196 return false; 15197 } 15198 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 15199 schedulePackageCleaning(ps.name, nextUserId, false); 15200 synchronized (mPackages) { 15201 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 15202 scheduleWritePackageRestrictionsLocked(nextUserId); 15203 } 15204 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 15205 } 15206 } 15207 15208 if (outInfo != null) { 15209 outInfo.removedPackage = ps.name; 15210 outInfo.removedAppId = ps.appId; 15211 outInfo.removedUsers = userIds; 15212 } 15213 15214 return true; 15215 } 15216 15217 private final class ClearStorageConnection implements ServiceConnection { 15218 IMediaContainerService mContainerService; 15219 15220 @Override 15221 public void onServiceConnected(ComponentName name, IBinder service) { 15222 synchronized (this) { 15223 mContainerService = IMediaContainerService.Stub.asInterface(service); 15224 notifyAll(); 15225 } 15226 } 15227 15228 @Override 15229 public void onServiceDisconnected(ComponentName name) { 15230 } 15231 } 15232 15233 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 15234 final boolean mounted; 15235 if (Environment.isExternalStorageEmulated()) { 15236 mounted = true; 15237 } else { 15238 final String status = Environment.getExternalStorageState(); 15239 15240 mounted = status.equals(Environment.MEDIA_MOUNTED) 15241 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 15242 } 15243 15244 if (!mounted) { 15245 return; 15246 } 15247 15248 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 15249 int[] users; 15250 if (userId == UserHandle.USER_ALL) { 15251 users = sUserManager.getUserIds(); 15252 } else { 15253 users = new int[] { userId }; 15254 } 15255 final ClearStorageConnection conn = new ClearStorageConnection(); 15256 if (mContext.bindServiceAsUser( 15257 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 15258 try { 15259 for (int curUser : users) { 15260 long timeout = SystemClock.uptimeMillis() + 5000; 15261 synchronized (conn) { 15262 long now = SystemClock.uptimeMillis(); 15263 while (conn.mContainerService == null && now < timeout) { 15264 try { 15265 conn.wait(timeout - now); 15266 } catch (InterruptedException e) { 15267 } 15268 } 15269 } 15270 if (conn.mContainerService == null) { 15271 return; 15272 } 15273 15274 final UserEnvironment userEnv = new UserEnvironment(curUser); 15275 clearDirectory(conn.mContainerService, 15276 userEnv.buildExternalStorageAppCacheDirs(packageName)); 15277 if (allData) { 15278 clearDirectory(conn.mContainerService, 15279 userEnv.buildExternalStorageAppDataDirs(packageName)); 15280 clearDirectory(conn.mContainerService, 15281 userEnv.buildExternalStorageAppMediaDirs(packageName)); 15282 } 15283 } 15284 } finally { 15285 mContext.unbindService(conn); 15286 } 15287 } 15288 } 15289 15290 @Override 15291 public void clearApplicationProfileData(String packageName) { 15292 enforceSystemOrRoot("Only the system can clear all profile data"); 15293 try { 15294 mInstaller.clearAppProfiles(packageName); 15295 } catch (InstallerException ex) { 15296 Log.e(TAG, "Could not clear profile data of package " + packageName); 15297 } 15298 } 15299 15300 @Override 15301 public void clearApplicationUserData(final String packageName, 15302 final IPackageDataObserver observer, final int userId) { 15303 mContext.enforceCallingOrSelfPermission( 15304 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 15305 15306 enforceCrossUserPermission(Binder.getCallingUid(), userId, 15307 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 15308 15309 final DevicePolicyManagerInternal dpmi = LocalServices 15310 .getService(DevicePolicyManagerInternal.class); 15311 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 15312 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 15313 } 15314 // Queue up an async operation since the package deletion may take a little while. 15315 mHandler.post(new Runnable() { 15316 public void run() { 15317 mHandler.removeCallbacks(this); 15318 final boolean succeeded; 15319 synchronized (mInstallLock) { 15320 succeeded = clearApplicationUserDataLI(packageName, userId); 15321 } 15322 clearExternalStorageDataSync(packageName, userId, true); 15323 if (succeeded) { 15324 // invoke DeviceStorageMonitor's update method to clear any notifications 15325 DeviceStorageMonitorInternal dsm = LocalServices 15326 .getService(DeviceStorageMonitorInternal.class); 15327 if (dsm != null) { 15328 dsm.checkMemory(); 15329 } 15330 } 15331 if(observer != null) { 15332 try { 15333 observer.onRemoveCompleted(packageName, succeeded); 15334 } catch (RemoteException e) { 15335 Log.i(TAG, "Observer no longer exists."); 15336 } 15337 } //end if observer 15338 } //end run 15339 }); 15340 } 15341 15342 private boolean clearApplicationUserDataLI(String packageName, int userId) { 15343 if (packageName == null) { 15344 Slog.w(TAG, "Attempt to delete null packageName."); 15345 return false; 15346 } 15347 15348 // Try finding details about the requested package 15349 PackageParser.Package pkg; 15350 synchronized (mPackages) { 15351 pkg = mPackages.get(packageName); 15352 if (pkg == null) { 15353 final PackageSetting ps = mSettings.mPackages.get(packageName); 15354 if (ps != null) { 15355 pkg = ps.pkg; 15356 } 15357 } 15358 15359 if (pkg == null) { 15360 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15361 return false; 15362 } 15363 15364 PackageSetting ps = (PackageSetting) pkg.mExtras; 15365 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15366 } 15367 15368 // Always delete data directories for package, even if we found no other 15369 // record of app. This helps users recover from UID mismatches without 15370 // resorting to a full data wipe. 15371 // TODO: triage flags as part of 26466827 15372 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15373 try { 15374 mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags); 15375 } catch (InstallerException e) { 15376 Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e); 15377 return false; 15378 } 15379 15380 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15381 removeKeystoreDataIfNeeded(userId, appId); 15382 15383 // Create a native library symlink only if we have native libraries 15384 // and if the native libraries are 32 bit libraries. We do not provide 15385 // this symlink for 64 bit libraries. 15386 if (pkg.applicationInfo.primaryCpuAbi != null && 15387 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 15388 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 15389 try { 15390 mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 15391 nativeLibPath, userId); 15392 } catch (InstallerException e) { 15393 Slog.w(TAG, "Failed linking native library dir", e); 15394 return false; 15395 } 15396 } 15397 15398 return true; 15399 } 15400 15401 /** 15402 * Reverts user permission state changes (permissions and flags) in 15403 * all packages for a given user. 15404 * 15405 * @param userId The device user for which to do a reset. 15406 */ 15407 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 15408 final int packageCount = mPackages.size(); 15409 for (int i = 0; i < packageCount; i++) { 15410 PackageParser.Package pkg = mPackages.valueAt(i); 15411 PackageSetting ps = (PackageSetting) pkg.mExtras; 15412 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15413 } 15414 } 15415 15416 /** 15417 * Reverts user permission state changes (permissions and flags). 15418 * 15419 * @param ps The package for which to reset. 15420 * @param userId The device user for which to do a reset. 15421 */ 15422 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 15423 final PackageSetting ps, final int userId) { 15424 if (ps.pkg == null) { 15425 return; 15426 } 15427 15428 // These are flags that can change base on user actions. 15429 final int userSettableMask = FLAG_PERMISSION_USER_SET 15430 | FLAG_PERMISSION_USER_FIXED 15431 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 15432 | FLAG_PERMISSION_REVIEW_REQUIRED; 15433 15434 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 15435 | FLAG_PERMISSION_POLICY_FIXED; 15436 15437 boolean writeInstallPermissions = false; 15438 boolean writeRuntimePermissions = false; 15439 15440 final int permissionCount = ps.pkg.requestedPermissions.size(); 15441 for (int i = 0; i < permissionCount; i++) { 15442 String permission = ps.pkg.requestedPermissions.get(i); 15443 15444 BasePermission bp = mSettings.mPermissions.get(permission); 15445 if (bp == null) { 15446 continue; 15447 } 15448 15449 // If shared user we just reset the state to which only this app contributed. 15450 if (ps.sharedUser != null) { 15451 boolean used = false; 15452 final int packageCount = ps.sharedUser.packages.size(); 15453 for (int j = 0; j < packageCount; j++) { 15454 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 15455 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 15456 && pkg.pkg.requestedPermissions.contains(permission)) { 15457 used = true; 15458 break; 15459 } 15460 } 15461 if (used) { 15462 continue; 15463 } 15464 } 15465 15466 PermissionsState permissionsState = ps.getPermissionsState(); 15467 15468 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 15469 15470 // Always clear the user settable flags. 15471 final boolean hasInstallState = permissionsState.getInstallPermissionState( 15472 bp.name) != null; 15473 // If permission review is enabled and this is a legacy app, mark the 15474 // permission as requiring a review as this is the initial state. 15475 int flags = 0; 15476 if (Build.PERMISSIONS_REVIEW_REQUIRED 15477 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 15478 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 15479 } 15480 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 15481 if (hasInstallState) { 15482 writeInstallPermissions = true; 15483 } else { 15484 writeRuntimePermissions = true; 15485 } 15486 } 15487 15488 // Below is only runtime permission handling. 15489 if (!bp.isRuntime()) { 15490 continue; 15491 } 15492 15493 // Never clobber system or policy. 15494 if ((oldFlags & policyOrSystemFlags) != 0) { 15495 continue; 15496 } 15497 15498 // If this permission was granted by default, make sure it is. 15499 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 15500 if (permissionsState.grantRuntimePermission(bp, userId) 15501 != PERMISSION_OPERATION_FAILURE) { 15502 writeRuntimePermissions = true; 15503 } 15504 // If permission review is enabled the permissions for a legacy apps 15505 // are represented as constantly granted runtime ones, so don't revoke. 15506 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 15507 // Otherwise, reset the permission. 15508 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 15509 switch (revokeResult) { 15510 case PERMISSION_OPERATION_SUCCESS: { 15511 writeRuntimePermissions = true; 15512 } break; 15513 15514 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 15515 writeRuntimePermissions = true; 15516 final int appId = ps.appId; 15517 mHandler.post(new Runnable() { 15518 @Override 15519 public void run() { 15520 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 15521 } 15522 }); 15523 } break; 15524 } 15525 } 15526 } 15527 15528 // Synchronously write as we are taking permissions away. 15529 if (writeRuntimePermissions) { 15530 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 15531 } 15532 15533 // Synchronously write as we are taking permissions away. 15534 if (writeInstallPermissions) { 15535 mSettings.writeLPr(); 15536 } 15537 } 15538 15539 /** 15540 * Remove entries from the keystore daemon. Will only remove it if the 15541 * {@code appId} is valid. 15542 */ 15543 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 15544 if (appId < 0) { 15545 return; 15546 } 15547 15548 final KeyStore keyStore = KeyStore.getInstance(); 15549 if (keyStore != null) { 15550 if (userId == UserHandle.USER_ALL) { 15551 for (final int individual : sUserManager.getUserIds()) { 15552 keyStore.clearUid(UserHandle.getUid(individual, appId)); 15553 } 15554 } else { 15555 keyStore.clearUid(UserHandle.getUid(userId, appId)); 15556 } 15557 } else { 15558 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 15559 } 15560 } 15561 15562 @Override 15563 public void deleteApplicationCacheFiles(final String packageName, 15564 final IPackageDataObserver observer) { 15565 mContext.enforceCallingOrSelfPermission( 15566 android.Manifest.permission.DELETE_CACHE_FILES, null); 15567 // Queue up an async operation since the package deletion may take a little while. 15568 final int userId = UserHandle.getCallingUserId(); 15569 mHandler.post(new Runnable() { 15570 public void run() { 15571 mHandler.removeCallbacks(this); 15572 final boolean succeded; 15573 synchronized (mInstallLock) { 15574 succeded = deleteApplicationCacheFilesLI(packageName, userId); 15575 } 15576 clearExternalStorageDataSync(packageName, userId, false); 15577 if (observer != null) { 15578 try { 15579 observer.onRemoveCompleted(packageName, succeded); 15580 } catch (RemoteException e) { 15581 Log.i(TAG, "Observer no longer exists."); 15582 } 15583 } //end if observer 15584 } //end run 15585 }); 15586 } 15587 15588 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 15589 if (packageName == null) { 15590 Slog.w(TAG, "Attempt to delete null packageName."); 15591 return false; 15592 } 15593 PackageParser.Package p; 15594 synchronized (mPackages) { 15595 p = mPackages.get(packageName); 15596 } 15597 if (p == null) { 15598 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 15599 return false; 15600 } 15601 final ApplicationInfo applicationInfo = p.applicationInfo; 15602 if (applicationInfo == null) { 15603 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 15604 return false; 15605 } 15606 // TODO: triage flags as part of 26466827 15607 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15608 try { 15609 mInstaller.clearAppData(p.volumeUuid, packageName, userId, 15610 flags | Installer.FLAG_CLEAR_CACHE_ONLY); 15611 } catch (InstallerException e) { 15612 Slog.w(TAG, "Couldn't remove cache files for package " 15613 + packageName + " u" + userId, e); 15614 return false; 15615 } 15616 return true; 15617 } 15618 15619 @Override 15620 public void getPackageSizeInfo(final String packageName, int userHandle, 15621 final IPackageStatsObserver observer) { 15622 mContext.enforceCallingOrSelfPermission( 15623 android.Manifest.permission.GET_PACKAGE_SIZE, null); 15624 if (packageName == null) { 15625 throw new IllegalArgumentException("Attempt to get size of null packageName"); 15626 } 15627 15628 PackageStats stats = new PackageStats(packageName, userHandle); 15629 15630 /* 15631 * Queue up an async operation since the package measurement may take a 15632 * little while. 15633 */ 15634 Message msg = mHandler.obtainMessage(INIT_COPY); 15635 msg.obj = new MeasureParams(stats, observer); 15636 mHandler.sendMessage(msg); 15637 } 15638 15639 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 15640 PackageStats pStats) { 15641 if (packageName == null) { 15642 Slog.w(TAG, "Attempt to get size of null packageName."); 15643 return false; 15644 } 15645 PackageParser.Package p; 15646 boolean dataOnly = false; 15647 String libDirRoot = null; 15648 String asecPath = null; 15649 PackageSetting ps = null; 15650 synchronized (mPackages) { 15651 p = mPackages.get(packageName); 15652 ps = mSettings.mPackages.get(packageName); 15653 if(p == null) { 15654 dataOnly = true; 15655 if((ps == null) || (ps.pkg == null)) { 15656 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 15657 return false; 15658 } 15659 p = ps.pkg; 15660 } 15661 if (ps != null) { 15662 libDirRoot = ps.legacyNativeLibraryPathString; 15663 } 15664 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 15665 final long token = Binder.clearCallingIdentity(); 15666 try { 15667 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 15668 if (secureContainerId != null) { 15669 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 15670 } 15671 } finally { 15672 Binder.restoreCallingIdentity(token); 15673 } 15674 } 15675 } 15676 String publicSrcDir = null; 15677 if(!dataOnly) { 15678 final ApplicationInfo applicationInfo = p.applicationInfo; 15679 if (applicationInfo == null) { 15680 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 15681 return false; 15682 } 15683 if (p.isForwardLocked()) { 15684 publicSrcDir = applicationInfo.getBaseResourcePath(); 15685 } 15686 } 15687 // TODO: extend to measure size of split APKs 15688 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 15689 // not just the first level. 15690 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 15691 // just the primary. 15692 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 15693 15694 String apkPath; 15695 File packageDir = new File(p.codePath); 15696 15697 if (packageDir.isDirectory() && p.canHaveOatDir()) { 15698 apkPath = packageDir.getAbsolutePath(); 15699 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 15700 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 15701 libDirRoot = null; 15702 } 15703 } else { 15704 apkPath = p.baseCodePath; 15705 } 15706 15707 // TODO: triage flags as part of 26466827 15708 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15709 try { 15710 mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath, 15711 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 15712 } catch (InstallerException e) { 15713 return false; 15714 } 15715 15716 // Fix-up for forward-locked applications in ASEC containers. 15717 if (!isExternal(p)) { 15718 pStats.codeSize += pStats.externalCodeSize; 15719 pStats.externalCodeSize = 0L; 15720 } 15721 15722 return true; 15723 } 15724 15725 private int getUidTargetSdkVersionLockedLPr(int uid) { 15726 Object obj = mSettings.getUserIdLPr(uid); 15727 if (obj instanceof SharedUserSetting) { 15728 final SharedUserSetting sus = (SharedUserSetting) obj; 15729 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 15730 final Iterator<PackageSetting> it = sus.packages.iterator(); 15731 while (it.hasNext()) { 15732 final PackageSetting ps = it.next(); 15733 if (ps.pkg != null) { 15734 int v = ps.pkg.applicationInfo.targetSdkVersion; 15735 if (v < vers) vers = v; 15736 } 15737 } 15738 return vers; 15739 } else if (obj instanceof PackageSetting) { 15740 final PackageSetting ps = (PackageSetting) obj; 15741 if (ps.pkg != null) { 15742 return ps.pkg.applicationInfo.targetSdkVersion; 15743 } 15744 } 15745 return Build.VERSION_CODES.CUR_DEVELOPMENT; 15746 } 15747 15748 @Override 15749 public void addPreferredActivity(IntentFilter filter, int match, 15750 ComponentName[] set, ComponentName activity, int userId) { 15751 addPreferredActivityInternal(filter, match, set, activity, true, userId, 15752 "Adding preferred"); 15753 } 15754 15755 private void addPreferredActivityInternal(IntentFilter filter, int match, 15756 ComponentName[] set, ComponentName activity, boolean always, int userId, 15757 String opname) { 15758 // writer 15759 int callingUid = Binder.getCallingUid(); 15760 enforceCrossUserPermission(callingUid, userId, 15761 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 15762 if (filter.countActions() == 0) { 15763 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 15764 return; 15765 } 15766 synchronized (mPackages) { 15767 if (mContext.checkCallingOrSelfPermission( 15768 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15769 != PackageManager.PERMISSION_GRANTED) { 15770 if (getUidTargetSdkVersionLockedLPr(callingUid) 15771 < Build.VERSION_CODES.FROYO) { 15772 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 15773 + callingUid); 15774 return; 15775 } 15776 mContext.enforceCallingOrSelfPermission( 15777 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15778 } 15779 15780 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 15781 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 15782 + userId + ":"); 15783 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15784 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 15785 scheduleWritePackageRestrictionsLocked(userId); 15786 } 15787 } 15788 15789 @Override 15790 public void replacePreferredActivity(IntentFilter filter, int match, 15791 ComponentName[] set, ComponentName activity, int userId) { 15792 if (filter.countActions() != 1) { 15793 throw new IllegalArgumentException( 15794 "replacePreferredActivity expects filter to have only 1 action."); 15795 } 15796 if (filter.countDataAuthorities() != 0 15797 || filter.countDataPaths() != 0 15798 || filter.countDataSchemes() > 1 15799 || filter.countDataTypes() != 0) { 15800 throw new IllegalArgumentException( 15801 "replacePreferredActivity expects filter to have no data authorities, " + 15802 "paths, or types; and at most one scheme."); 15803 } 15804 15805 final int callingUid = Binder.getCallingUid(); 15806 enforceCrossUserPermission(callingUid, userId, 15807 true /* requireFullPermission */, false /* checkShell */, 15808 "replace preferred activity"); 15809 synchronized (mPackages) { 15810 if (mContext.checkCallingOrSelfPermission( 15811 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15812 != PackageManager.PERMISSION_GRANTED) { 15813 if (getUidTargetSdkVersionLockedLPr(callingUid) 15814 < Build.VERSION_CODES.FROYO) { 15815 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 15816 + Binder.getCallingUid()); 15817 return; 15818 } 15819 mContext.enforceCallingOrSelfPermission( 15820 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15821 } 15822 15823 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 15824 if (pir != null) { 15825 // Get all of the existing entries that exactly match this filter. 15826 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 15827 if (existing != null && existing.size() == 1) { 15828 PreferredActivity cur = existing.get(0); 15829 if (DEBUG_PREFERRED) { 15830 Slog.i(TAG, "Checking replace of preferred:"); 15831 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15832 if (!cur.mPref.mAlways) { 15833 Slog.i(TAG, " -- CUR; not mAlways!"); 15834 } else { 15835 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 15836 Slog.i(TAG, " -- CUR: mSet=" 15837 + Arrays.toString(cur.mPref.mSetComponents)); 15838 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 15839 Slog.i(TAG, " -- NEW: mMatch=" 15840 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 15841 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 15842 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 15843 } 15844 } 15845 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 15846 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 15847 && cur.mPref.sameSet(set)) { 15848 // Setting the preferred activity to what it happens to be already 15849 if (DEBUG_PREFERRED) { 15850 Slog.i(TAG, "Replacing with same preferred activity " 15851 + cur.mPref.mShortComponent + " for user " 15852 + userId + ":"); 15853 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15854 } 15855 return; 15856 } 15857 } 15858 15859 if (existing != null) { 15860 if (DEBUG_PREFERRED) { 15861 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 15862 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15863 } 15864 for (int i = 0; i < existing.size(); i++) { 15865 PreferredActivity pa = existing.get(i); 15866 if (DEBUG_PREFERRED) { 15867 Slog.i(TAG, "Removing existing preferred activity " 15868 + pa.mPref.mComponent + ":"); 15869 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 15870 } 15871 pir.removeFilter(pa); 15872 } 15873 } 15874 } 15875 addPreferredActivityInternal(filter, match, set, activity, true, userId, 15876 "Replacing preferred"); 15877 } 15878 } 15879 15880 @Override 15881 public void clearPackagePreferredActivities(String packageName) { 15882 final int uid = Binder.getCallingUid(); 15883 // writer 15884 synchronized (mPackages) { 15885 PackageParser.Package pkg = mPackages.get(packageName); 15886 if (pkg == null || pkg.applicationInfo.uid != uid) { 15887 if (mContext.checkCallingOrSelfPermission( 15888 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15889 != PackageManager.PERMISSION_GRANTED) { 15890 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 15891 < Build.VERSION_CODES.FROYO) { 15892 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 15893 + Binder.getCallingUid()); 15894 return; 15895 } 15896 mContext.enforceCallingOrSelfPermission( 15897 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15898 } 15899 } 15900 15901 int user = UserHandle.getCallingUserId(); 15902 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 15903 scheduleWritePackageRestrictionsLocked(user); 15904 } 15905 } 15906 } 15907 15908 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15909 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 15910 ArrayList<PreferredActivity> removed = null; 15911 boolean changed = false; 15912 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15913 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 15914 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15915 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 15916 continue; 15917 } 15918 Iterator<PreferredActivity> it = pir.filterIterator(); 15919 while (it.hasNext()) { 15920 PreferredActivity pa = it.next(); 15921 // Mark entry for removal only if it matches the package name 15922 // and the entry is of type "always". 15923 if (packageName == null || 15924 (pa.mPref.mComponent.getPackageName().equals(packageName) 15925 && pa.mPref.mAlways)) { 15926 if (removed == null) { 15927 removed = new ArrayList<PreferredActivity>(); 15928 } 15929 removed.add(pa); 15930 } 15931 } 15932 if (removed != null) { 15933 for (int j=0; j<removed.size(); j++) { 15934 PreferredActivity pa = removed.get(j); 15935 pir.removeFilter(pa); 15936 } 15937 changed = true; 15938 } 15939 } 15940 return changed; 15941 } 15942 15943 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15944 private void clearIntentFilterVerificationsLPw(int userId) { 15945 final int packageCount = mPackages.size(); 15946 for (int i = 0; i < packageCount; i++) { 15947 PackageParser.Package pkg = mPackages.valueAt(i); 15948 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 15949 } 15950 } 15951 15952 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15953 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 15954 if (userId == UserHandle.USER_ALL) { 15955 if (mSettings.removeIntentFilterVerificationLPw(packageName, 15956 sUserManager.getUserIds())) { 15957 for (int oneUserId : sUserManager.getUserIds()) { 15958 scheduleWritePackageRestrictionsLocked(oneUserId); 15959 } 15960 } 15961 } else { 15962 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 15963 scheduleWritePackageRestrictionsLocked(userId); 15964 } 15965 } 15966 } 15967 15968 void clearDefaultBrowserIfNeeded(String packageName) { 15969 for (int oneUserId : sUserManager.getUserIds()) { 15970 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 15971 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 15972 if (packageName.equals(defaultBrowserPackageName)) { 15973 setDefaultBrowserPackageName(null, oneUserId); 15974 } 15975 } 15976 } 15977 15978 @Override 15979 public void resetApplicationPreferences(int userId) { 15980 mContext.enforceCallingOrSelfPermission( 15981 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15982 // writer 15983 synchronized (mPackages) { 15984 final long identity = Binder.clearCallingIdentity(); 15985 try { 15986 clearPackagePreferredActivitiesLPw(null, userId); 15987 mSettings.applyDefaultPreferredAppsLPw(this, userId); 15988 // TODO: We have to reset the default SMS and Phone. This requires 15989 // significant refactoring to keep all default apps in the package 15990 // manager (cleaner but more work) or have the services provide 15991 // callbacks to the package manager to request a default app reset. 15992 applyFactoryDefaultBrowserLPw(userId); 15993 clearIntentFilterVerificationsLPw(userId); 15994 primeDomainVerificationsLPw(userId); 15995 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 15996 scheduleWritePackageRestrictionsLocked(userId); 15997 } finally { 15998 Binder.restoreCallingIdentity(identity); 15999 } 16000 } 16001 } 16002 16003 @Override 16004 public int getPreferredActivities(List<IntentFilter> outFilters, 16005 List<ComponentName> outActivities, String packageName) { 16006 16007 int num = 0; 16008 final int userId = UserHandle.getCallingUserId(); 16009 // reader 16010 synchronized (mPackages) { 16011 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16012 if (pir != null) { 16013 final Iterator<PreferredActivity> it = pir.filterIterator(); 16014 while (it.hasNext()) { 16015 final PreferredActivity pa = it.next(); 16016 if (packageName == null 16017 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16018 && pa.mPref.mAlways)) { 16019 if (outFilters != null) { 16020 outFilters.add(new IntentFilter(pa)); 16021 } 16022 if (outActivities != null) { 16023 outActivities.add(pa.mPref.mComponent); 16024 } 16025 } 16026 } 16027 } 16028 } 16029 16030 return num; 16031 } 16032 16033 @Override 16034 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16035 int userId) { 16036 int callingUid = Binder.getCallingUid(); 16037 if (callingUid != Process.SYSTEM_UID) { 16038 throw new SecurityException( 16039 "addPersistentPreferredActivity can only be run by the system"); 16040 } 16041 if (filter.countActions() == 0) { 16042 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16043 return; 16044 } 16045 synchronized (mPackages) { 16046 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16047 ":"); 16048 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16049 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16050 new PersistentPreferredActivity(filter, activity)); 16051 scheduleWritePackageRestrictionsLocked(userId); 16052 } 16053 } 16054 16055 @Override 16056 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16057 int callingUid = Binder.getCallingUid(); 16058 if (callingUid != Process.SYSTEM_UID) { 16059 throw new SecurityException( 16060 "clearPackagePersistentPreferredActivities can only be run by the system"); 16061 } 16062 ArrayList<PersistentPreferredActivity> removed = null; 16063 boolean changed = false; 16064 synchronized (mPackages) { 16065 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16066 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16067 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16068 .valueAt(i); 16069 if (userId != thisUserId) { 16070 continue; 16071 } 16072 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16073 while (it.hasNext()) { 16074 PersistentPreferredActivity ppa = it.next(); 16075 // Mark entry for removal only if it matches the package name. 16076 if (ppa.mComponent.getPackageName().equals(packageName)) { 16077 if (removed == null) { 16078 removed = new ArrayList<PersistentPreferredActivity>(); 16079 } 16080 removed.add(ppa); 16081 } 16082 } 16083 if (removed != null) { 16084 for (int j=0; j<removed.size(); j++) { 16085 PersistentPreferredActivity ppa = removed.get(j); 16086 ppir.removeFilter(ppa); 16087 } 16088 changed = true; 16089 } 16090 } 16091 16092 if (changed) { 16093 scheduleWritePackageRestrictionsLocked(userId); 16094 } 16095 } 16096 } 16097 16098 /** 16099 * Common machinery for picking apart a restored XML blob and passing 16100 * it to a caller-supplied functor to be applied to the running system. 16101 */ 16102 private void restoreFromXml(XmlPullParser parser, int userId, 16103 String expectedStartTag, BlobXmlRestorer functor) 16104 throws IOException, XmlPullParserException { 16105 int type; 16106 while ((type = parser.next()) != XmlPullParser.START_TAG 16107 && type != XmlPullParser.END_DOCUMENT) { 16108 } 16109 if (type != XmlPullParser.START_TAG) { 16110 // oops didn't find a start tag?! 16111 if (DEBUG_BACKUP) { 16112 Slog.e(TAG, "Didn't find start tag during restore"); 16113 } 16114 return; 16115 } 16116Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16117 // this is supposed to be TAG_PREFERRED_BACKUP 16118 if (!expectedStartTag.equals(parser.getName())) { 16119 if (DEBUG_BACKUP) { 16120 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16121 } 16122 return; 16123 } 16124 16125 // skip interfering stuff, then we're aligned with the backing implementation 16126 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16127Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16128 functor.apply(parser, userId); 16129 } 16130 16131 private interface BlobXmlRestorer { 16132 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16133 } 16134 16135 /** 16136 * Non-Binder method, support for the backup/restore mechanism: write the 16137 * full set of preferred activities in its canonical XML format. Returns the 16138 * XML output as a byte array, or null if there is none. 16139 */ 16140 @Override 16141 public byte[] getPreferredActivityBackup(int userId) { 16142 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16143 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16144 } 16145 16146 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16147 try { 16148 final XmlSerializer serializer = new FastXmlSerializer(); 16149 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16150 serializer.startDocument(null, true); 16151 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16152 16153 synchronized (mPackages) { 16154 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16155 } 16156 16157 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16158 serializer.endDocument(); 16159 serializer.flush(); 16160 } catch (Exception e) { 16161 if (DEBUG_BACKUP) { 16162 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16163 } 16164 return null; 16165 } 16166 16167 return dataStream.toByteArray(); 16168 } 16169 16170 @Override 16171 public void restorePreferredActivities(byte[] backup, int userId) { 16172 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16173 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16174 } 16175 16176 try { 16177 final XmlPullParser parser = Xml.newPullParser(); 16178 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16179 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16180 new BlobXmlRestorer() { 16181 @Override 16182 public void apply(XmlPullParser parser, int userId) 16183 throws XmlPullParserException, IOException { 16184 synchronized (mPackages) { 16185 mSettings.readPreferredActivitiesLPw(parser, userId); 16186 } 16187 } 16188 } ); 16189 } catch (Exception e) { 16190 if (DEBUG_BACKUP) { 16191 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16192 } 16193 } 16194 } 16195 16196 /** 16197 * Non-Binder method, support for the backup/restore mechanism: write the 16198 * default browser (etc) settings in its canonical XML format. Returns the default 16199 * browser XML representation as a byte array, or null if there is none. 16200 */ 16201 @Override 16202 public byte[] getDefaultAppsBackup(int userId) { 16203 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16204 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 16205 } 16206 16207 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16208 try { 16209 final XmlSerializer serializer = new FastXmlSerializer(); 16210 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16211 serializer.startDocument(null, true); 16212 serializer.startTag(null, TAG_DEFAULT_APPS); 16213 16214 synchronized (mPackages) { 16215 mSettings.writeDefaultAppsLPr(serializer, userId); 16216 } 16217 16218 serializer.endTag(null, TAG_DEFAULT_APPS); 16219 serializer.endDocument(); 16220 serializer.flush(); 16221 } catch (Exception e) { 16222 if (DEBUG_BACKUP) { 16223 Slog.e(TAG, "Unable to write default apps for backup", e); 16224 } 16225 return null; 16226 } 16227 16228 return dataStream.toByteArray(); 16229 } 16230 16231 @Override 16232 public void restoreDefaultApps(byte[] backup, int userId) { 16233 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16234 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16235 } 16236 16237 try { 16238 final XmlPullParser parser = Xml.newPullParser(); 16239 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16240 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16241 new BlobXmlRestorer() { 16242 @Override 16243 public void apply(XmlPullParser parser, int userId) 16244 throws XmlPullParserException, IOException { 16245 synchronized (mPackages) { 16246 mSettings.readDefaultAppsLPw(parser, userId); 16247 } 16248 } 16249 } ); 16250 } catch (Exception e) { 16251 if (DEBUG_BACKUP) { 16252 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16253 } 16254 } 16255 } 16256 16257 @Override 16258 public byte[] getIntentFilterVerificationBackup(int userId) { 16259 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16260 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 16261 } 16262 16263 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16264 try { 16265 final XmlSerializer serializer = new FastXmlSerializer(); 16266 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16267 serializer.startDocument(null, true); 16268 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 16269 16270 synchronized (mPackages) { 16271 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 16272 } 16273 16274 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 16275 serializer.endDocument(); 16276 serializer.flush(); 16277 } catch (Exception e) { 16278 if (DEBUG_BACKUP) { 16279 Slog.e(TAG, "Unable to write default apps for backup", e); 16280 } 16281 return null; 16282 } 16283 16284 return dataStream.toByteArray(); 16285 } 16286 16287 @Override 16288 public void restoreIntentFilterVerification(byte[] backup, int userId) { 16289 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16290 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16291 } 16292 16293 try { 16294 final XmlPullParser parser = Xml.newPullParser(); 16295 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16296 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 16297 new BlobXmlRestorer() { 16298 @Override 16299 public void apply(XmlPullParser parser, int userId) 16300 throws XmlPullParserException, IOException { 16301 synchronized (mPackages) { 16302 mSettings.readAllDomainVerificationsLPr(parser, userId); 16303 mSettings.writeLPr(); 16304 } 16305 } 16306 } ); 16307 } catch (Exception e) { 16308 if (DEBUG_BACKUP) { 16309 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16310 } 16311 } 16312 } 16313 16314 @Override 16315 public byte[] getPermissionGrantBackup(int userId) { 16316 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16317 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 16318 } 16319 16320 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16321 try { 16322 final XmlSerializer serializer = new FastXmlSerializer(); 16323 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16324 serializer.startDocument(null, true); 16325 serializer.startTag(null, TAG_PERMISSION_BACKUP); 16326 16327 synchronized (mPackages) { 16328 serializeRuntimePermissionGrantsLPr(serializer, userId); 16329 } 16330 16331 serializer.endTag(null, TAG_PERMISSION_BACKUP); 16332 serializer.endDocument(); 16333 serializer.flush(); 16334 } catch (Exception e) { 16335 if (DEBUG_BACKUP) { 16336 Slog.e(TAG, "Unable to write default apps for backup", e); 16337 } 16338 return null; 16339 } 16340 16341 return dataStream.toByteArray(); 16342 } 16343 16344 @Override 16345 public void restorePermissionGrants(byte[] backup, int userId) { 16346 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16347 throw new SecurityException("Only the system may call restorePermissionGrants()"); 16348 } 16349 16350 try { 16351 final XmlPullParser parser = Xml.newPullParser(); 16352 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16353 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 16354 new BlobXmlRestorer() { 16355 @Override 16356 public void apply(XmlPullParser parser, int userId) 16357 throws XmlPullParserException, IOException { 16358 synchronized (mPackages) { 16359 processRestoredPermissionGrantsLPr(parser, userId); 16360 } 16361 } 16362 } ); 16363 } catch (Exception e) { 16364 if (DEBUG_BACKUP) { 16365 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16366 } 16367 } 16368 } 16369 16370 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 16371 throws IOException { 16372 serializer.startTag(null, TAG_ALL_GRANTS); 16373 16374 final int N = mSettings.mPackages.size(); 16375 for (int i = 0; i < N; i++) { 16376 final PackageSetting ps = mSettings.mPackages.valueAt(i); 16377 boolean pkgGrantsKnown = false; 16378 16379 PermissionsState packagePerms = ps.getPermissionsState(); 16380 16381 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 16382 final int grantFlags = state.getFlags(); 16383 // only look at grants that are not system/policy fixed 16384 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 16385 final boolean isGranted = state.isGranted(); 16386 // And only back up the user-twiddled state bits 16387 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 16388 final String packageName = mSettings.mPackages.keyAt(i); 16389 if (!pkgGrantsKnown) { 16390 serializer.startTag(null, TAG_GRANT); 16391 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 16392 pkgGrantsKnown = true; 16393 } 16394 16395 final boolean userSet = 16396 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 16397 final boolean userFixed = 16398 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 16399 final boolean revoke = 16400 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 16401 16402 serializer.startTag(null, TAG_PERMISSION); 16403 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 16404 if (isGranted) { 16405 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 16406 } 16407 if (userSet) { 16408 serializer.attribute(null, ATTR_USER_SET, "true"); 16409 } 16410 if (userFixed) { 16411 serializer.attribute(null, ATTR_USER_FIXED, "true"); 16412 } 16413 if (revoke) { 16414 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 16415 } 16416 serializer.endTag(null, TAG_PERMISSION); 16417 } 16418 } 16419 } 16420 16421 if (pkgGrantsKnown) { 16422 serializer.endTag(null, TAG_GRANT); 16423 } 16424 } 16425 16426 serializer.endTag(null, TAG_ALL_GRANTS); 16427 } 16428 16429 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 16430 throws XmlPullParserException, IOException { 16431 String pkgName = null; 16432 int outerDepth = parser.getDepth(); 16433 int type; 16434 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 16435 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 16436 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 16437 continue; 16438 } 16439 16440 final String tagName = parser.getName(); 16441 if (tagName.equals(TAG_GRANT)) { 16442 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 16443 if (DEBUG_BACKUP) { 16444 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 16445 } 16446 } else if (tagName.equals(TAG_PERMISSION)) { 16447 16448 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 16449 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 16450 16451 int newFlagSet = 0; 16452 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 16453 newFlagSet |= FLAG_PERMISSION_USER_SET; 16454 } 16455 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 16456 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 16457 } 16458 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 16459 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 16460 } 16461 if (DEBUG_BACKUP) { 16462 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 16463 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 16464 } 16465 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16466 if (ps != null) { 16467 // Already installed so we apply the grant immediately 16468 if (DEBUG_BACKUP) { 16469 Slog.v(TAG, " + already installed; applying"); 16470 } 16471 PermissionsState perms = ps.getPermissionsState(); 16472 BasePermission bp = mSettings.mPermissions.get(permName); 16473 if (bp != null) { 16474 if (isGranted) { 16475 perms.grantRuntimePermission(bp, userId); 16476 } 16477 if (newFlagSet != 0) { 16478 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 16479 } 16480 } 16481 } else { 16482 // Need to wait for post-restore install to apply the grant 16483 if (DEBUG_BACKUP) { 16484 Slog.v(TAG, " - not yet installed; saving for later"); 16485 } 16486 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 16487 isGranted, newFlagSet, userId); 16488 } 16489 } else { 16490 PackageManagerService.reportSettingsProblem(Log.WARN, 16491 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 16492 XmlUtils.skipCurrentTag(parser); 16493 } 16494 } 16495 16496 scheduleWriteSettingsLocked(); 16497 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16498 } 16499 16500 @Override 16501 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 16502 int sourceUserId, int targetUserId, int flags) { 16503 mContext.enforceCallingOrSelfPermission( 16504 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16505 int callingUid = Binder.getCallingUid(); 16506 enforceOwnerRights(ownerPackage, callingUid); 16507 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16508 if (intentFilter.countActions() == 0) { 16509 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 16510 return; 16511 } 16512 synchronized (mPackages) { 16513 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 16514 ownerPackage, targetUserId, flags); 16515 CrossProfileIntentResolver resolver = 16516 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16517 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 16518 // We have all those whose filter is equal. Now checking if the rest is equal as well. 16519 if (existing != null) { 16520 int size = existing.size(); 16521 for (int i = 0; i < size; i++) { 16522 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 16523 return; 16524 } 16525 } 16526 } 16527 resolver.addFilter(newFilter); 16528 scheduleWritePackageRestrictionsLocked(sourceUserId); 16529 } 16530 } 16531 16532 @Override 16533 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 16534 mContext.enforceCallingOrSelfPermission( 16535 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16536 int callingUid = Binder.getCallingUid(); 16537 enforceOwnerRights(ownerPackage, callingUid); 16538 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16539 synchronized (mPackages) { 16540 CrossProfileIntentResolver resolver = 16541 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16542 ArraySet<CrossProfileIntentFilter> set = 16543 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 16544 for (CrossProfileIntentFilter filter : set) { 16545 if (filter.getOwnerPackage().equals(ownerPackage)) { 16546 resolver.removeFilter(filter); 16547 } 16548 } 16549 scheduleWritePackageRestrictionsLocked(sourceUserId); 16550 } 16551 } 16552 16553 // Enforcing that callingUid is owning pkg on userId 16554 private void enforceOwnerRights(String pkg, int callingUid) { 16555 // The system owns everything. 16556 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 16557 return; 16558 } 16559 int callingUserId = UserHandle.getUserId(callingUid); 16560 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 16561 if (pi == null) { 16562 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 16563 + callingUserId); 16564 } 16565 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 16566 throw new SecurityException("Calling uid " + callingUid 16567 + " does not own package " + pkg); 16568 } 16569 } 16570 16571 @Override 16572 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 16573 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 16574 } 16575 16576 private Intent getHomeIntent() { 16577 Intent intent = new Intent(Intent.ACTION_MAIN); 16578 intent.addCategory(Intent.CATEGORY_HOME); 16579 return intent; 16580 } 16581 16582 private IntentFilter getHomeFilter() { 16583 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 16584 filter.addCategory(Intent.CATEGORY_HOME); 16585 filter.addCategory(Intent.CATEGORY_DEFAULT); 16586 return filter; 16587 } 16588 16589 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 16590 int userId) { 16591 Intent intent = getHomeIntent(); 16592 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 16593 PackageManager.GET_META_DATA, userId); 16594 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 16595 true, false, false, userId); 16596 16597 allHomeCandidates.clear(); 16598 if (list != null) { 16599 for (ResolveInfo ri : list) { 16600 allHomeCandidates.add(ri); 16601 } 16602 } 16603 return (preferred == null || preferred.activityInfo == null) 16604 ? null 16605 : new ComponentName(preferred.activityInfo.packageName, 16606 preferred.activityInfo.name); 16607 } 16608 16609 @Override 16610 public void setHomeActivity(ComponentName comp, int userId) { 16611 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 16612 getHomeActivitiesAsUser(homeActivities, userId); 16613 16614 boolean found = false; 16615 16616 final int size = homeActivities.size(); 16617 final ComponentName[] set = new ComponentName[size]; 16618 for (int i = 0; i < size; i++) { 16619 final ResolveInfo candidate = homeActivities.get(i); 16620 final ActivityInfo info = candidate.activityInfo; 16621 final ComponentName activityName = new ComponentName(info.packageName, info.name); 16622 set[i] = activityName; 16623 if (!found && activityName.equals(comp)) { 16624 found = true; 16625 } 16626 } 16627 if (!found) { 16628 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 16629 + userId); 16630 } 16631 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 16632 set, comp, userId); 16633 } 16634 16635 @Override 16636 public void setApplicationEnabledSetting(String appPackageName, 16637 int newState, int flags, int userId, String callingPackage) { 16638 if (!sUserManager.exists(userId)) return; 16639 if (callingPackage == null) { 16640 callingPackage = Integer.toString(Binder.getCallingUid()); 16641 } 16642 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 16643 } 16644 16645 @Override 16646 public void setComponentEnabledSetting(ComponentName componentName, 16647 int newState, int flags, int userId) { 16648 if (!sUserManager.exists(userId)) return; 16649 setEnabledSetting(componentName.getPackageName(), 16650 componentName.getClassName(), newState, flags, userId, null); 16651 } 16652 16653 private void setEnabledSetting(final String packageName, String className, int newState, 16654 final int flags, int userId, String callingPackage) { 16655 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 16656 || newState == COMPONENT_ENABLED_STATE_ENABLED 16657 || newState == COMPONENT_ENABLED_STATE_DISABLED 16658 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 16659 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 16660 throw new IllegalArgumentException("Invalid new component state: " 16661 + newState); 16662 } 16663 PackageSetting pkgSetting; 16664 final int uid = Binder.getCallingUid(); 16665 final int permission = mContext.checkCallingOrSelfPermission( 16666 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 16667 enforceCrossUserPermission(uid, userId, 16668 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 16669 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 16670 boolean sendNow = false; 16671 boolean isApp = (className == null); 16672 String componentName = isApp ? packageName : className; 16673 int packageUid = -1; 16674 ArrayList<String> components; 16675 16676 // writer 16677 synchronized (mPackages) { 16678 pkgSetting = mSettings.mPackages.get(packageName); 16679 if (pkgSetting == null) { 16680 if (className == null) { 16681 throw new IllegalArgumentException("Unknown package: " + packageName); 16682 } 16683 throw new IllegalArgumentException( 16684 "Unknown component: " + packageName + "/" + className); 16685 } 16686 // Allow root and verify that userId is not being specified by a different user 16687 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 16688 throw new SecurityException( 16689 "Permission Denial: attempt to change component state from pid=" 16690 + Binder.getCallingPid() 16691 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 16692 } 16693 if (className == null) { 16694 // We're dealing with an application/package level state change 16695 if (pkgSetting.getEnabled(userId) == newState) { 16696 // Nothing to do 16697 return; 16698 } 16699 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 16700 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 16701 // Don't care about who enables an app. 16702 callingPackage = null; 16703 } 16704 pkgSetting.setEnabled(newState, userId, callingPackage); 16705 // pkgSetting.pkg.mSetEnabled = newState; 16706 } else { 16707 // We're dealing with a component level state change 16708 // First, verify that this is a valid class name. 16709 PackageParser.Package pkg = pkgSetting.pkg; 16710 if (pkg == null || !pkg.hasComponentClassName(className)) { 16711 if (pkg != null && 16712 pkg.applicationInfo.targetSdkVersion >= 16713 Build.VERSION_CODES.JELLY_BEAN) { 16714 throw new IllegalArgumentException("Component class " + className 16715 + " does not exist in " + packageName); 16716 } else { 16717 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 16718 + className + " does not exist in " + packageName); 16719 } 16720 } 16721 switch (newState) { 16722 case COMPONENT_ENABLED_STATE_ENABLED: 16723 if (!pkgSetting.enableComponentLPw(className, userId)) { 16724 return; 16725 } 16726 break; 16727 case COMPONENT_ENABLED_STATE_DISABLED: 16728 if (!pkgSetting.disableComponentLPw(className, userId)) { 16729 return; 16730 } 16731 break; 16732 case COMPONENT_ENABLED_STATE_DEFAULT: 16733 if (!pkgSetting.restoreComponentLPw(className, userId)) { 16734 return; 16735 } 16736 break; 16737 default: 16738 Slog.e(TAG, "Invalid new component state: " + newState); 16739 return; 16740 } 16741 } 16742 scheduleWritePackageRestrictionsLocked(userId); 16743 components = mPendingBroadcasts.get(userId, packageName); 16744 final boolean newPackage = components == null; 16745 if (newPackage) { 16746 components = new ArrayList<String>(); 16747 } 16748 if (!components.contains(componentName)) { 16749 components.add(componentName); 16750 } 16751 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 16752 sendNow = true; 16753 // Purge entry from pending broadcast list if another one exists already 16754 // since we are sending one right away. 16755 mPendingBroadcasts.remove(userId, packageName); 16756 } else { 16757 if (newPackage) { 16758 mPendingBroadcasts.put(userId, packageName, components); 16759 } 16760 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 16761 // Schedule a message 16762 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 16763 } 16764 } 16765 } 16766 16767 long callingId = Binder.clearCallingIdentity(); 16768 try { 16769 if (sendNow) { 16770 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 16771 sendPackageChangedBroadcast(packageName, 16772 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 16773 } 16774 } finally { 16775 Binder.restoreCallingIdentity(callingId); 16776 } 16777 } 16778 16779 @Override 16780 public void flushPackageRestrictionsAsUser(int userId) { 16781 if (!sUserManager.exists(userId)) { 16782 return; 16783 } 16784 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 16785 false /* checkShell */, "flushPackageRestrictions"); 16786 synchronized (mPackages) { 16787 mSettings.writePackageRestrictionsLPr(userId); 16788 mDirtyUsers.remove(userId); 16789 if (mDirtyUsers.isEmpty()) { 16790 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 16791 } 16792 } 16793 } 16794 16795 private void sendPackageChangedBroadcast(String packageName, 16796 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 16797 if (DEBUG_INSTALL) 16798 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 16799 + componentNames); 16800 Bundle extras = new Bundle(4); 16801 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 16802 String nameList[] = new String[componentNames.size()]; 16803 componentNames.toArray(nameList); 16804 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 16805 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 16806 extras.putInt(Intent.EXTRA_UID, packageUid); 16807 // If this is not reporting a change of the overall package, then only send it 16808 // to registered receivers. We don't want to launch a swath of apps for every 16809 // little component state change. 16810 final int flags = !componentNames.contains(packageName) 16811 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 16812 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 16813 new int[] {UserHandle.getUserId(packageUid)}); 16814 } 16815 16816 @Override 16817 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 16818 if (!sUserManager.exists(userId)) return; 16819 final int uid = Binder.getCallingUid(); 16820 final int permission = mContext.checkCallingOrSelfPermission( 16821 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 16822 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 16823 enforceCrossUserPermission(uid, userId, 16824 true /* requireFullPermission */, true /* checkShell */, "stop package"); 16825 // writer 16826 synchronized (mPackages) { 16827 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 16828 allowedByPermission, uid, userId)) { 16829 scheduleWritePackageRestrictionsLocked(userId); 16830 } 16831 } 16832 } 16833 16834 @Override 16835 public String getInstallerPackageName(String packageName) { 16836 // reader 16837 synchronized (mPackages) { 16838 return mSettings.getInstallerPackageNameLPr(packageName); 16839 } 16840 } 16841 16842 @Override 16843 public int getApplicationEnabledSetting(String packageName, int userId) { 16844 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 16845 int uid = Binder.getCallingUid(); 16846 enforceCrossUserPermission(uid, userId, 16847 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 16848 // reader 16849 synchronized (mPackages) { 16850 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 16851 } 16852 } 16853 16854 @Override 16855 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 16856 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 16857 int uid = Binder.getCallingUid(); 16858 enforceCrossUserPermission(uid, userId, 16859 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 16860 // reader 16861 synchronized (mPackages) { 16862 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 16863 } 16864 } 16865 16866 @Override 16867 public void enterSafeMode() { 16868 enforceSystemOrRoot("Only the system can request entering safe mode"); 16869 16870 if (!mSystemReady) { 16871 mSafeMode = true; 16872 } 16873 } 16874 16875 @Override 16876 public void systemReady() { 16877 mSystemReady = true; 16878 16879 // Read the compatibilty setting when the system is ready. 16880 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 16881 mContext.getContentResolver(), 16882 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 16883 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 16884 if (DEBUG_SETTINGS) { 16885 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 16886 } 16887 16888 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 16889 16890 synchronized (mPackages) { 16891 // Verify that all of the preferred activity components actually 16892 // exist. It is possible for applications to be updated and at 16893 // that point remove a previously declared activity component that 16894 // had been set as a preferred activity. We try to clean this up 16895 // the next time we encounter that preferred activity, but it is 16896 // possible for the user flow to never be able to return to that 16897 // situation so here we do a sanity check to make sure we haven't 16898 // left any junk around. 16899 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 16900 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16901 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16902 removed.clear(); 16903 for (PreferredActivity pa : pir.filterSet()) { 16904 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 16905 removed.add(pa); 16906 } 16907 } 16908 if (removed.size() > 0) { 16909 for (int r=0; r<removed.size(); r++) { 16910 PreferredActivity pa = removed.get(r); 16911 Slog.w(TAG, "Removing dangling preferred activity: " 16912 + pa.mPref.mComponent); 16913 pir.removeFilter(pa); 16914 } 16915 mSettings.writePackageRestrictionsLPr( 16916 mSettings.mPreferredActivities.keyAt(i)); 16917 } 16918 } 16919 16920 for (int userId : UserManagerService.getInstance().getUserIds()) { 16921 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 16922 grantPermissionsUserIds = ArrayUtils.appendInt( 16923 grantPermissionsUserIds, userId); 16924 } 16925 } 16926 } 16927 sUserManager.systemReady(); 16928 16929 // If we upgraded grant all default permissions before kicking off. 16930 for (int userId : grantPermissionsUserIds) { 16931 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 16932 } 16933 16934 // Kick off any messages waiting for system ready 16935 if (mPostSystemReadyMessages != null) { 16936 for (Message msg : mPostSystemReadyMessages) { 16937 msg.sendToTarget(); 16938 } 16939 mPostSystemReadyMessages = null; 16940 } 16941 16942 // Watch for external volumes that come and go over time 16943 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16944 storage.registerListener(mStorageListener); 16945 16946 mInstallerService.systemReady(); 16947 mPackageDexOptimizer.systemReady(); 16948 16949 MountServiceInternal mountServiceInternal = LocalServices.getService( 16950 MountServiceInternal.class); 16951 mountServiceInternal.addExternalStoragePolicy( 16952 new MountServiceInternal.ExternalStorageMountPolicy() { 16953 @Override 16954 public int getMountMode(int uid, String packageName) { 16955 if (Process.isIsolated(uid)) { 16956 return Zygote.MOUNT_EXTERNAL_NONE; 16957 } 16958 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 16959 return Zygote.MOUNT_EXTERNAL_DEFAULT; 16960 } 16961 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 16962 return Zygote.MOUNT_EXTERNAL_DEFAULT; 16963 } 16964 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 16965 return Zygote.MOUNT_EXTERNAL_READ; 16966 } 16967 return Zygote.MOUNT_EXTERNAL_WRITE; 16968 } 16969 16970 @Override 16971 public boolean hasExternalStorage(int uid, String packageName) { 16972 return true; 16973 } 16974 }); 16975 } 16976 16977 @Override 16978 public boolean isSafeMode() { 16979 return mSafeMode; 16980 } 16981 16982 @Override 16983 public boolean hasSystemUidErrors() { 16984 return mHasSystemUidErrors; 16985 } 16986 16987 static String arrayToString(int[] array) { 16988 StringBuffer buf = new StringBuffer(128); 16989 buf.append('['); 16990 if (array != null) { 16991 for (int i=0; i<array.length; i++) { 16992 if (i > 0) buf.append(", "); 16993 buf.append(array[i]); 16994 } 16995 } 16996 buf.append(']'); 16997 return buf.toString(); 16998 } 16999 17000 static class DumpState { 17001 public static final int DUMP_LIBS = 1 << 0; 17002 public static final int DUMP_FEATURES = 1 << 1; 17003 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17004 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17005 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17006 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17007 public static final int DUMP_PERMISSIONS = 1 << 6; 17008 public static final int DUMP_PACKAGES = 1 << 7; 17009 public static final int DUMP_SHARED_USERS = 1 << 8; 17010 public static final int DUMP_MESSAGES = 1 << 9; 17011 public static final int DUMP_PROVIDERS = 1 << 10; 17012 public static final int DUMP_VERIFIERS = 1 << 11; 17013 public static final int DUMP_PREFERRED = 1 << 12; 17014 public static final int DUMP_PREFERRED_XML = 1 << 13; 17015 public static final int DUMP_KEYSETS = 1 << 14; 17016 public static final int DUMP_VERSION = 1 << 15; 17017 public static final int DUMP_INSTALLS = 1 << 16; 17018 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17019 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17020 17021 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17022 17023 private int mTypes; 17024 17025 private int mOptions; 17026 17027 private boolean mTitlePrinted; 17028 17029 private SharedUserSetting mSharedUser; 17030 17031 public boolean isDumping(int type) { 17032 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17033 return true; 17034 } 17035 17036 return (mTypes & type) != 0; 17037 } 17038 17039 public void setDump(int type) { 17040 mTypes |= type; 17041 } 17042 17043 public boolean isOptionEnabled(int option) { 17044 return (mOptions & option) != 0; 17045 } 17046 17047 public void setOptionEnabled(int option) { 17048 mOptions |= option; 17049 } 17050 17051 public boolean onTitlePrinted() { 17052 final boolean printed = mTitlePrinted; 17053 mTitlePrinted = true; 17054 return printed; 17055 } 17056 17057 public boolean getTitlePrinted() { 17058 return mTitlePrinted; 17059 } 17060 17061 public void setTitlePrinted(boolean enabled) { 17062 mTitlePrinted = enabled; 17063 } 17064 17065 public SharedUserSetting getSharedUser() { 17066 return mSharedUser; 17067 } 17068 17069 public void setSharedUser(SharedUserSetting user) { 17070 mSharedUser = user; 17071 } 17072 } 17073 17074 @Override 17075 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17076 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17077 (new PackageManagerShellCommand(this)).exec( 17078 this, in, out, err, args, resultReceiver); 17079 } 17080 17081 @Override 17082 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17083 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17084 != PackageManager.PERMISSION_GRANTED) { 17085 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17086 + Binder.getCallingPid() 17087 + ", uid=" + Binder.getCallingUid() 17088 + " without permission " 17089 + android.Manifest.permission.DUMP); 17090 return; 17091 } 17092 17093 DumpState dumpState = new DumpState(); 17094 boolean fullPreferred = false; 17095 boolean checkin = false; 17096 17097 String packageName = null; 17098 ArraySet<String> permissionNames = null; 17099 17100 int opti = 0; 17101 while (opti < args.length) { 17102 String opt = args[opti]; 17103 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 17104 break; 17105 } 17106 opti++; 17107 17108 if ("-a".equals(opt)) { 17109 // Right now we only know how to print all. 17110 } else if ("-h".equals(opt)) { 17111 pw.println("Package manager dump options:"); 17112 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 17113 pw.println(" --checkin: dump for a checkin"); 17114 pw.println(" -f: print details of intent filters"); 17115 pw.println(" -h: print this help"); 17116 pw.println(" cmd may be one of:"); 17117 pw.println(" l[ibraries]: list known shared libraries"); 17118 pw.println(" f[eatures]: list device features"); 17119 pw.println(" k[eysets]: print known keysets"); 17120 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 17121 pw.println(" perm[issions]: dump permissions"); 17122 pw.println(" permission [name ...]: dump declaration and use of given permission"); 17123 pw.println(" pref[erred]: print preferred package settings"); 17124 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 17125 pw.println(" prov[iders]: dump content providers"); 17126 pw.println(" p[ackages]: dump installed packages"); 17127 pw.println(" s[hared-users]: dump shared user IDs"); 17128 pw.println(" m[essages]: print collected runtime messages"); 17129 pw.println(" v[erifiers]: print package verifier info"); 17130 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 17131 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 17132 pw.println(" version: print database version info"); 17133 pw.println(" write: write current settings now"); 17134 pw.println(" installs: details about install sessions"); 17135 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 17136 pw.println(" <package.name>: info about given package"); 17137 return; 17138 } else if ("--checkin".equals(opt)) { 17139 checkin = true; 17140 } else if ("-f".equals(opt)) { 17141 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17142 } else { 17143 pw.println("Unknown argument: " + opt + "; use -h for help"); 17144 } 17145 } 17146 17147 // Is the caller requesting to dump a particular piece of data? 17148 if (opti < args.length) { 17149 String cmd = args[opti]; 17150 opti++; 17151 // Is this a package name? 17152 if ("android".equals(cmd) || cmd.contains(".")) { 17153 packageName = cmd; 17154 // When dumping a single package, we always dump all of its 17155 // filter information since the amount of data will be reasonable. 17156 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17157 } else if ("check-permission".equals(cmd)) { 17158 if (opti >= args.length) { 17159 pw.println("Error: check-permission missing permission argument"); 17160 return; 17161 } 17162 String perm = args[opti]; 17163 opti++; 17164 if (opti >= args.length) { 17165 pw.println("Error: check-permission missing package argument"); 17166 return; 17167 } 17168 String pkg = args[opti]; 17169 opti++; 17170 int user = UserHandle.getUserId(Binder.getCallingUid()); 17171 if (opti < args.length) { 17172 try { 17173 user = Integer.parseInt(args[opti]); 17174 } catch (NumberFormatException e) { 17175 pw.println("Error: check-permission user argument is not a number: " 17176 + args[opti]); 17177 return; 17178 } 17179 } 17180 pw.println(checkPermission(perm, pkg, user)); 17181 return; 17182 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 17183 dumpState.setDump(DumpState.DUMP_LIBS); 17184 } else if ("f".equals(cmd) || "features".equals(cmd)) { 17185 dumpState.setDump(DumpState.DUMP_FEATURES); 17186 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 17187 if (opti >= args.length) { 17188 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 17189 | DumpState.DUMP_SERVICE_RESOLVERS 17190 | DumpState.DUMP_RECEIVER_RESOLVERS 17191 | DumpState.DUMP_CONTENT_RESOLVERS); 17192 } else { 17193 while (opti < args.length) { 17194 String name = args[opti]; 17195 if ("a".equals(name) || "activity".equals(name)) { 17196 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 17197 } else if ("s".equals(name) || "service".equals(name)) { 17198 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 17199 } else if ("r".equals(name) || "receiver".equals(name)) { 17200 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 17201 } else if ("c".equals(name) || "content".equals(name)) { 17202 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 17203 } else { 17204 pw.println("Error: unknown resolver table type: " + name); 17205 return; 17206 } 17207 opti++; 17208 } 17209 } 17210 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 17211 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 17212 } else if ("permission".equals(cmd)) { 17213 if (opti >= args.length) { 17214 pw.println("Error: permission requires permission name"); 17215 return; 17216 } 17217 permissionNames = new ArraySet<>(); 17218 while (opti < args.length) { 17219 permissionNames.add(args[opti]); 17220 opti++; 17221 } 17222 dumpState.setDump(DumpState.DUMP_PERMISSIONS 17223 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 17224 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 17225 dumpState.setDump(DumpState.DUMP_PREFERRED); 17226 } else if ("preferred-xml".equals(cmd)) { 17227 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 17228 if (opti < args.length && "--full".equals(args[opti])) { 17229 fullPreferred = true; 17230 opti++; 17231 } 17232 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 17233 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 17234 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 17235 dumpState.setDump(DumpState.DUMP_PACKAGES); 17236 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 17237 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 17238 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 17239 dumpState.setDump(DumpState.DUMP_PROVIDERS); 17240 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 17241 dumpState.setDump(DumpState.DUMP_MESSAGES); 17242 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 17243 dumpState.setDump(DumpState.DUMP_VERIFIERS); 17244 } else if ("i".equals(cmd) || "ifv".equals(cmd) 17245 || "intent-filter-verifiers".equals(cmd)) { 17246 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 17247 } else if ("version".equals(cmd)) { 17248 dumpState.setDump(DumpState.DUMP_VERSION); 17249 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 17250 dumpState.setDump(DumpState.DUMP_KEYSETS); 17251 } else if ("installs".equals(cmd)) { 17252 dumpState.setDump(DumpState.DUMP_INSTALLS); 17253 } else if ("write".equals(cmd)) { 17254 synchronized (mPackages) { 17255 mSettings.writeLPr(); 17256 pw.println("Settings written."); 17257 return; 17258 } 17259 } 17260 } 17261 17262 if (checkin) { 17263 pw.println("vers,1"); 17264 } 17265 17266 // reader 17267 synchronized (mPackages) { 17268 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 17269 if (!checkin) { 17270 if (dumpState.onTitlePrinted()) 17271 pw.println(); 17272 pw.println("Database versions:"); 17273 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 17274 } 17275 } 17276 17277 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 17278 if (!checkin) { 17279 if (dumpState.onTitlePrinted()) 17280 pw.println(); 17281 pw.println("Verifiers:"); 17282 pw.print(" Required: "); 17283 pw.print(mRequiredVerifierPackage); 17284 pw.print(" (uid="); 17285 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17286 UserHandle.USER_SYSTEM)); 17287 pw.println(")"); 17288 } else if (mRequiredVerifierPackage != null) { 17289 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 17290 pw.print(","); 17291 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17292 UserHandle.USER_SYSTEM)); 17293 } 17294 } 17295 17296 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 17297 packageName == null) { 17298 if (mIntentFilterVerifierComponent != null) { 17299 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 17300 if (!checkin) { 17301 if (dumpState.onTitlePrinted()) 17302 pw.println(); 17303 pw.println("Intent Filter Verifier:"); 17304 pw.print(" Using: "); 17305 pw.print(verifierPackageName); 17306 pw.print(" (uid="); 17307 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17308 UserHandle.USER_SYSTEM)); 17309 pw.println(")"); 17310 } else if (verifierPackageName != null) { 17311 pw.print("ifv,"); pw.print(verifierPackageName); 17312 pw.print(","); 17313 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17314 UserHandle.USER_SYSTEM)); 17315 } 17316 } else { 17317 pw.println(); 17318 pw.println("No Intent Filter Verifier available!"); 17319 } 17320 } 17321 17322 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 17323 boolean printedHeader = false; 17324 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 17325 while (it.hasNext()) { 17326 String name = it.next(); 17327 SharedLibraryEntry ent = mSharedLibraries.get(name); 17328 if (!checkin) { 17329 if (!printedHeader) { 17330 if (dumpState.onTitlePrinted()) 17331 pw.println(); 17332 pw.println("Libraries:"); 17333 printedHeader = true; 17334 } 17335 pw.print(" "); 17336 } else { 17337 pw.print("lib,"); 17338 } 17339 pw.print(name); 17340 if (!checkin) { 17341 pw.print(" -> "); 17342 } 17343 if (ent.path != null) { 17344 if (!checkin) { 17345 pw.print("(jar) "); 17346 pw.print(ent.path); 17347 } else { 17348 pw.print(",jar,"); 17349 pw.print(ent.path); 17350 } 17351 } else { 17352 if (!checkin) { 17353 pw.print("(apk) "); 17354 pw.print(ent.apk); 17355 } else { 17356 pw.print(",apk,"); 17357 pw.print(ent.apk); 17358 } 17359 } 17360 pw.println(); 17361 } 17362 } 17363 17364 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 17365 if (dumpState.onTitlePrinted()) 17366 pw.println(); 17367 if (!checkin) { 17368 pw.println("Features:"); 17369 } 17370 17371 for (FeatureInfo feat : mAvailableFeatures.values()) { 17372 if (checkin) { 17373 pw.print("feat,"); 17374 pw.print(feat.name); 17375 pw.print(","); 17376 pw.println(feat.version); 17377 } else { 17378 pw.print(" "); 17379 pw.print(feat.name); 17380 if (feat.version > 0) { 17381 pw.print(" version="); 17382 pw.print(feat.version); 17383 } 17384 pw.println(); 17385 } 17386 } 17387 } 17388 17389 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 17390 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 17391 : "Activity Resolver Table:", " ", packageName, 17392 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17393 dumpState.setTitlePrinted(true); 17394 } 17395 } 17396 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 17397 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 17398 : "Receiver Resolver Table:", " ", packageName, 17399 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17400 dumpState.setTitlePrinted(true); 17401 } 17402 } 17403 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 17404 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 17405 : "Service Resolver Table:", " ", packageName, 17406 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17407 dumpState.setTitlePrinted(true); 17408 } 17409 } 17410 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 17411 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 17412 : "Provider Resolver Table:", " ", packageName, 17413 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17414 dumpState.setTitlePrinted(true); 17415 } 17416 } 17417 17418 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 17419 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17420 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17421 int user = mSettings.mPreferredActivities.keyAt(i); 17422 if (pir.dump(pw, 17423 dumpState.getTitlePrinted() 17424 ? "\nPreferred Activities User " + user + ":" 17425 : "Preferred Activities User " + user + ":", " ", 17426 packageName, true, false)) { 17427 dumpState.setTitlePrinted(true); 17428 } 17429 } 17430 } 17431 17432 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 17433 pw.flush(); 17434 FileOutputStream fout = new FileOutputStream(fd); 17435 BufferedOutputStream str = new BufferedOutputStream(fout); 17436 XmlSerializer serializer = new FastXmlSerializer(); 17437 try { 17438 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 17439 serializer.startDocument(null, true); 17440 serializer.setFeature( 17441 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 17442 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 17443 serializer.endDocument(); 17444 serializer.flush(); 17445 } catch (IllegalArgumentException e) { 17446 pw.println("Failed writing: " + e); 17447 } catch (IllegalStateException e) { 17448 pw.println("Failed writing: " + e); 17449 } catch (IOException e) { 17450 pw.println("Failed writing: " + e); 17451 } 17452 } 17453 17454 if (!checkin 17455 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 17456 && packageName == null) { 17457 pw.println(); 17458 int count = mSettings.mPackages.size(); 17459 if (count == 0) { 17460 pw.println("No applications!"); 17461 pw.println(); 17462 } else { 17463 final String prefix = " "; 17464 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 17465 if (allPackageSettings.size() == 0) { 17466 pw.println("No domain preferred apps!"); 17467 pw.println(); 17468 } else { 17469 pw.println("App verification status:"); 17470 pw.println(); 17471 count = 0; 17472 for (PackageSetting ps : allPackageSettings) { 17473 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 17474 if (ivi == null || ivi.getPackageName() == null) continue; 17475 pw.println(prefix + "Package: " + ivi.getPackageName()); 17476 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 17477 pw.println(prefix + "Status: " + ivi.getStatusString()); 17478 pw.println(); 17479 count++; 17480 } 17481 if (count == 0) { 17482 pw.println(prefix + "No app verification established."); 17483 pw.println(); 17484 } 17485 for (int userId : sUserManager.getUserIds()) { 17486 pw.println("App linkages for user " + userId + ":"); 17487 pw.println(); 17488 count = 0; 17489 for (PackageSetting ps : allPackageSettings) { 17490 final long status = ps.getDomainVerificationStatusForUser(userId); 17491 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 17492 continue; 17493 } 17494 pw.println(prefix + "Package: " + ps.name); 17495 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 17496 String statusStr = IntentFilterVerificationInfo. 17497 getStatusStringFromValue(status); 17498 pw.println(prefix + "Status: " + statusStr); 17499 pw.println(); 17500 count++; 17501 } 17502 if (count == 0) { 17503 pw.println(prefix + "No configured app linkages."); 17504 pw.println(); 17505 } 17506 } 17507 } 17508 } 17509 } 17510 17511 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 17512 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 17513 if (packageName == null && permissionNames == null) { 17514 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 17515 if (iperm == 0) { 17516 if (dumpState.onTitlePrinted()) 17517 pw.println(); 17518 pw.println("AppOp Permissions:"); 17519 } 17520 pw.print(" AppOp Permission "); 17521 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 17522 pw.println(":"); 17523 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 17524 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 17525 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 17526 } 17527 } 17528 } 17529 } 17530 17531 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 17532 boolean printedSomething = false; 17533 for (PackageParser.Provider p : mProviders.mProviders.values()) { 17534 if (packageName != null && !packageName.equals(p.info.packageName)) { 17535 continue; 17536 } 17537 if (!printedSomething) { 17538 if (dumpState.onTitlePrinted()) 17539 pw.println(); 17540 pw.println("Registered ContentProviders:"); 17541 printedSomething = true; 17542 } 17543 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 17544 pw.print(" "); pw.println(p.toString()); 17545 } 17546 printedSomething = false; 17547 for (Map.Entry<String, PackageParser.Provider> entry : 17548 mProvidersByAuthority.entrySet()) { 17549 PackageParser.Provider p = entry.getValue(); 17550 if (packageName != null && !packageName.equals(p.info.packageName)) { 17551 continue; 17552 } 17553 if (!printedSomething) { 17554 if (dumpState.onTitlePrinted()) 17555 pw.println(); 17556 pw.println("ContentProvider Authorities:"); 17557 printedSomething = true; 17558 } 17559 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 17560 pw.print(" "); pw.println(p.toString()); 17561 if (p.info != null && p.info.applicationInfo != null) { 17562 final String appInfo = p.info.applicationInfo.toString(); 17563 pw.print(" applicationInfo="); pw.println(appInfo); 17564 } 17565 } 17566 } 17567 17568 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 17569 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 17570 } 17571 17572 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 17573 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 17574 } 17575 17576 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 17577 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 17578 } 17579 17580 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 17581 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 17582 } 17583 17584 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 17585 // XXX should handle packageName != null by dumping only install data that 17586 // the given package is involved with. 17587 if (dumpState.onTitlePrinted()) pw.println(); 17588 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 17589 } 17590 17591 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 17592 if (dumpState.onTitlePrinted()) pw.println(); 17593 mSettings.dumpReadMessagesLPr(pw, dumpState); 17594 17595 pw.println(); 17596 pw.println("Package warning messages:"); 17597 BufferedReader in = null; 17598 String line = null; 17599 try { 17600 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 17601 while ((line = in.readLine()) != null) { 17602 if (line.contains("ignored: updated version")) continue; 17603 pw.println(line); 17604 } 17605 } catch (IOException ignored) { 17606 } finally { 17607 IoUtils.closeQuietly(in); 17608 } 17609 } 17610 17611 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 17612 BufferedReader in = null; 17613 String line = null; 17614 try { 17615 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 17616 while ((line = in.readLine()) != null) { 17617 if (line.contains("ignored: updated version")) continue; 17618 pw.print("msg,"); 17619 pw.println(line); 17620 } 17621 } catch (IOException ignored) { 17622 } finally { 17623 IoUtils.closeQuietly(in); 17624 } 17625 } 17626 } 17627 } 17628 17629 private String dumpDomainString(String packageName) { 17630 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 17631 .getList(); 17632 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 17633 17634 ArraySet<String> result = new ArraySet<>(); 17635 if (iviList.size() > 0) { 17636 for (IntentFilterVerificationInfo ivi : iviList) { 17637 for (String host : ivi.getDomains()) { 17638 result.add(host); 17639 } 17640 } 17641 } 17642 if (filters != null && filters.size() > 0) { 17643 for (IntentFilter filter : filters) { 17644 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 17645 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 17646 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 17647 result.addAll(filter.getHostsList()); 17648 } 17649 } 17650 } 17651 17652 StringBuilder sb = new StringBuilder(result.size() * 16); 17653 for (String domain : result) { 17654 if (sb.length() > 0) sb.append(" "); 17655 sb.append(domain); 17656 } 17657 return sb.toString(); 17658 } 17659 17660 // ------- apps on sdcard specific code ------- 17661 static final boolean DEBUG_SD_INSTALL = false; 17662 17663 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 17664 17665 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 17666 17667 private boolean mMediaMounted = false; 17668 17669 static String getEncryptKey() { 17670 try { 17671 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 17672 SD_ENCRYPTION_KEYSTORE_NAME); 17673 if (sdEncKey == null) { 17674 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 17675 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 17676 if (sdEncKey == null) { 17677 Slog.e(TAG, "Failed to create encryption keys"); 17678 return null; 17679 } 17680 } 17681 return sdEncKey; 17682 } catch (NoSuchAlgorithmException nsae) { 17683 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 17684 return null; 17685 } catch (IOException ioe) { 17686 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 17687 return null; 17688 } 17689 } 17690 17691 /* 17692 * Update media status on PackageManager. 17693 */ 17694 @Override 17695 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 17696 int callingUid = Binder.getCallingUid(); 17697 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 17698 throw new SecurityException("Media status can only be updated by the system"); 17699 } 17700 // reader; this apparently protects mMediaMounted, but should probably 17701 // be a different lock in that case. 17702 synchronized (mPackages) { 17703 Log.i(TAG, "Updating external media status from " 17704 + (mMediaMounted ? "mounted" : "unmounted") + " to " 17705 + (mediaStatus ? "mounted" : "unmounted")); 17706 if (DEBUG_SD_INSTALL) 17707 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 17708 + ", mMediaMounted=" + mMediaMounted); 17709 if (mediaStatus == mMediaMounted) { 17710 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 17711 : 0, -1); 17712 mHandler.sendMessage(msg); 17713 return; 17714 } 17715 mMediaMounted = mediaStatus; 17716 } 17717 // Queue up an async operation since the package installation may take a 17718 // little while. 17719 mHandler.post(new Runnable() { 17720 public void run() { 17721 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 17722 } 17723 }); 17724 } 17725 17726 /** 17727 * Called by MountService when the initial ASECs to scan are available. 17728 * Should block until all the ASEC containers are finished being scanned. 17729 */ 17730 public void scanAvailableAsecs() { 17731 updateExternalMediaStatusInner(true, false, false); 17732 } 17733 17734 /* 17735 * Collect information of applications on external media, map them against 17736 * existing containers and update information based on current mount status. 17737 * Please note that we always have to report status if reportStatus has been 17738 * set to true especially when unloading packages. 17739 */ 17740 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 17741 boolean externalStorage) { 17742 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 17743 int[] uidArr = EmptyArray.INT; 17744 17745 final String[] list = PackageHelper.getSecureContainerList(); 17746 if (ArrayUtils.isEmpty(list)) { 17747 Log.i(TAG, "No secure containers found"); 17748 } else { 17749 // Process list of secure containers and categorize them 17750 // as active or stale based on their package internal state. 17751 17752 // reader 17753 synchronized (mPackages) { 17754 for (String cid : list) { 17755 // Leave stages untouched for now; installer service owns them 17756 if (PackageInstallerService.isStageName(cid)) continue; 17757 17758 if (DEBUG_SD_INSTALL) 17759 Log.i(TAG, "Processing container " + cid); 17760 String pkgName = getAsecPackageName(cid); 17761 if (pkgName == null) { 17762 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 17763 continue; 17764 } 17765 if (DEBUG_SD_INSTALL) 17766 Log.i(TAG, "Looking for pkg : " + pkgName); 17767 17768 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17769 if (ps == null) { 17770 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 17771 continue; 17772 } 17773 17774 /* 17775 * Skip packages that are not external if we're unmounting 17776 * external storage. 17777 */ 17778 if (externalStorage && !isMounted && !isExternal(ps)) { 17779 continue; 17780 } 17781 17782 final AsecInstallArgs args = new AsecInstallArgs(cid, 17783 getAppDexInstructionSets(ps), ps.isForwardLocked()); 17784 // The package status is changed only if the code path 17785 // matches between settings and the container id. 17786 if (ps.codePathString != null 17787 && ps.codePathString.startsWith(args.getCodePath())) { 17788 if (DEBUG_SD_INSTALL) { 17789 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 17790 + " at code path: " + ps.codePathString); 17791 } 17792 17793 // We do have a valid package installed on sdcard 17794 processCids.put(args, ps.codePathString); 17795 final int uid = ps.appId; 17796 if (uid != -1) { 17797 uidArr = ArrayUtils.appendInt(uidArr, uid); 17798 } 17799 } else { 17800 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 17801 + ps.codePathString); 17802 } 17803 } 17804 } 17805 17806 Arrays.sort(uidArr); 17807 } 17808 17809 // Process packages with valid entries. 17810 if (isMounted) { 17811 if (DEBUG_SD_INSTALL) 17812 Log.i(TAG, "Loading packages"); 17813 loadMediaPackages(processCids, uidArr, externalStorage); 17814 startCleaningPackages(); 17815 mInstallerService.onSecureContainersAvailable(); 17816 } else { 17817 if (DEBUG_SD_INSTALL) 17818 Log.i(TAG, "Unloading packages"); 17819 unloadMediaPackages(processCids, uidArr, reportStatus); 17820 } 17821 } 17822 17823 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17824 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 17825 final int size = infos.size(); 17826 final String[] packageNames = new String[size]; 17827 final int[] packageUids = new int[size]; 17828 for (int i = 0; i < size; i++) { 17829 final ApplicationInfo info = infos.get(i); 17830 packageNames[i] = info.packageName; 17831 packageUids[i] = info.uid; 17832 } 17833 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 17834 finishedReceiver); 17835 } 17836 17837 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17838 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 17839 sendResourcesChangedBroadcast(mediaStatus, replacing, 17840 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 17841 } 17842 17843 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17844 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 17845 int size = pkgList.length; 17846 if (size > 0) { 17847 // Send broadcasts here 17848 Bundle extras = new Bundle(); 17849 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 17850 if (uidArr != null) { 17851 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 17852 } 17853 if (replacing) { 17854 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 17855 } 17856 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 17857 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 17858 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 17859 } 17860 } 17861 17862 /* 17863 * Look at potentially valid container ids from processCids If package 17864 * information doesn't match the one on record or package scanning fails, 17865 * the cid is added to list of removeCids. We currently don't delete stale 17866 * containers. 17867 */ 17868 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 17869 boolean externalStorage) { 17870 ArrayList<String> pkgList = new ArrayList<String>(); 17871 Set<AsecInstallArgs> keys = processCids.keySet(); 17872 17873 for (AsecInstallArgs args : keys) { 17874 String codePath = processCids.get(args); 17875 if (DEBUG_SD_INSTALL) 17876 Log.i(TAG, "Loading container : " + args.cid); 17877 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 17878 try { 17879 // Make sure there are no container errors first. 17880 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 17881 Slog.e(TAG, "Failed to mount cid : " + args.cid 17882 + " when installing from sdcard"); 17883 continue; 17884 } 17885 // Check code path here. 17886 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 17887 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 17888 + " does not match one in settings " + codePath); 17889 continue; 17890 } 17891 // Parse package 17892 int parseFlags = mDefParseFlags; 17893 if (args.isExternalAsec()) { 17894 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 17895 } 17896 if (args.isFwdLocked()) { 17897 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 17898 } 17899 17900 synchronized (mInstallLock) { 17901 PackageParser.Package pkg = null; 17902 try { 17903 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 17904 } catch (PackageManagerException e) { 17905 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 17906 } 17907 // Scan the package 17908 if (pkg != null) { 17909 /* 17910 * TODO why is the lock being held? doPostInstall is 17911 * called in other places without the lock. This needs 17912 * to be straightened out. 17913 */ 17914 // writer 17915 synchronized (mPackages) { 17916 retCode = PackageManager.INSTALL_SUCCEEDED; 17917 pkgList.add(pkg.packageName); 17918 // Post process args 17919 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 17920 pkg.applicationInfo.uid); 17921 } 17922 } else { 17923 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 17924 } 17925 } 17926 17927 } finally { 17928 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 17929 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 17930 } 17931 } 17932 } 17933 // writer 17934 synchronized (mPackages) { 17935 // If the platform SDK has changed since the last time we booted, 17936 // we need to re-grant app permission to catch any new ones that 17937 // appear. This is really a hack, and means that apps can in some 17938 // cases get permissions that the user didn't initially explicitly 17939 // allow... it would be nice to have some better way to handle 17940 // this situation. 17941 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 17942 : mSettings.getInternalVersion(); 17943 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 17944 : StorageManager.UUID_PRIVATE_INTERNAL; 17945 17946 int updateFlags = UPDATE_PERMISSIONS_ALL; 17947 if (ver.sdkVersion != mSdkVersion) { 17948 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 17949 + mSdkVersion + "; regranting permissions for external"); 17950 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 17951 } 17952 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 17953 17954 // Yay, everything is now upgraded 17955 ver.forceCurrent(); 17956 17957 // can downgrade to reader 17958 // Persist settings 17959 mSettings.writeLPr(); 17960 } 17961 // Send a broadcast to let everyone know we are done processing 17962 if (pkgList.size() > 0) { 17963 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 17964 } 17965 } 17966 17967 /* 17968 * Utility method to unload a list of specified containers 17969 */ 17970 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 17971 // Just unmount all valid containers. 17972 for (AsecInstallArgs arg : cidArgs) { 17973 synchronized (mInstallLock) { 17974 arg.doPostDeleteLI(false); 17975 } 17976 } 17977 } 17978 17979 /* 17980 * Unload packages mounted on external media. This involves deleting package 17981 * data from internal structures, sending broadcasts about disabled packages, 17982 * gc'ing to free up references, unmounting all secure containers 17983 * corresponding to packages on external media, and posting a 17984 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 17985 * that we always have to post this message if status has been requested no 17986 * matter what. 17987 */ 17988 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 17989 final boolean reportStatus) { 17990 if (DEBUG_SD_INSTALL) 17991 Log.i(TAG, "unloading media packages"); 17992 ArrayList<String> pkgList = new ArrayList<String>(); 17993 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 17994 final Set<AsecInstallArgs> keys = processCids.keySet(); 17995 for (AsecInstallArgs args : keys) { 17996 String pkgName = args.getPackageName(); 17997 if (DEBUG_SD_INSTALL) 17998 Log.i(TAG, "Trying to unload pkg : " + pkgName); 17999 // Delete package internally 18000 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18001 synchronized (mInstallLock) { 18002 boolean res = deletePackageLI(pkgName, null, false, null, 18003 PackageManager.DELETE_KEEP_DATA, outInfo, false, null); 18004 if (res) { 18005 pkgList.add(pkgName); 18006 } else { 18007 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18008 failedList.add(args); 18009 } 18010 } 18011 } 18012 18013 // reader 18014 synchronized (mPackages) { 18015 // We didn't update the settings after removing each package; 18016 // write them now for all packages. 18017 mSettings.writeLPr(); 18018 } 18019 18020 // We have to absolutely send UPDATED_MEDIA_STATUS only 18021 // after confirming that all the receivers processed the ordered 18022 // broadcast when packages get disabled, force a gc to clean things up. 18023 // and unload all the containers. 18024 if (pkgList.size() > 0) { 18025 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18026 new IIntentReceiver.Stub() { 18027 public void performReceive(Intent intent, int resultCode, String data, 18028 Bundle extras, boolean ordered, boolean sticky, 18029 int sendingUser) throws RemoteException { 18030 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18031 reportStatus ? 1 : 0, 1, keys); 18032 mHandler.sendMessage(msg); 18033 } 18034 }); 18035 } else { 18036 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 18037 keys); 18038 mHandler.sendMessage(msg); 18039 } 18040 } 18041 18042 private void loadPrivatePackages(final VolumeInfo vol) { 18043 mHandler.post(new Runnable() { 18044 @Override 18045 public void run() { 18046 loadPrivatePackagesInner(vol); 18047 } 18048 }); 18049 } 18050 18051 private void loadPrivatePackagesInner(VolumeInfo vol) { 18052 final String volumeUuid = vol.fsUuid; 18053 if (TextUtils.isEmpty(volumeUuid)) { 18054 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 18055 return; 18056 } 18057 18058 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 18059 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 18060 18061 final VersionInfo ver; 18062 final List<PackageSetting> packages; 18063 synchronized (mPackages) { 18064 ver = mSettings.findOrCreateVersion(volumeUuid); 18065 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18066 } 18067 18068 // TODO: introduce a new concept similar to "frozen" to prevent these 18069 // apps from being launched until after data has been fully reconciled 18070 for (PackageSetting ps : packages) { 18071 synchronized (mInstallLock) { 18072 final PackageParser.Package pkg; 18073 try { 18074 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 18075 loaded.add(pkg.applicationInfo); 18076 18077 } catch (PackageManagerException e) { 18078 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 18079 } 18080 18081 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 18082 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 18083 } 18084 } 18085 } 18086 18087 // Reconcile app data for all started/unlocked users 18088 final StorageManager sm = mContext.getSystemService(StorageManager.class); 18089 final UserManager um = mContext.getSystemService(UserManager.class); 18090 for (UserInfo user : um.getUsers()) { 18091 final int flags; 18092 if (um.isUserUnlocked(user.id)) { 18093 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18094 } else if (um.isUserRunning(user.id)) { 18095 flags = StorageManager.FLAG_STORAGE_DE; 18096 } else { 18097 continue; 18098 } 18099 18100 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 18101 reconcileAppsData(volumeUuid, user.id, flags); 18102 } 18103 18104 synchronized (mPackages) { 18105 int updateFlags = UPDATE_PERMISSIONS_ALL; 18106 if (ver.sdkVersion != mSdkVersion) { 18107 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18108 + mSdkVersion + "; regranting permissions for " + volumeUuid); 18109 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18110 } 18111 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18112 18113 // Yay, everything is now upgraded 18114 ver.forceCurrent(); 18115 18116 mSettings.writeLPr(); 18117 } 18118 18119 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 18120 sendResourcesChangedBroadcast(true, false, loaded, null); 18121 } 18122 18123 private void unloadPrivatePackages(final VolumeInfo vol) { 18124 mHandler.post(new Runnable() { 18125 @Override 18126 public void run() { 18127 unloadPrivatePackagesInner(vol); 18128 } 18129 }); 18130 } 18131 18132 private void unloadPrivatePackagesInner(VolumeInfo vol) { 18133 final String volumeUuid = vol.fsUuid; 18134 if (TextUtils.isEmpty(volumeUuid)) { 18135 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 18136 return; 18137 } 18138 18139 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 18140 synchronized (mInstallLock) { 18141 synchronized (mPackages) { 18142 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 18143 for (PackageSetting ps : packages) { 18144 if (ps.pkg == null) continue; 18145 18146 final ApplicationInfo info = ps.pkg.applicationInfo; 18147 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18148 if (deletePackageLI(ps.name, null, false, null, 18149 PackageManager.DELETE_KEEP_DATA, outInfo, false, null)) { 18150 unloaded.add(info); 18151 } else { 18152 Slog.w(TAG, "Failed to unload " + ps.codePath); 18153 } 18154 } 18155 18156 mSettings.writeLPr(); 18157 } 18158 } 18159 18160 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 18161 sendResourcesChangedBroadcast(false, false, unloaded, null); 18162 } 18163 18164 /** 18165 * Examine all users present on given mounted volume, and destroy data 18166 * belonging to users that are no longer valid, or whose user ID has been 18167 * recycled. 18168 */ 18169 private void reconcileUsers(String volumeUuid) { 18170 // TODO: also reconcile DE directories 18171 final File[] files = FileUtils 18172 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)); 18173 for (File file : files) { 18174 if (!file.isDirectory()) continue; 18175 18176 final int userId; 18177 final UserInfo info; 18178 try { 18179 userId = Integer.parseInt(file.getName()); 18180 info = sUserManager.getUserInfo(userId); 18181 } catch (NumberFormatException e) { 18182 Slog.w(TAG, "Invalid user directory " + file); 18183 continue; 18184 } 18185 18186 boolean destroyUser = false; 18187 if (info == null) { 18188 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18189 + " because no matching user was found"); 18190 destroyUser = true; 18191 } else { 18192 try { 18193 UserManagerService.enforceSerialNumber(file, info.serialNumber); 18194 } catch (IOException e) { 18195 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18196 + " because we failed to enforce serial number: " + e); 18197 destroyUser = true; 18198 } 18199 } 18200 18201 if (destroyUser) { 18202 synchronized (mInstallLock) { 18203 try { 18204 mInstaller.removeUserDataDirs(volumeUuid, userId); 18205 } catch (InstallerException e) { 18206 Slog.w(TAG, "Failed to clean up user dirs", e); 18207 } 18208 } 18209 } 18210 } 18211 } 18212 18213 private void assertPackageKnown(String volumeUuid, String packageName) 18214 throws PackageManagerException { 18215 synchronized (mPackages) { 18216 final PackageSetting ps = mSettings.mPackages.get(packageName); 18217 if (ps == null) { 18218 throw new PackageManagerException("Package " + packageName + " is unknown"); 18219 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18220 throw new PackageManagerException( 18221 "Package " + packageName + " found on unknown volume " + volumeUuid 18222 + "; expected volume " + ps.volumeUuid); 18223 } 18224 } 18225 } 18226 18227 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 18228 throws PackageManagerException { 18229 synchronized (mPackages) { 18230 final PackageSetting ps = mSettings.mPackages.get(packageName); 18231 if (ps == null) { 18232 throw new PackageManagerException("Package " + packageName + " is unknown"); 18233 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18234 throw new PackageManagerException( 18235 "Package " + packageName + " found on unknown volume " + volumeUuid 18236 + "; expected volume " + ps.volumeUuid); 18237 } else if (!ps.getInstalled(userId)) { 18238 throw new PackageManagerException( 18239 "Package " + packageName + " not installed for user " + userId); 18240 } 18241 } 18242 } 18243 18244 /** 18245 * Examine all apps present on given mounted volume, and destroy apps that 18246 * aren't expected, either due to uninstallation or reinstallation on 18247 * another volume. 18248 */ 18249 private void reconcileApps(String volumeUuid) { 18250 final File[] files = FileUtils 18251 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 18252 for (File file : files) { 18253 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 18254 && !PackageInstallerService.isStageName(file.getName()); 18255 if (!isPackage) { 18256 // Ignore entries which are not packages 18257 continue; 18258 } 18259 18260 try { 18261 final PackageLite pkg = PackageParser.parsePackageLite(file, 18262 PackageParser.PARSE_MUST_BE_APK); 18263 assertPackageKnown(volumeUuid, pkg.packageName); 18264 18265 } catch (PackageParserException | PackageManagerException e) { 18266 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18267 synchronized (mInstallLock) { 18268 removeCodePathLI(file); 18269 } 18270 } 18271 } 18272 } 18273 18274 /** 18275 * Reconcile all app data for the given user. 18276 * <p> 18277 * Verifies that directories exist and that ownership and labeling is 18278 * correct for all installed apps on all mounted volumes. 18279 */ 18280 void reconcileAppsData(int userId, int flags) { 18281 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18282 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18283 final String volumeUuid = vol.getFsUuid(); 18284 reconcileAppsData(volumeUuid, userId, flags); 18285 } 18286 } 18287 18288 /** 18289 * Reconcile all app data on given mounted volume. 18290 * <p> 18291 * Destroys app data that isn't expected, either due to uninstallation or 18292 * reinstallation on another volume. 18293 * <p> 18294 * Verifies that directories exist and that ownership and labeling is 18295 * correct for all installed apps. 18296 */ 18297 private void reconcileAppsData(String volumeUuid, int userId, int flags) { 18298 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 18299 + Integer.toHexString(flags)); 18300 18301 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 18302 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 18303 18304 boolean restoreconNeeded = false; 18305 18306 // First look for stale data that doesn't belong, and check if things 18307 // have changed since we did our last restorecon 18308 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18309 if (!isUserKeyUnlocked(userId)) { 18310 throw new RuntimeException( 18311 "Yikes, someone asked us to reconcile CE storage while " + userId 18312 + " was still locked; this would have caused massive data loss!"); 18313 } 18314 18315 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 18316 18317 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 18318 for (File file : files) { 18319 final String packageName = file.getName(); 18320 try { 18321 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18322 } catch (PackageManagerException e) { 18323 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18324 synchronized (mInstallLock) { 18325 destroyAppDataLI(volumeUuid, packageName, userId, 18326 StorageManager.FLAG_STORAGE_CE); 18327 } 18328 } 18329 } 18330 } 18331 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18332 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 18333 18334 final File[] files = FileUtils.listFilesOrEmpty(deDir); 18335 for (File file : files) { 18336 final String packageName = file.getName(); 18337 try { 18338 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18339 } catch (PackageManagerException e) { 18340 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18341 synchronized (mInstallLock) { 18342 destroyAppDataLI(volumeUuid, packageName, userId, 18343 StorageManager.FLAG_STORAGE_DE); 18344 } 18345 } 18346 } 18347 } 18348 18349 // Ensure that data directories are ready to roll for all packages 18350 // installed for this volume and user 18351 final List<PackageSetting> packages; 18352 synchronized (mPackages) { 18353 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18354 } 18355 int preparedCount = 0; 18356 for (PackageSetting ps : packages) { 18357 final String packageName = ps.name; 18358 if (ps.pkg == null) { 18359 Slog.w(TAG, "Odd, missing scanned package " + packageName); 18360 // TODO: might be due to legacy ASEC apps; we should circle back 18361 // and reconcile again once they're scanned 18362 continue; 18363 } 18364 18365 if (ps.getInstalled(userId)) { 18366 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 18367 18368 if (maybeMigrateAppData(volumeUuid, userId, ps.pkg)) { 18369 // We may have just shuffled around app data directories, so 18370 // prepare them one more time 18371 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 18372 } 18373 18374 preparedCount++; 18375 } 18376 } 18377 18378 if (restoreconNeeded) { 18379 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18380 SELinuxMMAC.setRestoreconDone(ceDir); 18381 } 18382 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18383 SELinuxMMAC.setRestoreconDone(deDir); 18384 } 18385 } 18386 18387 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 18388 + " packages; restoreconNeeded was " + restoreconNeeded); 18389 } 18390 18391 /** 18392 * Prepare app data for the given app just after it was installed or 18393 * upgraded. This method carefully only touches users that it's installed 18394 * for, and it forces a restorecon to handle any seinfo changes. 18395 * <p> 18396 * Verifies that directories exist and that ownership and labeling is 18397 * correct for all installed apps. If there is an ownership mismatch, it 18398 * will try recovering system apps by wiping data; third-party app data is 18399 * left intact. 18400 * <p> 18401 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 18402 */ 18403 private void prepareAppDataAfterInstall(PackageParser.Package pkg) { 18404 prepareAppDataAfterInstallInternal(pkg); 18405 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 18406 for (int i = 0; i < childCount; i++) { 18407 PackageParser.Package childPackage = pkg.childPackages.get(i); 18408 prepareAppDataAfterInstallInternal(childPackage); 18409 } 18410 } 18411 18412 private void prepareAppDataAfterInstallInternal(PackageParser.Package pkg) { 18413 final PackageSetting ps; 18414 synchronized (mPackages) { 18415 ps = mSettings.mPackages.get(pkg.packageName); 18416 mSettings.writeKernelMappingLPr(ps); 18417 } 18418 18419 final UserManager um = mContext.getSystemService(UserManager.class); 18420 for (UserInfo user : um.getUsers()) { 18421 final int flags; 18422 if (um.isUserUnlocked(user.id)) { 18423 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18424 } else if (um.isUserRunning(user.id)) { 18425 flags = StorageManager.FLAG_STORAGE_DE; 18426 } else { 18427 continue; 18428 } 18429 18430 if (ps.getInstalled(user.id)) { 18431 // Whenever an app changes, force a restorecon of its data 18432 // TODO: when user data is locked, mark that we're still dirty 18433 prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true); 18434 } 18435 } 18436 } 18437 18438 /** 18439 * Prepare app data for the given app. 18440 * <p> 18441 * Verifies that directories exist and that ownership and labeling is 18442 * correct for all installed apps. If there is an ownership mismatch, this 18443 * will try recovering system apps by wiping data; third-party app data is 18444 * left intact. 18445 */ 18446 private void prepareAppData(String volumeUuid, int userId, int flags, 18447 PackageParser.Package pkg, boolean restoreconNeeded) { 18448 if (DEBUG_APP_DATA) { 18449 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 18450 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 18451 } 18452 18453 final String packageName = pkg.packageName; 18454 final ApplicationInfo app = pkg.applicationInfo; 18455 final int appId = UserHandle.getAppId(app.uid); 18456 18457 Preconditions.checkNotNull(app.seinfo); 18458 18459 synchronized (mInstallLock) { 18460 try { 18461 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18462 appId, app.seinfo, app.targetSdkVersion); 18463 } catch (InstallerException e) { 18464 if (app.isSystemApp()) { 18465 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 18466 + ", but trying to recover: " + e); 18467 destroyAppDataLI(volumeUuid, packageName, userId, flags); 18468 try { 18469 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18470 appId, app.seinfo, app.targetSdkVersion); 18471 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 18472 } catch (InstallerException e2) { 18473 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 18474 } 18475 } else { 18476 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 18477 } 18478 } 18479 18480 if (restoreconNeeded) { 18481 restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo); 18482 } 18483 18484 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18485 // Create a native library symlink only if we have native libraries 18486 // and if the native libraries are 32 bit libraries. We do not provide 18487 // this symlink for 64 bit libraries. 18488 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 18489 final String nativeLibPath = app.nativeLibraryDir; 18490 try { 18491 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 18492 nativeLibPath, userId); 18493 } catch (InstallerException e) { 18494 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 18495 } 18496 } 18497 } 18498 } 18499 } 18500 18501 /** 18502 * For system apps on non-FBE devices, this method migrates any existing 18503 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 18504 * requested by the app. 18505 */ 18506 private boolean maybeMigrateAppData(String volumeUuid, int userId, PackageParser.Package pkg) { 18507 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 18508 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 18509 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 18510 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 18511 synchronized (mInstallLock) { 18512 try { 18513 mInstaller.migrateAppData(volumeUuid, pkg.packageName, userId, storageTarget); 18514 } catch (InstallerException e) { 18515 logCriticalInfo(Log.WARN, 18516 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 18517 } 18518 } 18519 return true; 18520 } else { 18521 return false; 18522 } 18523 } 18524 18525 private void unfreezePackage(String packageName) { 18526 synchronized (mPackages) { 18527 final PackageSetting ps = mSettings.mPackages.get(packageName); 18528 if (ps != null) { 18529 ps.frozen = false; 18530 } 18531 } 18532 } 18533 18534 @Override 18535 public int movePackage(final String packageName, final String volumeUuid) { 18536 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 18537 18538 final int moveId = mNextMoveId.getAndIncrement(); 18539 mHandler.post(new Runnable() { 18540 @Override 18541 public void run() { 18542 try { 18543 movePackageInternal(packageName, volumeUuid, moveId); 18544 } catch (PackageManagerException e) { 18545 Slog.w(TAG, "Failed to move " + packageName, e); 18546 mMoveCallbacks.notifyStatusChanged(moveId, 18547 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 18548 } 18549 } 18550 }); 18551 return moveId; 18552 } 18553 18554 private void movePackageInternal(final String packageName, final String volumeUuid, 18555 final int moveId) throws PackageManagerException { 18556 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 18557 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18558 final PackageManager pm = mContext.getPackageManager(); 18559 18560 final boolean currentAsec; 18561 final String currentVolumeUuid; 18562 final File codeFile; 18563 final String installerPackageName; 18564 final String packageAbiOverride; 18565 final int appId; 18566 final String seinfo; 18567 final String label; 18568 final int targetSdkVersion; 18569 18570 // reader 18571 synchronized (mPackages) { 18572 final PackageParser.Package pkg = mPackages.get(packageName); 18573 final PackageSetting ps = mSettings.mPackages.get(packageName); 18574 if (pkg == null || ps == null) { 18575 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 18576 } 18577 18578 if (pkg.applicationInfo.isSystemApp()) { 18579 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 18580 "Cannot move system application"); 18581 } 18582 18583 if (pkg.applicationInfo.isExternalAsec()) { 18584 currentAsec = true; 18585 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 18586 } else if (pkg.applicationInfo.isForwardLocked()) { 18587 currentAsec = true; 18588 currentVolumeUuid = "forward_locked"; 18589 } else { 18590 currentAsec = false; 18591 currentVolumeUuid = ps.volumeUuid; 18592 18593 final File probe = new File(pkg.codePath); 18594 final File probeOat = new File(probe, "oat"); 18595 if (!probe.isDirectory() || !probeOat.isDirectory()) { 18596 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18597 "Move only supported for modern cluster style installs"); 18598 } 18599 } 18600 18601 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 18602 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18603 "Package already moved to " + volumeUuid); 18604 } 18605 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 18606 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 18607 "Device admin cannot be moved"); 18608 } 18609 18610 if (ps.frozen) { 18611 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 18612 "Failed to move already frozen package"); 18613 } 18614 ps.frozen = true; 18615 18616 codeFile = new File(pkg.codePath); 18617 installerPackageName = ps.installerPackageName; 18618 packageAbiOverride = ps.cpuAbiOverrideString; 18619 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18620 seinfo = pkg.applicationInfo.seinfo; 18621 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 18622 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 18623 } 18624 18625 // Now that we're guarded by frozen state, kill app during move 18626 final long token = Binder.clearCallingIdentity(); 18627 try { 18628 killApplication(packageName, appId, "move pkg"); 18629 } finally { 18630 Binder.restoreCallingIdentity(token); 18631 } 18632 18633 final Bundle extras = new Bundle(); 18634 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 18635 extras.putString(Intent.EXTRA_TITLE, label); 18636 mMoveCallbacks.notifyCreated(moveId, extras); 18637 18638 int installFlags; 18639 final boolean moveCompleteApp; 18640 final File measurePath; 18641 18642 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 18643 installFlags = INSTALL_INTERNAL; 18644 moveCompleteApp = !currentAsec; 18645 measurePath = Environment.getDataAppDirectory(volumeUuid); 18646 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 18647 installFlags = INSTALL_EXTERNAL; 18648 moveCompleteApp = false; 18649 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 18650 } else { 18651 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 18652 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 18653 || !volume.isMountedWritable()) { 18654 unfreezePackage(packageName); 18655 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18656 "Move location not mounted private volume"); 18657 } 18658 18659 Preconditions.checkState(!currentAsec); 18660 18661 installFlags = INSTALL_INTERNAL; 18662 moveCompleteApp = true; 18663 measurePath = Environment.getDataAppDirectory(volumeUuid); 18664 } 18665 18666 final PackageStats stats = new PackageStats(null, -1); 18667 synchronized (mInstaller) { 18668 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 18669 unfreezePackage(packageName); 18670 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18671 "Failed to measure package size"); 18672 } 18673 } 18674 18675 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 18676 + stats.dataSize); 18677 18678 final long startFreeBytes = measurePath.getFreeSpace(); 18679 final long sizeBytes; 18680 if (moveCompleteApp) { 18681 sizeBytes = stats.codeSize + stats.dataSize; 18682 } else { 18683 sizeBytes = stats.codeSize; 18684 } 18685 18686 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 18687 unfreezePackage(packageName); 18688 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18689 "Not enough free space to move"); 18690 } 18691 18692 mMoveCallbacks.notifyStatusChanged(moveId, 10); 18693 18694 final CountDownLatch installedLatch = new CountDownLatch(1); 18695 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 18696 @Override 18697 public void onUserActionRequired(Intent intent) throws RemoteException { 18698 throw new IllegalStateException(); 18699 } 18700 18701 @Override 18702 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 18703 Bundle extras) throws RemoteException { 18704 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 18705 + PackageManager.installStatusToString(returnCode, msg)); 18706 18707 installedLatch.countDown(); 18708 18709 // Regardless of success or failure of the move operation, 18710 // always unfreeze the package 18711 unfreezePackage(packageName); 18712 18713 final int status = PackageManager.installStatusToPublicStatus(returnCode); 18714 switch (status) { 18715 case PackageInstaller.STATUS_SUCCESS: 18716 mMoveCallbacks.notifyStatusChanged(moveId, 18717 PackageManager.MOVE_SUCCEEDED); 18718 break; 18719 case PackageInstaller.STATUS_FAILURE_STORAGE: 18720 mMoveCallbacks.notifyStatusChanged(moveId, 18721 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 18722 break; 18723 default: 18724 mMoveCallbacks.notifyStatusChanged(moveId, 18725 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 18726 break; 18727 } 18728 } 18729 }; 18730 18731 final MoveInfo move; 18732 if (moveCompleteApp) { 18733 // Kick off a thread to report progress estimates 18734 new Thread() { 18735 @Override 18736 public void run() { 18737 while (true) { 18738 try { 18739 if (installedLatch.await(1, TimeUnit.SECONDS)) { 18740 break; 18741 } 18742 } catch (InterruptedException ignored) { 18743 } 18744 18745 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 18746 final int progress = 10 + (int) MathUtils.constrain( 18747 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 18748 mMoveCallbacks.notifyStatusChanged(moveId, progress); 18749 } 18750 } 18751 }.start(); 18752 18753 final String dataAppName = codeFile.getName(); 18754 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 18755 dataAppName, appId, seinfo, targetSdkVersion); 18756 } else { 18757 move = null; 18758 } 18759 18760 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 18761 18762 final Message msg = mHandler.obtainMessage(INIT_COPY); 18763 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 18764 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 18765 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 18766 packageAbiOverride, null); 18767 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 18768 msg.obj = params; 18769 18770 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 18771 System.identityHashCode(msg.obj)); 18772 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 18773 System.identityHashCode(msg.obj)); 18774 18775 mHandler.sendMessage(msg); 18776 } 18777 18778 @Override 18779 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 18780 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 18781 18782 final int realMoveId = mNextMoveId.getAndIncrement(); 18783 final Bundle extras = new Bundle(); 18784 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 18785 mMoveCallbacks.notifyCreated(realMoveId, extras); 18786 18787 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 18788 @Override 18789 public void onCreated(int moveId, Bundle extras) { 18790 // Ignored 18791 } 18792 18793 @Override 18794 public void onStatusChanged(int moveId, int status, long estMillis) { 18795 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 18796 } 18797 }; 18798 18799 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18800 storage.setPrimaryStorageUuid(volumeUuid, callback); 18801 return realMoveId; 18802 } 18803 18804 @Override 18805 public int getMoveStatus(int moveId) { 18806 mContext.enforceCallingOrSelfPermission( 18807 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18808 return mMoveCallbacks.mLastStatus.get(moveId); 18809 } 18810 18811 @Override 18812 public void registerMoveCallback(IPackageMoveObserver callback) { 18813 mContext.enforceCallingOrSelfPermission( 18814 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18815 mMoveCallbacks.register(callback); 18816 } 18817 18818 @Override 18819 public void unregisterMoveCallback(IPackageMoveObserver callback) { 18820 mContext.enforceCallingOrSelfPermission( 18821 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18822 mMoveCallbacks.unregister(callback); 18823 } 18824 18825 @Override 18826 public boolean setInstallLocation(int loc) { 18827 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 18828 null); 18829 if (getInstallLocation() == loc) { 18830 return true; 18831 } 18832 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 18833 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 18834 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 18835 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 18836 return true; 18837 } 18838 return false; 18839 } 18840 18841 @Override 18842 public int getInstallLocation() { 18843 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 18844 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 18845 PackageHelper.APP_INSTALL_AUTO); 18846 } 18847 18848 /** Called by UserManagerService */ 18849 void cleanUpUser(UserManagerService userManager, int userHandle) { 18850 synchronized (mPackages) { 18851 mDirtyUsers.remove(userHandle); 18852 mUserNeedsBadging.delete(userHandle); 18853 mSettings.removeUserLPw(userHandle); 18854 mPendingBroadcasts.remove(userHandle); 18855 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 18856 } 18857 synchronized (mInstallLock) { 18858 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18859 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18860 final String volumeUuid = vol.getFsUuid(); 18861 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 18862 try { 18863 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 18864 } catch (InstallerException e) { 18865 Slog.w(TAG, "Failed to remove user data", e); 18866 } 18867 } 18868 synchronized (mPackages) { 18869 removeUnusedPackagesLILPw(userManager, userHandle); 18870 } 18871 } 18872 } 18873 18874 /** 18875 * We're removing userHandle and would like to remove any downloaded packages 18876 * that are no longer in use by any other user. 18877 * @param userHandle the user being removed 18878 */ 18879 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 18880 final boolean DEBUG_CLEAN_APKS = false; 18881 int [] users = userManager.getUserIds(); 18882 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 18883 while (psit.hasNext()) { 18884 PackageSetting ps = psit.next(); 18885 if (ps.pkg == null) { 18886 continue; 18887 } 18888 final String packageName = ps.pkg.packageName; 18889 // Skip over if system app 18890 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 18891 continue; 18892 } 18893 if (DEBUG_CLEAN_APKS) { 18894 Slog.i(TAG, "Checking package " + packageName); 18895 } 18896 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 18897 if (keep) { 18898 if (DEBUG_CLEAN_APKS) { 18899 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 18900 } 18901 } else { 18902 for (int i = 0; i < users.length; i++) { 18903 if (users[i] != userHandle && ps.getInstalled(users[i])) { 18904 keep = true; 18905 if (DEBUG_CLEAN_APKS) { 18906 Slog.i(TAG, " Keeping package " + packageName + " for user " 18907 + users[i]); 18908 } 18909 break; 18910 } 18911 } 18912 } 18913 if (!keep) { 18914 if (DEBUG_CLEAN_APKS) { 18915 Slog.i(TAG, " Removing package " + packageName); 18916 } 18917 mHandler.post(new Runnable() { 18918 public void run() { 18919 deletePackageX(packageName, userHandle, 0); 18920 } //end run 18921 }); 18922 } 18923 } 18924 } 18925 18926 /** Called by UserManagerService */ 18927 void createNewUser(int userHandle) { 18928 synchronized (mInstallLock) { 18929 try { 18930 mInstaller.createUserConfig(userHandle); 18931 } catch (InstallerException e) { 18932 Slog.w(TAG, "Failed to create user config", e); 18933 } 18934 mSettings.createNewUserLI(this, mInstaller, userHandle); 18935 } 18936 synchronized (mPackages) { 18937 applyFactoryDefaultBrowserLPw(userHandle); 18938 primeDomainVerificationsLPw(userHandle); 18939 } 18940 } 18941 18942 void newUserCreated(final int userHandle) { 18943 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 18944 // If permission review for legacy apps is required, we represent 18945 // dagerous permissions for such apps as always granted runtime 18946 // permissions to keep per user flag state whether review is needed. 18947 // Hence, if a new user is added we have to propagate dangerous 18948 // permission grants for these legacy apps. 18949 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 18950 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 18951 | UPDATE_PERMISSIONS_REPLACE_ALL); 18952 } 18953 } 18954 18955 @Override 18956 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 18957 mContext.enforceCallingOrSelfPermission( 18958 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 18959 "Only package verification agents can read the verifier device identity"); 18960 18961 synchronized (mPackages) { 18962 return mSettings.getVerifierDeviceIdentityLPw(); 18963 } 18964 } 18965 18966 @Override 18967 public void setPermissionEnforced(String permission, boolean enforced) { 18968 // TODO: Now that we no longer change GID for storage, this should to away. 18969 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 18970 "setPermissionEnforced"); 18971 if (READ_EXTERNAL_STORAGE.equals(permission)) { 18972 synchronized (mPackages) { 18973 if (mSettings.mReadExternalStorageEnforced == null 18974 || mSettings.mReadExternalStorageEnforced != enforced) { 18975 mSettings.mReadExternalStorageEnforced = enforced; 18976 mSettings.writeLPr(); 18977 } 18978 } 18979 // kill any non-foreground processes so we restart them and 18980 // grant/revoke the GID. 18981 final IActivityManager am = ActivityManagerNative.getDefault(); 18982 if (am != null) { 18983 final long token = Binder.clearCallingIdentity(); 18984 try { 18985 am.killProcessesBelowForeground("setPermissionEnforcement"); 18986 } catch (RemoteException e) { 18987 } finally { 18988 Binder.restoreCallingIdentity(token); 18989 } 18990 } 18991 } else { 18992 throw new IllegalArgumentException("No selective enforcement for " + permission); 18993 } 18994 } 18995 18996 @Override 18997 @Deprecated 18998 public boolean isPermissionEnforced(String permission) { 18999 return true; 19000 } 19001 19002 @Override 19003 public boolean isStorageLow() { 19004 final long token = Binder.clearCallingIdentity(); 19005 try { 19006 final DeviceStorageMonitorInternal 19007 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 19008 if (dsm != null) { 19009 return dsm.isMemoryLow(); 19010 } else { 19011 return false; 19012 } 19013 } finally { 19014 Binder.restoreCallingIdentity(token); 19015 } 19016 } 19017 19018 @Override 19019 public IPackageInstaller getPackageInstaller() { 19020 return mInstallerService; 19021 } 19022 19023 private boolean userNeedsBadging(int userId) { 19024 int index = mUserNeedsBadging.indexOfKey(userId); 19025 if (index < 0) { 19026 final UserInfo userInfo; 19027 final long token = Binder.clearCallingIdentity(); 19028 try { 19029 userInfo = sUserManager.getUserInfo(userId); 19030 } finally { 19031 Binder.restoreCallingIdentity(token); 19032 } 19033 final boolean b; 19034 if (userInfo != null && userInfo.isManagedProfile()) { 19035 b = true; 19036 } else { 19037 b = false; 19038 } 19039 mUserNeedsBadging.put(userId, b); 19040 return b; 19041 } 19042 return mUserNeedsBadging.valueAt(index); 19043 } 19044 19045 @Override 19046 public KeySet getKeySetByAlias(String packageName, String alias) { 19047 if (packageName == null || alias == null) { 19048 return null; 19049 } 19050 synchronized(mPackages) { 19051 final PackageParser.Package pkg = mPackages.get(packageName); 19052 if (pkg == null) { 19053 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19054 throw new IllegalArgumentException("Unknown package: " + packageName); 19055 } 19056 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19057 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 19058 } 19059 } 19060 19061 @Override 19062 public KeySet getSigningKeySet(String packageName) { 19063 if (packageName == null) { 19064 return null; 19065 } 19066 synchronized(mPackages) { 19067 final PackageParser.Package pkg = mPackages.get(packageName); 19068 if (pkg == null) { 19069 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19070 throw new IllegalArgumentException("Unknown package: " + packageName); 19071 } 19072 if (pkg.applicationInfo.uid != Binder.getCallingUid() 19073 && Process.SYSTEM_UID != Binder.getCallingUid()) { 19074 throw new SecurityException("May not access signing KeySet of other apps."); 19075 } 19076 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19077 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 19078 } 19079 } 19080 19081 @Override 19082 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 19083 if (packageName == null || ks == null) { 19084 return false; 19085 } 19086 synchronized(mPackages) { 19087 final PackageParser.Package pkg = mPackages.get(packageName); 19088 if (pkg == null) { 19089 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19090 throw new IllegalArgumentException("Unknown package: " + packageName); 19091 } 19092 IBinder ksh = ks.getToken(); 19093 if (ksh instanceof KeySetHandle) { 19094 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19095 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 19096 } 19097 return false; 19098 } 19099 } 19100 19101 @Override 19102 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 19103 if (packageName == null || ks == null) { 19104 return false; 19105 } 19106 synchronized(mPackages) { 19107 final PackageParser.Package pkg = mPackages.get(packageName); 19108 if (pkg == null) { 19109 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19110 throw new IllegalArgumentException("Unknown package: " + packageName); 19111 } 19112 IBinder ksh = ks.getToken(); 19113 if (ksh instanceof KeySetHandle) { 19114 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19115 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 19116 } 19117 return false; 19118 } 19119 } 19120 19121 private void deletePackageIfUnusedLPr(final String packageName) { 19122 PackageSetting ps = mSettings.mPackages.get(packageName); 19123 if (ps == null) { 19124 return; 19125 } 19126 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 19127 // TODO Implement atomic delete if package is unused 19128 // It is currently possible that the package will be deleted even if it is installed 19129 // after this method returns. 19130 mHandler.post(new Runnable() { 19131 public void run() { 19132 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 19133 } 19134 }); 19135 } 19136 } 19137 19138 /** 19139 * Check and throw if the given before/after packages would be considered a 19140 * downgrade. 19141 */ 19142 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 19143 throws PackageManagerException { 19144 if (after.versionCode < before.mVersionCode) { 19145 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19146 "Update version code " + after.versionCode + " is older than current " 19147 + before.mVersionCode); 19148 } else if (after.versionCode == before.mVersionCode) { 19149 if (after.baseRevisionCode < before.baseRevisionCode) { 19150 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19151 "Update base revision code " + after.baseRevisionCode 19152 + " is older than current " + before.baseRevisionCode); 19153 } 19154 19155 if (!ArrayUtils.isEmpty(after.splitNames)) { 19156 for (int i = 0; i < after.splitNames.length; i++) { 19157 final String splitName = after.splitNames[i]; 19158 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 19159 if (j != -1) { 19160 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 19161 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19162 "Update split " + splitName + " revision code " 19163 + after.splitRevisionCodes[i] + " is older than current " 19164 + before.splitRevisionCodes[j]); 19165 } 19166 } 19167 } 19168 } 19169 } 19170 } 19171 19172 private static class MoveCallbacks extends Handler { 19173 private static final int MSG_CREATED = 1; 19174 private static final int MSG_STATUS_CHANGED = 2; 19175 19176 private final RemoteCallbackList<IPackageMoveObserver> 19177 mCallbacks = new RemoteCallbackList<>(); 19178 19179 private final SparseIntArray mLastStatus = new SparseIntArray(); 19180 19181 public MoveCallbacks(Looper looper) { 19182 super(looper); 19183 } 19184 19185 public void register(IPackageMoveObserver callback) { 19186 mCallbacks.register(callback); 19187 } 19188 19189 public void unregister(IPackageMoveObserver callback) { 19190 mCallbacks.unregister(callback); 19191 } 19192 19193 @Override 19194 public void handleMessage(Message msg) { 19195 final SomeArgs args = (SomeArgs) msg.obj; 19196 final int n = mCallbacks.beginBroadcast(); 19197 for (int i = 0; i < n; i++) { 19198 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 19199 try { 19200 invokeCallback(callback, msg.what, args); 19201 } catch (RemoteException ignored) { 19202 } 19203 } 19204 mCallbacks.finishBroadcast(); 19205 args.recycle(); 19206 } 19207 19208 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 19209 throws RemoteException { 19210 switch (what) { 19211 case MSG_CREATED: { 19212 callback.onCreated(args.argi1, (Bundle) args.arg2); 19213 break; 19214 } 19215 case MSG_STATUS_CHANGED: { 19216 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 19217 break; 19218 } 19219 } 19220 } 19221 19222 private void notifyCreated(int moveId, Bundle extras) { 19223 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 19224 19225 final SomeArgs args = SomeArgs.obtain(); 19226 args.argi1 = moveId; 19227 args.arg2 = extras; 19228 obtainMessage(MSG_CREATED, args).sendToTarget(); 19229 } 19230 19231 private void notifyStatusChanged(int moveId, int status) { 19232 notifyStatusChanged(moveId, status, -1); 19233 } 19234 19235 private void notifyStatusChanged(int moveId, int status, long estMillis) { 19236 Slog.v(TAG, "Move " + moveId + " status " + status); 19237 19238 final SomeArgs args = SomeArgs.obtain(); 19239 args.argi1 = moveId; 19240 args.argi2 = status; 19241 args.arg3 = estMillis; 19242 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 19243 19244 synchronized (mLastStatus) { 19245 mLastStatus.put(moveId, status); 19246 } 19247 } 19248 } 19249 19250 private final static class OnPermissionChangeListeners extends Handler { 19251 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 19252 19253 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 19254 new RemoteCallbackList<>(); 19255 19256 public OnPermissionChangeListeners(Looper looper) { 19257 super(looper); 19258 } 19259 19260 @Override 19261 public void handleMessage(Message msg) { 19262 switch (msg.what) { 19263 case MSG_ON_PERMISSIONS_CHANGED: { 19264 final int uid = msg.arg1; 19265 handleOnPermissionsChanged(uid); 19266 } break; 19267 } 19268 } 19269 19270 public void addListenerLocked(IOnPermissionsChangeListener listener) { 19271 mPermissionListeners.register(listener); 19272 19273 } 19274 19275 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 19276 mPermissionListeners.unregister(listener); 19277 } 19278 19279 public void onPermissionsChanged(int uid) { 19280 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 19281 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 19282 } 19283 } 19284 19285 private void handleOnPermissionsChanged(int uid) { 19286 final int count = mPermissionListeners.beginBroadcast(); 19287 try { 19288 for (int i = 0; i < count; i++) { 19289 IOnPermissionsChangeListener callback = mPermissionListeners 19290 .getBroadcastItem(i); 19291 try { 19292 callback.onPermissionsChanged(uid); 19293 } catch (RemoteException e) { 19294 Log.e(TAG, "Permission listener is dead", e); 19295 } 19296 } 19297 } finally { 19298 mPermissionListeners.finishBroadcast(); 19299 } 19300 } 19301 } 19302 19303 private class PackageManagerInternalImpl extends PackageManagerInternal { 19304 @Override 19305 public void setLocationPackagesProvider(PackagesProvider provider) { 19306 synchronized (mPackages) { 19307 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 19308 } 19309 } 19310 19311 @Override 19312 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 19313 synchronized (mPackages) { 19314 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 19315 } 19316 } 19317 19318 @Override 19319 public void setSmsAppPackagesProvider(PackagesProvider provider) { 19320 synchronized (mPackages) { 19321 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 19322 } 19323 } 19324 19325 @Override 19326 public void setDialerAppPackagesProvider(PackagesProvider provider) { 19327 synchronized (mPackages) { 19328 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 19329 } 19330 } 19331 19332 @Override 19333 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 19334 synchronized (mPackages) { 19335 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 19336 } 19337 } 19338 19339 @Override 19340 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 19341 synchronized (mPackages) { 19342 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 19343 } 19344 } 19345 19346 @Override 19347 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 19348 synchronized (mPackages) { 19349 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 19350 packageName, userId); 19351 } 19352 } 19353 19354 @Override 19355 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 19356 synchronized (mPackages) { 19357 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 19358 packageName, userId); 19359 } 19360 } 19361 19362 @Override 19363 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 19364 synchronized (mPackages) { 19365 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 19366 packageName, userId); 19367 } 19368 } 19369 19370 @Override 19371 public void setKeepUninstalledPackages(final List<String> packageList) { 19372 Preconditions.checkNotNull(packageList); 19373 List<String> removedFromList = null; 19374 synchronized (mPackages) { 19375 if (mKeepUninstalledPackages != null) { 19376 final int packagesCount = mKeepUninstalledPackages.size(); 19377 for (int i = 0; i < packagesCount; i++) { 19378 String oldPackage = mKeepUninstalledPackages.get(i); 19379 if (packageList != null && packageList.contains(oldPackage)) { 19380 continue; 19381 } 19382 if (removedFromList == null) { 19383 removedFromList = new ArrayList<>(); 19384 } 19385 removedFromList.add(oldPackage); 19386 } 19387 } 19388 mKeepUninstalledPackages = new ArrayList<>(packageList); 19389 if (removedFromList != null) { 19390 final int removedCount = removedFromList.size(); 19391 for (int i = 0; i < removedCount; i++) { 19392 deletePackageIfUnusedLPr(removedFromList.get(i)); 19393 } 19394 } 19395 } 19396 } 19397 19398 @Override 19399 public boolean isPermissionsReviewRequired(String packageName, int userId) { 19400 synchronized (mPackages) { 19401 // If we do not support permission review, done. 19402 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 19403 return false; 19404 } 19405 19406 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 19407 if (packageSetting == null) { 19408 return false; 19409 } 19410 19411 // Permission review applies only to apps not supporting the new permission model. 19412 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 19413 return false; 19414 } 19415 19416 // Legacy apps have the permission and get user consent on launch. 19417 PermissionsState permissionsState = packageSetting.getPermissionsState(); 19418 return permissionsState.isPermissionReviewRequired(userId); 19419 } 19420 } 19421 19422 @Override 19423 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 19424 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 19425 } 19426 19427 @Override 19428 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 19429 int userId) { 19430 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 19431 } 19432 } 19433 19434 @Override 19435 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 19436 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 19437 synchronized (mPackages) { 19438 final long identity = Binder.clearCallingIdentity(); 19439 try { 19440 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 19441 packageNames, userId); 19442 } finally { 19443 Binder.restoreCallingIdentity(identity); 19444 } 19445 } 19446 } 19447 19448 private static void enforceSystemOrPhoneCaller(String tag) { 19449 int callingUid = Binder.getCallingUid(); 19450 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 19451 throw new SecurityException( 19452 "Cannot call " + tag + " from UID " + callingUid); 19453 } 19454 } 19455 19456 boolean isHistoricalPackageUsageAvailable() { 19457 return mPackageUsage.isHistoricalPackageUsageAvailable(); 19458 } 19459 19460 /** 19461 * Return a <b>copy</b> of the collection of packages known to the package manager. 19462 * @return A copy of the values of mPackages. 19463 */ 19464 Collection<PackageParser.Package> getPackages() { 19465 synchronized (mPackages) { 19466 return new ArrayList<>(mPackages.values()); 19467 } 19468 } 19469 19470 /** 19471 * Logs process start information (including base APK hash) to the security log. 19472 * @hide 19473 */ 19474 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 19475 String apkFile, int pid) { 19476 if (!SecurityLog.isLoggingEnabled()) { 19477 return; 19478 } 19479 Bundle data = new Bundle(); 19480 data.putLong("startTimestamp", System.currentTimeMillis()); 19481 data.putString("processName", processName); 19482 data.putInt("uid", uid); 19483 data.putString("seinfo", seinfo); 19484 data.putString("apkFile", apkFile); 19485 data.putInt("pid", pid); 19486 Message msg = mProcessLoggingHandler.obtainMessage( 19487 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 19488 msg.setData(data); 19489 mProcessLoggingHandler.sendMessage(msg); 19490 } 19491} 19492