PackageManagerService.java revision c9b329ed8e422d7be0717b41efc2007493d71504
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 35import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 55import static android.content.pm.PackageManager.INSTALL_INTERNAL; 56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 62import static android.content.pm.PackageManager.MATCH_ALL; 63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 67import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 68import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 69import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 70import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 71import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 72import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 73import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 74import static android.content.pm.PackageManager.PERMISSION_DENIED; 75import static android.content.pm.PackageManager.PERMISSION_GRANTED; 76import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 77import static android.content.pm.PackageParser.isApkFile; 78import static android.os.Process.PACKAGE_INFO_GID; 79import static android.os.Process.SYSTEM_UID; 80import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 81import static android.system.OsConstants.O_CREAT; 82import static android.system.OsConstants.O_RDWR; 83 84import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 86import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 87import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 88import static com.android.internal.util.ArrayUtils.appendInt; 89import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 90import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 91import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 93import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 94import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 95import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 97import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 100 101import android.Manifest; 102import android.annotation.NonNull; 103import android.annotation.Nullable; 104import android.app.ActivityManager; 105import android.app.ActivityManagerNative; 106import android.app.IActivityManager; 107import android.app.admin.DevicePolicyManagerInternal; 108import android.app.admin.IDevicePolicyManager; 109import android.app.backup.IBackupManager; 110import android.content.BroadcastReceiver; 111import android.content.ComponentName; 112import android.content.Context; 113import android.content.IIntentReceiver; 114import android.content.Intent; 115import android.content.IntentFilter; 116import android.content.IntentSender; 117import android.content.IntentSender.SendIntentException; 118import android.content.ServiceConnection; 119import android.content.pm.ActivityInfo; 120import android.content.pm.ApplicationInfo; 121import android.content.pm.AppsQueryHelper; 122import android.content.pm.ComponentInfo; 123import android.content.pm.EphemeralApplicationInfo; 124import android.content.pm.EphemeralResolveInfo; 125import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 126import android.content.pm.FeatureInfo; 127import android.content.pm.IOnPermissionsChangeListener; 128import android.content.pm.IPackageDataObserver; 129import android.content.pm.IPackageDeleteObserver; 130import android.content.pm.IPackageDeleteObserver2; 131import android.content.pm.IPackageInstallObserver2; 132import android.content.pm.IPackageInstaller; 133import android.content.pm.IPackageManager; 134import android.content.pm.IPackageMoveObserver; 135import android.content.pm.IPackageStatsObserver; 136import android.content.pm.InstrumentationInfo; 137import android.content.pm.IntentFilterVerificationInfo; 138import android.content.pm.KeySet; 139import android.content.pm.PackageCleanItem; 140import android.content.pm.PackageInfo; 141import android.content.pm.PackageInfoLite; 142import android.content.pm.PackageInstaller; 143import android.content.pm.PackageManager; 144import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 145import android.content.pm.PackageManagerInternal; 146import android.content.pm.PackageParser; 147import android.content.pm.PackageParser.ActivityIntentInfo; 148import android.content.pm.PackageParser.PackageLite; 149import android.content.pm.PackageParser.PackageParserException; 150import android.content.pm.PackageStats; 151import android.content.pm.PackageUserState; 152import android.content.pm.ParceledListSlice; 153import android.content.pm.PermissionGroupInfo; 154import android.content.pm.PermissionInfo; 155import android.content.pm.ProviderInfo; 156import android.content.pm.ResolveInfo; 157import android.content.pm.ServiceInfo; 158import android.content.pm.Signature; 159import android.content.pm.UserInfo; 160import android.content.pm.VerifierDeviceIdentity; 161import android.content.pm.VerifierInfo; 162import android.content.res.Resources; 163import android.graphics.Bitmap; 164import android.hardware.display.DisplayManager; 165import android.net.Uri; 166import android.os.Binder; 167import android.os.Build; 168import android.os.Bundle; 169import android.os.Debug; 170import android.os.Environment; 171import android.os.Environment.UserEnvironment; 172import android.os.FileUtils; 173import android.os.Handler; 174import android.os.IBinder; 175import android.os.Looper; 176import android.os.Message; 177import android.os.Parcel; 178import android.os.ParcelFileDescriptor; 179import android.os.Process; 180import android.os.RemoteCallbackList; 181import android.os.RemoteException; 182import android.os.ResultReceiver; 183import android.os.SELinux; 184import android.os.ServiceManager; 185import android.os.SystemClock; 186import android.os.SystemProperties; 187import android.os.Trace; 188import android.os.UserHandle; 189import android.os.UserManager; 190import android.os.storage.IMountService; 191import android.os.storage.MountServiceInternal; 192import android.os.storage.StorageEventListener; 193import android.os.storage.StorageManager; 194import android.os.storage.VolumeInfo; 195import android.os.storage.VolumeRecord; 196import android.security.KeyStore; 197import android.security.SystemKeyStore; 198import android.system.ErrnoException; 199import android.system.Os; 200import android.text.TextUtils; 201import android.text.format.DateUtils; 202import android.util.ArrayMap; 203import android.util.ArraySet; 204import android.util.AtomicFile; 205import android.util.DisplayMetrics; 206import android.util.EventLog; 207import android.util.ExceptionUtils; 208import android.util.Log; 209import android.util.LogPrinter; 210import android.util.MathUtils; 211import android.util.PrintStreamPrinter; 212import android.util.Slog; 213import android.util.SparseArray; 214import android.util.SparseBooleanArray; 215import android.util.SparseIntArray; 216import android.util.Xml; 217import android.view.Display; 218 219import com.android.internal.R; 220import com.android.internal.annotations.GuardedBy; 221import com.android.internal.app.IMediaContainerService; 222import com.android.internal.app.ResolverActivity; 223import com.android.internal.content.NativeLibraryHelper; 224import com.android.internal.content.PackageHelper; 225import com.android.internal.os.IParcelFileDescriptorFactory; 226import com.android.internal.os.InstallerConnection.InstallerException; 227import com.android.internal.os.SomeArgs; 228import com.android.internal.os.Zygote; 229import com.android.internal.util.ArrayUtils; 230import com.android.internal.util.FastPrintWriter; 231import com.android.internal.util.FastXmlSerializer; 232import com.android.internal.util.IndentingPrintWriter; 233import com.android.internal.util.Preconditions; 234import com.android.internal.util.XmlUtils; 235import com.android.server.EventLogTags; 236import com.android.server.FgThread; 237import com.android.server.IntentResolver; 238import com.android.server.LocalServices; 239import com.android.server.ServiceThread; 240import com.android.server.SystemConfig; 241import com.android.server.Watchdog; 242import com.android.server.pm.PermissionsState.PermissionState; 243import com.android.server.pm.Settings.DatabaseVersion; 244import com.android.server.pm.Settings.VersionInfo; 245import com.android.server.storage.DeviceStorageMonitorInternal; 246 247import dalvik.system.DexFile; 248import dalvik.system.VMRuntime; 249 250import libcore.io.IoUtils; 251import libcore.util.EmptyArray; 252 253import org.xmlpull.v1.XmlPullParser; 254import org.xmlpull.v1.XmlPullParserException; 255import org.xmlpull.v1.XmlSerializer; 256 257import java.io.BufferedInputStream; 258import java.io.BufferedOutputStream; 259import java.io.BufferedReader; 260import java.io.ByteArrayInputStream; 261import java.io.ByteArrayOutputStream; 262import java.io.File; 263import java.io.FileDescriptor; 264import java.io.FileNotFoundException; 265import java.io.FileOutputStream; 266import java.io.FileReader; 267import java.io.FilenameFilter; 268import java.io.IOException; 269import java.io.InputStream; 270import java.io.PrintWriter; 271import java.nio.charset.StandardCharsets; 272import java.security.MessageDigest; 273import java.security.NoSuchAlgorithmException; 274import java.security.PublicKey; 275import java.security.cert.CertificateEncodingException; 276import java.security.cert.CertificateException; 277import java.text.SimpleDateFormat; 278import java.util.ArrayList; 279import java.util.Arrays; 280import java.util.Collection; 281import java.util.Collections; 282import java.util.Comparator; 283import java.util.Date; 284import java.util.HashSet; 285import java.util.Iterator; 286import java.util.List; 287import java.util.Map; 288import java.util.Objects; 289import java.util.Set; 290import java.util.concurrent.CountDownLatch; 291import java.util.concurrent.TimeUnit; 292import java.util.concurrent.atomic.AtomicBoolean; 293import java.util.concurrent.atomic.AtomicInteger; 294import java.util.concurrent.atomic.AtomicLong; 295 296/** 297 * Keep track of all those .apks everywhere. 298 * 299 * This is very central to the platform's security; please run the unit 300 * tests whenever making modifications here: 301 * 302runtest -c android.content.pm.PackageManagerTests frameworks-core 303 * 304 * {@hide} 305 */ 306public class PackageManagerService extends IPackageManager.Stub { 307 static final String TAG = "PackageManager"; 308 static final boolean DEBUG_SETTINGS = false; 309 static final boolean DEBUG_PREFERRED = false; 310 static final boolean DEBUG_UPGRADE = false; 311 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 312 private static final boolean DEBUG_BACKUP = false; 313 private static final boolean DEBUG_INSTALL = false; 314 private static final boolean DEBUG_REMOVE = false; 315 private static final boolean DEBUG_BROADCASTS = false; 316 private static final boolean DEBUG_SHOW_INFO = false; 317 private static final boolean DEBUG_PACKAGE_INFO = false; 318 private static final boolean DEBUG_INTENT_MATCHING = false; 319 private static final boolean DEBUG_PACKAGE_SCANNING = false; 320 private static final boolean DEBUG_VERIFY = false; 321 322 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 323 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 324 // user, but by default initialize to this. 325 static final boolean DEBUG_DEXOPT = false; 326 327 private static final boolean DEBUG_ABI_SELECTION = false; 328 private static final boolean DEBUG_EPHEMERAL = false; 329 private static final boolean DEBUG_TRIAGED_MISSING = false; 330 private static final boolean DEBUG_APP_DATA = false; 331 332 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 333 334 private static final boolean DISABLE_EPHEMERAL_APPS = true; 335 336 private static final int RADIO_UID = Process.PHONE_UID; 337 private static final int LOG_UID = Process.LOG_UID; 338 private static final int NFC_UID = Process.NFC_UID; 339 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 340 private static final int SHELL_UID = Process.SHELL_UID; 341 342 // Cap the size of permission trees that 3rd party apps can define 343 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 344 345 // Suffix used during package installation when copying/moving 346 // package apks to install directory. 347 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 348 349 static final int SCAN_NO_DEX = 1<<1; 350 static final int SCAN_FORCE_DEX = 1<<2; 351 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 352 static final int SCAN_NEW_INSTALL = 1<<4; 353 static final int SCAN_NO_PATHS = 1<<5; 354 static final int SCAN_UPDATE_TIME = 1<<6; 355 static final int SCAN_DEFER_DEX = 1<<7; 356 static final int SCAN_BOOTING = 1<<8; 357 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 358 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 359 static final int SCAN_REPLACING = 1<<11; 360 static final int SCAN_REQUIRE_KNOWN = 1<<12; 361 static final int SCAN_MOVE = 1<<13; 362 static final int SCAN_INITIAL = 1<<14; 363 static final int SCAN_CHECK_ONLY = 1<<15; 364 static final int SCAN_DONT_KILL_APP = 1<<17; 365 366 static final int REMOVE_CHATTY = 1<<16; 367 368 private static final int[] EMPTY_INT_ARRAY = new int[0]; 369 370 /** 371 * Timeout (in milliseconds) after which the watchdog should declare that 372 * our handler thread is wedged. The usual default for such things is one 373 * minute but we sometimes do very lengthy I/O operations on this thread, 374 * such as installing multi-gigabyte applications, so ours needs to be longer. 375 */ 376 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 377 378 /** 379 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 380 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 381 * settings entry if available, otherwise we use the hardcoded default. If it's been 382 * more than this long since the last fstrim, we force one during the boot sequence. 383 * 384 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 385 * one gets run at the next available charging+idle time. This final mandatory 386 * no-fstrim check kicks in only of the other scheduling criteria is never met. 387 */ 388 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 389 390 /** 391 * Whether verification is enabled by default. 392 */ 393 private static final boolean DEFAULT_VERIFY_ENABLE = true; 394 395 /** 396 * The default maximum time to wait for the verification agent to return in 397 * milliseconds. 398 */ 399 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 400 401 /** 402 * The default response for package verification timeout. 403 * 404 * This can be either PackageManager.VERIFICATION_ALLOW or 405 * PackageManager.VERIFICATION_REJECT. 406 */ 407 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 408 409 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 410 411 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 412 DEFAULT_CONTAINER_PACKAGE, 413 "com.android.defcontainer.DefaultContainerService"); 414 415 private static final String KILL_APP_REASON_GIDS_CHANGED = 416 "permission grant or revoke changed gids"; 417 418 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 419 "permissions revoked"; 420 421 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 422 423 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 424 425 /** Permission grant: not grant the permission. */ 426 private static final int GRANT_DENIED = 1; 427 428 /** Permission grant: grant the permission as an install permission. */ 429 private static final int GRANT_INSTALL = 2; 430 431 /** Permission grant: grant the permission as a runtime one. */ 432 private static final int GRANT_RUNTIME = 3; 433 434 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 435 private static final int GRANT_UPGRADE = 4; 436 437 /** Canonical intent used to identify what counts as a "web browser" app */ 438 private static final Intent sBrowserIntent; 439 static { 440 sBrowserIntent = new Intent(); 441 sBrowserIntent.setAction(Intent.ACTION_VIEW); 442 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 443 sBrowserIntent.setData(Uri.parse("http:")); 444 } 445 446 // Compilation reasons. 447 public static final int REASON_BOOT = 0; 448 public static final int REASON_INSTALL = 1; 449 public static final int REASON_BACKGROUND_DEXOPT = 2; 450 public static final int REASON_AB_OTA = 3; 451 public static final int REASON_NON_SYSTEM_LIBRARY = 4; 452 public static final int REASON_SHARED_APK = 5; 453 public static final int REASON_FORCED_DEXOPT = 6; 454 455 public static final int REASON_LAST = REASON_FORCED_DEXOPT; 456 457 final ServiceThread mHandlerThread; 458 459 final PackageHandler mHandler; 460 461 /** 462 * Messages for {@link #mHandler} that need to wait for system ready before 463 * being dispatched. 464 */ 465 private ArrayList<Message> mPostSystemReadyMessages; 466 467 final int mSdkVersion = Build.VERSION.SDK_INT; 468 469 final Context mContext; 470 final boolean mFactoryTest; 471 final boolean mOnlyCore; 472 final DisplayMetrics mMetrics; 473 final int mDefParseFlags; 474 final String[] mSeparateProcesses; 475 final boolean mIsUpgrade; 476 477 /** The location for ASEC container files on internal storage. */ 478 final String mAsecInternalPath; 479 480 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 481 // LOCK HELD. Can be called with mInstallLock held. 482 @GuardedBy("mInstallLock") 483 final Installer mInstaller; 484 485 /** Directory where installed third-party apps stored */ 486 final File mAppInstallDir; 487 final File mEphemeralInstallDir; 488 489 /** 490 * Directory to which applications installed internally have their 491 * 32 bit native libraries copied. 492 */ 493 private File mAppLib32InstallDir; 494 495 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 496 // apps. 497 final File mDrmAppPrivateInstallDir; 498 499 // ---------------------------------------------------------------- 500 501 // Lock for state used when installing and doing other long running 502 // operations. Methods that must be called with this lock held have 503 // the suffix "LI". 504 final Object mInstallLock = new Object(); 505 506 // ---------------------------------------------------------------- 507 508 // Keys are String (package name), values are Package. This also serves 509 // as the lock for the global state. Methods that must be called with 510 // this lock held have the prefix "LP". 511 @GuardedBy("mPackages") 512 final ArrayMap<String, PackageParser.Package> mPackages = 513 new ArrayMap<String, PackageParser.Package>(); 514 515 final ArrayMap<String, Set<String>> mKnownCodebase = 516 new ArrayMap<String, Set<String>>(); 517 518 // Tracks available target package names -> overlay package paths. 519 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 520 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 521 522 /** 523 * Tracks new system packages [received in an OTA] that we expect to 524 * find updated user-installed versions. Keys are package name, values 525 * are package location. 526 */ 527 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 528 529 /** 530 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 531 */ 532 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 533 /** 534 * Whether or not system app permissions should be promoted from install to runtime. 535 */ 536 boolean mPromoteSystemApps; 537 538 final Settings mSettings; 539 boolean mRestoredSettings; 540 541 // System configuration read by SystemConfig. 542 final int[] mGlobalGids; 543 final SparseArray<ArraySet<String>> mSystemPermissions; 544 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 545 546 // If mac_permissions.xml was found for seinfo labeling. 547 boolean mFoundPolicyFile; 548 549 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 550 551 public static final class SharedLibraryEntry { 552 public final String path; 553 public final String apk; 554 555 SharedLibraryEntry(String _path, String _apk) { 556 path = _path; 557 apk = _apk; 558 } 559 } 560 561 // Currently known shared libraries. 562 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 563 new ArrayMap<String, SharedLibraryEntry>(); 564 565 // All available activities, for your resolving pleasure. 566 final ActivityIntentResolver mActivities = 567 new ActivityIntentResolver(); 568 569 // All available receivers, for your resolving pleasure. 570 final ActivityIntentResolver mReceivers = 571 new ActivityIntentResolver(); 572 573 // All available services, for your resolving pleasure. 574 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 575 576 // All available providers, for your resolving pleasure. 577 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 578 579 // Mapping from provider base names (first directory in content URI codePath) 580 // to the provider information. 581 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 582 new ArrayMap<String, PackageParser.Provider>(); 583 584 // Mapping from instrumentation class names to info about them. 585 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 586 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 587 588 // Mapping from permission names to info about them. 589 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 590 new ArrayMap<String, PackageParser.PermissionGroup>(); 591 592 // Packages whose data we have transfered into another package, thus 593 // should no longer exist. 594 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 595 596 // Broadcast actions that are only available to the system. 597 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 598 599 /** List of packages waiting for verification. */ 600 final SparseArray<PackageVerificationState> mPendingVerification 601 = new SparseArray<PackageVerificationState>(); 602 603 /** Set of packages associated with each app op permission. */ 604 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 605 606 final PackageInstallerService mInstallerService; 607 608 private final PackageDexOptimizer mPackageDexOptimizer; 609 610 private AtomicInteger mNextMoveId = new AtomicInteger(); 611 private final MoveCallbacks mMoveCallbacks; 612 613 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 614 615 // Cache of users who need badging. 616 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 617 618 /** Token for keys in mPendingVerification. */ 619 private int mPendingVerificationToken = 0; 620 621 volatile boolean mSystemReady; 622 volatile boolean mSafeMode; 623 volatile boolean mHasSystemUidErrors; 624 625 ApplicationInfo mAndroidApplication; 626 final ActivityInfo mResolveActivity = new ActivityInfo(); 627 final ResolveInfo mResolveInfo = new ResolveInfo(); 628 ComponentName mResolveComponentName; 629 PackageParser.Package mPlatformPackage; 630 ComponentName mCustomResolverComponentName; 631 632 boolean mResolverReplaced = false; 633 634 private final @Nullable ComponentName mIntentFilterVerifierComponent; 635 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 636 637 private int mIntentFilterVerificationToken = 0; 638 639 /** Component that knows whether or not an ephemeral application exists */ 640 final ComponentName mEphemeralResolverComponent; 641 /** The service connection to the ephemeral resolver */ 642 final EphemeralResolverConnection mEphemeralResolverConnection; 643 644 /** Component used to install ephemeral applications */ 645 final ComponentName mEphemeralInstallerComponent; 646 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 647 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 648 649 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 650 = new SparseArray<IntentFilterVerificationState>(); 651 652 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 653 new DefaultPermissionGrantPolicy(this); 654 655 // List of packages names to keep cached, even if they are uninstalled for all users 656 private List<String> mKeepUninstalledPackages; 657 658 private static class IFVerificationParams { 659 PackageParser.Package pkg; 660 boolean replacing; 661 int userId; 662 int verifierUid; 663 664 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 665 int _userId, int _verifierUid) { 666 pkg = _pkg; 667 replacing = _replacing; 668 userId = _userId; 669 replacing = _replacing; 670 verifierUid = _verifierUid; 671 } 672 } 673 674 private interface IntentFilterVerifier<T extends IntentFilter> { 675 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 676 T filter, String packageName); 677 void startVerifications(int userId); 678 void receiveVerificationResponse(int verificationId); 679 } 680 681 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 682 private Context mContext; 683 private ComponentName mIntentFilterVerifierComponent; 684 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 685 686 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 687 mContext = context; 688 mIntentFilterVerifierComponent = verifierComponent; 689 } 690 691 private String getDefaultScheme() { 692 return IntentFilter.SCHEME_HTTPS; 693 } 694 695 @Override 696 public void startVerifications(int userId) { 697 // Launch verifications requests 698 int count = mCurrentIntentFilterVerifications.size(); 699 for (int n=0; n<count; n++) { 700 int verificationId = mCurrentIntentFilterVerifications.get(n); 701 final IntentFilterVerificationState ivs = 702 mIntentFilterVerificationStates.get(verificationId); 703 704 String packageName = ivs.getPackageName(); 705 706 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 707 final int filterCount = filters.size(); 708 ArraySet<String> domainsSet = new ArraySet<>(); 709 for (int m=0; m<filterCount; m++) { 710 PackageParser.ActivityIntentInfo filter = filters.get(m); 711 domainsSet.addAll(filter.getHostsList()); 712 } 713 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 714 synchronized (mPackages) { 715 if (mSettings.createIntentFilterVerificationIfNeededLPw( 716 packageName, domainsList) != null) { 717 scheduleWriteSettingsLocked(); 718 } 719 } 720 sendVerificationRequest(userId, verificationId, ivs); 721 } 722 mCurrentIntentFilterVerifications.clear(); 723 } 724 725 private void sendVerificationRequest(int userId, int verificationId, 726 IntentFilterVerificationState ivs) { 727 728 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 729 verificationIntent.putExtra( 730 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 731 verificationId); 732 verificationIntent.putExtra( 733 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 734 getDefaultScheme()); 735 verificationIntent.putExtra( 736 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 737 ivs.getHostsString()); 738 verificationIntent.putExtra( 739 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 740 ivs.getPackageName()); 741 verificationIntent.setComponent(mIntentFilterVerifierComponent); 742 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 743 744 UserHandle user = new UserHandle(userId); 745 mContext.sendBroadcastAsUser(verificationIntent, user); 746 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 747 "Sending IntentFilter verification broadcast"); 748 } 749 750 public void receiveVerificationResponse(int verificationId) { 751 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 752 753 final boolean verified = ivs.isVerified(); 754 755 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 756 final int count = filters.size(); 757 if (DEBUG_DOMAIN_VERIFICATION) { 758 Slog.i(TAG, "Received verification response " + verificationId 759 + " for " + count + " filters, verified=" + verified); 760 } 761 for (int n=0; n<count; n++) { 762 PackageParser.ActivityIntentInfo filter = filters.get(n); 763 filter.setVerified(verified); 764 765 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 766 + " verified with result:" + verified + " and hosts:" 767 + ivs.getHostsString()); 768 } 769 770 mIntentFilterVerificationStates.remove(verificationId); 771 772 final String packageName = ivs.getPackageName(); 773 IntentFilterVerificationInfo ivi = null; 774 775 synchronized (mPackages) { 776 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 777 } 778 if (ivi == null) { 779 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 780 + verificationId + " packageName:" + packageName); 781 return; 782 } 783 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 784 "Updating IntentFilterVerificationInfo for package " + packageName 785 +" verificationId:" + verificationId); 786 787 synchronized (mPackages) { 788 if (verified) { 789 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 790 } else { 791 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 792 } 793 scheduleWriteSettingsLocked(); 794 795 final int userId = ivs.getUserId(); 796 if (userId != UserHandle.USER_ALL) { 797 final int userStatus = 798 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 799 800 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 801 boolean needUpdate = false; 802 803 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 804 // already been set by the User thru the Disambiguation dialog 805 switch (userStatus) { 806 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 807 if (verified) { 808 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 809 } else { 810 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 811 } 812 needUpdate = true; 813 break; 814 815 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 816 if (verified) { 817 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 818 needUpdate = true; 819 } 820 break; 821 822 default: 823 // Nothing to do 824 } 825 826 if (needUpdate) { 827 mSettings.updateIntentFilterVerificationStatusLPw( 828 packageName, updatedStatus, userId); 829 scheduleWritePackageRestrictionsLocked(userId); 830 } 831 } 832 } 833 } 834 835 @Override 836 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 837 ActivityIntentInfo filter, String packageName) { 838 if (!hasValidDomains(filter)) { 839 return false; 840 } 841 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 842 if (ivs == null) { 843 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 844 packageName); 845 } 846 if (DEBUG_DOMAIN_VERIFICATION) { 847 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 848 } 849 ivs.addFilter(filter); 850 return true; 851 } 852 853 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 854 int userId, int verificationId, String packageName) { 855 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 856 verifierUid, userId, packageName); 857 ivs.setPendingState(); 858 synchronized (mPackages) { 859 mIntentFilterVerificationStates.append(verificationId, ivs); 860 mCurrentIntentFilterVerifications.add(verificationId); 861 } 862 return ivs; 863 } 864 } 865 866 private static boolean hasValidDomains(ActivityIntentInfo filter) { 867 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 868 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 869 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 870 } 871 872 // Set of pending broadcasts for aggregating enable/disable of components. 873 static class PendingPackageBroadcasts { 874 // for each user id, a map of <package name -> components within that package> 875 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 876 877 public PendingPackageBroadcasts() { 878 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 879 } 880 881 public ArrayList<String> get(int userId, String packageName) { 882 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 883 return packages.get(packageName); 884 } 885 886 public void put(int userId, String packageName, ArrayList<String> components) { 887 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 888 packages.put(packageName, components); 889 } 890 891 public void remove(int userId, String packageName) { 892 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 893 if (packages != null) { 894 packages.remove(packageName); 895 } 896 } 897 898 public void remove(int userId) { 899 mUidMap.remove(userId); 900 } 901 902 public int userIdCount() { 903 return mUidMap.size(); 904 } 905 906 public int userIdAt(int n) { 907 return mUidMap.keyAt(n); 908 } 909 910 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 911 return mUidMap.get(userId); 912 } 913 914 public int size() { 915 // total number of pending broadcast entries across all userIds 916 int num = 0; 917 for (int i = 0; i< mUidMap.size(); i++) { 918 num += mUidMap.valueAt(i).size(); 919 } 920 return num; 921 } 922 923 public void clear() { 924 mUidMap.clear(); 925 } 926 927 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 928 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 929 if (map == null) { 930 map = new ArrayMap<String, ArrayList<String>>(); 931 mUidMap.put(userId, map); 932 } 933 return map; 934 } 935 } 936 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 937 938 // Service Connection to remote media container service to copy 939 // package uri's from external media onto secure containers 940 // or internal storage. 941 private IMediaContainerService mContainerService = null; 942 943 static final int SEND_PENDING_BROADCAST = 1; 944 static final int MCS_BOUND = 3; 945 static final int END_COPY = 4; 946 static final int INIT_COPY = 5; 947 static final int MCS_UNBIND = 6; 948 static final int START_CLEANING_PACKAGE = 7; 949 static final int FIND_INSTALL_LOC = 8; 950 static final int POST_INSTALL = 9; 951 static final int MCS_RECONNECT = 10; 952 static final int MCS_GIVE_UP = 11; 953 static final int UPDATED_MEDIA_STATUS = 12; 954 static final int WRITE_SETTINGS = 13; 955 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 956 static final int PACKAGE_VERIFIED = 15; 957 static final int CHECK_PENDING_VERIFICATION = 16; 958 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 959 static final int INTENT_FILTER_VERIFIED = 18; 960 961 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 962 963 // Delay time in millisecs 964 static final int BROADCAST_DELAY = 10 * 1000; 965 966 static UserManagerService sUserManager; 967 968 // Stores a list of users whose package restrictions file needs to be updated 969 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 970 971 final private DefaultContainerConnection mDefContainerConn = 972 new DefaultContainerConnection(); 973 class DefaultContainerConnection implements ServiceConnection { 974 public void onServiceConnected(ComponentName name, IBinder service) { 975 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 976 IMediaContainerService imcs = 977 IMediaContainerService.Stub.asInterface(service); 978 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 979 } 980 981 public void onServiceDisconnected(ComponentName name) { 982 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 983 } 984 } 985 986 // Recordkeeping of restore-after-install operations that are currently in flight 987 // between the Package Manager and the Backup Manager 988 static class PostInstallData { 989 public InstallArgs args; 990 public PackageInstalledInfo res; 991 992 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 993 args = _a; 994 res = _r; 995 } 996 } 997 998 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 999 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1000 1001 // XML tags for backup/restore of various bits of state 1002 private static final String TAG_PREFERRED_BACKUP = "pa"; 1003 private static final String TAG_DEFAULT_APPS = "da"; 1004 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1005 1006 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1007 private static final String TAG_ALL_GRANTS = "rt-grants"; 1008 private static final String TAG_GRANT = "grant"; 1009 private static final String ATTR_PACKAGE_NAME = "pkg"; 1010 1011 private static final String TAG_PERMISSION = "perm"; 1012 private static final String ATTR_PERMISSION_NAME = "name"; 1013 private static final String ATTR_IS_GRANTED = "g"; 1014 private static final String ATTR_USER_SET = "set"; 1015 private static final String ATTR_USER_FIXED = "fixed"; 1016 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1017 1018 // System/policy permission grants are not backed up 1019 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1020 FLAG_PERMISSION_POLICY_FIXED 1021 | FLAG_PERMISSION_SYSTEM_FIXED 1022 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1023 1024 // And we back up these user-adjusted states 1025 private static final int USER_RUNTIME_GRANT_MASK = 1026 FLAG_PERMISSION_USER_SET 1027 | FLAG_PERMISSION_USER_FIXED 1028 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1029 1030 final @Nullable String mRequiredVerifierPackage; 1031 final @Nullable String mRequiredInstallerPackage; 1032 1033 private final PackageUsage mPackageUsage = new PackageUsage(); 1034 1035 private class PackageUsage { 1036 private static final int WRITE_INTERVAL 1037 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1038 1039 private final Object mFileLock = new Object(); 1040 private final AtomicLong mLastWritten = new AtomicLong(0); 1041 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1042 1043 private boolean mIsHistoricalPackageUsageAvailable = true; 1044 1045 boolean isHistoricalPackageUsageAvailable() { 1046 return mIsHistoricalPackageUsageAvailable; 1047 } 1048 1049 void write(boolean force) { 1050 if (force) { 1051 writeInternal(); 1052 return; 1053 } 1054 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1055 && !DEBUG_DEXOPT) { 1056 return; 1057 } 1058 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1059 new Thread("PackageUsage_DiskWriter") { 1060 @Override 1061 public void run() { 1062 try { 1063 writeInternal(); 1064 } finally { 1065 mBackgroundWriteRunning.set(false); 1066 } 1067 } 1068 }.start(); 1069 } 1070 } 1071 1072 private void writeInternal() { 1073 synchronized (mPackages) { 1074 synchronized (mFileLock) { 1075 AtomicFile file = getFile(); 1076 FileOutputStream f = null; 1077 try { 1078 f = file.startWrite(); 1079 BufferedOutputStream out = new BufferedOutputStream(f); 1080 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1081 StringBuilder sb = new StringBuilder(); 1082 for (PackageParser.Package pkg : mPackages.values()) { 1083 if (pkg.mLastPackageUsageTimeInMills == 0) { 1084 continue; 1085 } 1086 sb.setLength(0); 1087 sb.append(pkg.packageName); 1088 sb.append(' '); 1089 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1090 sb.append('\n'); 1091 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1092 } 1093 out.flush(); 1094 file.finishWrite(f); 1095 } catch (IOException e) { 1096 if (f != null) { 1097 file.failWrite(f); 1098 } 1099 Log.e(TAG, "Failed to write package usage times", e); 1100 } 1101 } 1102 } 1103 mLastWritten.set(SystemClock.elapsedRealtime()); 1104 } 1105 1106 void readLP() { 1107 synchronized (mFileLock) { 1108 AtomicFile file = getFile(); 1109 BufferedInputStream in = null; 1110 try { 1111 in = new BufferedInputStream(file.openRead()); 1112 StringBuffer sb = new StringBuffer(); 1113 while (true) { 1114 String packageName = readToken(in, sb, ' '); 1115 if (packageName == null) { 1116 break; 1117 } 1118 String timeInMillisString = readToken(in, sb, '\n'); 1119 if (timeInMillisString == null) { 1120 throw new IOException("Failed to find last usage time for package " 1121 + packageName); 1122 } 1123 PackageParser.Package pkg = mPackages.get(packageName); 1124 if (pkg == null) { 1125 continue; 1126 } 1127 long timeInMillis; 1128 try { 1129 timeInMillis = Long.parseLong(timeInMillisString); 1130 } catch (NumberFormatException e) { 1131 throw new IOException("Failed to parse " + timeInMillisString 1132 + " as a long.", e); 1133 } 1134 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1135 } 1136 } catch (FileNotFoundException expected) { 1137 mIsHistoricalPackageUsageAvailable = false; 1138 } catch (IOException e) { 1139 Log.w(TAG, "Failed to read package usage times", e); 1140 } finally { 1141 IoUtils.closeQuietly(in); 1142 } 1143 } 1144 mLastWritten.set(SystemClock.elapsedRealtime()); 1145 } 1146 1147 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1148 throws IOException { 1149 sb.setLength(0); 1150 while (true) { 1151 int ch = in.read(); 1152 if (ch == -1) { 1153 if (sb.length() == 0) { 1154 return null; 1155 } 1156 throw new IOException("Unexpected EOF"); 1157 } 1158 if (ch == endOfToken) { 1159 return sb.toString(); 1160 } 1161 sb.append((char)ch); 1162 } 1163 } 1164 1165 private AtomicFile getFile() { 1166 File dataDir = Environment.getDataDirectory(); 1167 File systemDir = new File(dataDir, "system"); 1168 File fname = new File(systemDir, "package-usage.list"); 1169 return new AtomicFile(fname); 1170 } 1171 } 1172 1173 class PackageHandler extends Handler { 1174 private boolean mBound = false; 1175 final ArrayList<HandlerParams> mPendingInstalls = 1176 new ArrayList<HandlerParams>(); 1177 1178 private boolean connectToService() { 1179 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1180 " DefaultContainerService"); 1181 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1182 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1183 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1184 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1185 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1186 mBound = true; 1187 return true; 1188 } 1189 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1190 return false; 1191 } 1192 1193 private void disconnectService() { 1194 mContainerService = null; 1195 mBound = false; 1196 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1197 mContext.unbindService(mDefContainerConn); 1198 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1199 } 1200 1201 PackageHandler(Looper looper) { 1202 super(looper); 1203 } 1204 1205 public void handleMessage(Message msg) { 1206 try { 1207 doHandleMessage(msg); 1208 } finally { 1209 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1210 } 1211 } 1212 1213 void doHandleMessage(Message msg) { 1214 switch (msg.what) { 1215 case INIT_COPY: { 1216 HandlerParams params = (HandlerParams) msg.obj; 1217 int idx = mPendingInstalls.size(); 1218 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1219 // If a bind was already initiated we dont really 1220 // need to do anything. The pending install 1221 // will be processed later on. 1222 if (!mBound) { 1223 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1224 System.identityHashCode(mHandler)); 1225 // If this is the only one pending we might 1226 // have to bind to the service again. 1227 if (!connectToService()) { 1228 Slog.e(TAG, "Failed to bind to media container service"); 1229 params.serviceError(); 1230 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1231 System.identityHashCode(mHandler)); 1232 if (params.traceMethod != null) { 1233 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1234 params.traceCookie); 1235 } 1236 return; 1237 } else { 1238 // Once we bind to the service, the first 1239 // pending request will be processed. 1240 mPendingInstalls.add(idx, params); 1241 } 1242 } else { 1243 mPendingInstalls.add(idx, params); 1244 // Already bound to the service. Just make 1245 // sure we trigger off processing the first request. 1246 if (idx == 0) { 1247 mHandler.sendEmptyMessage(MCS_BOUND); 1248 } 1249 } 1250 break; 1251 } 1252 case MCS_BOUND: { 1253 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1254 if (msg.obj != null) { 1255 mContainerService = (IMediaContainerService) msg.obj; 1256 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1257 System.identityHashCode(mHandler)); 1258 } 1259 if (mContainerService == null) { 1260 if (!mBound) { 1261 // Something seriously wrong since we are not bound and we are not 1262 // waiting for connection. Bail out. 1263 Slog.e(TAG, "Cannot bind to media container service"); 1264 for (HandlerParams params : mPendingInstalls) { 1265 // Indicate service bind error 1266 params.serviceError(); 1267 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1268 System.identityHashCode(params)); 1269 if (params.traceMethod != null) { 1270 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1271 params.traceMethod, params.traceCookie); 1272 } 1273 return; 1274 } 1275 mPendingInstalls.clear(); 1276 } else { 1277 Slog.w(TAG, "Waiting to connect to media container service"); 1278 } 1279 } else if (mPendingInstalls.size() > 0) { 1280 HandlerParams params = mPendingInstalls.get(0); 1281 if (params != null) { 1282 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1283 System.identityHashCode(params)); 1284 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1285 if (params.startCopy()) { 1286 // We are done... look for more work or to 1287 // go idle. 1288 if (DEBUG_SD_INSTALL) Log.i(TAG, 1289 "Checking for more work or unbind..."); 1290 // Delete pending install 1291 if (mPendingInstalls.size() > 0) { 1292 mPendingInstalls.remove(0); 1293 } 1294 if (mPendingInstalls.size() == 0) { 1295 if (mBound) { 1296 if (DEBUG_SD_INSTALL) Log.i(TAG, 1297 "Posting delayed MCS_UNBIND"); 1298 removeMessages(MCS_UNBIND); 1299 Message ubmsg = obtainMessage(MCS_UNBIND); 1300 // Unbind after a little delay, to avoid 1301 // continual thrashing. 1302 sendMessageDelayed(ubmsg, 10000); 1303 } 1304 } else { 1305 // There are more pending requests in queue. 1306 // Just post MCS_BOUND message to trigger processing 1307 // of next pending install. 1308 if (DEBUG_SD_INSTALL) Log.i(TAG, 1309 "Posting MCS_BOUND for next work"); 1310 mHandler.sendEmptyMessage(MCS_BOUND); 1311 } 1312 } 1313 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1314 } 1315 } else { 1316 // Should never happen ideally. 1317 Slog.w(TAG, "Empty queue"); 1318 } 1319 break; 1320 } 1321 case MCS_RECONNECT: { 1322 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1323 if (mPendingInstalls.size() > 0) { 1324 if (mBound) { 1325 disconnectService(); 1326 } 1327 if (!connectToService()) { 1328 Slog.e(TAG, "Failed to bind to media container service"); 1329 for (HandlerParams params : mPendingInstalls) { 1330 // Indicate service bind error 1331 params.serviceError(); 1332 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1333 System.identityHashCode(params)); 1334 } 1335 mPendingInstalls.clear(); 1336 } 1337 } 1338 break; 1339 } 1340 case MCS_UNBIND: { 1341 // If there is no actual work left, then time to unbind. 1342 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1343 1344 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1345 if (mBound) { 1346 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1347 1348 disconnectService(); 1349 } 1350 } else if (mPendingInstalls.size() > 0) { 1351 // There are more pending requests in queue. 1352 // Just post MCS_BOUND message to trigger processing 1353 // of next pending install. 1354 mHandler.sendEmptyMessage(MCS_BOUND); 1355 } 1356 1357 break; 1358 } 1359 case MCS_GIVE_UP: { 1360 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1361 HandlerParams params = mPendingInstalls.remove(0); 1362 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1363 System.identityHashCode(params)); 1364 break; 1365 } 1366 case SEND_PENDING_BROADCAST: { 1367 String packages[]; 1368 ArrayList<String> components[]; 1369 int size = 0; 1370 int uids[]; 1371 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1372 synchronized (mPackages) { 1373 if (mPendingBroadcasts == null) { 1374 return; 1375 } 1376 size = mPendingBroadcasts.size(); 1377 if (size <= 0) { 1378 // Nothing to be done. Just return 1379 return; 1380 } 1381 packages = new String[size]; 1382 components = new ArrayList[size]; 1383 uids = new int[size]; 1384 int i = 0; // filling out the above arrays 1385 1386 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1387 int packageUserId = mPendingBroadcasts.userIdAt(n); 1388 Iterator<Map.Entry<String, ArrayList<String>>> it 1389 = mPendingBroadcasts.packagesForUserId(packageUserId) 1390 .entrySet().iterator(); 1391 while (it.hasNext() && i < size) { 1392 Map.Entry<String, ArrayList<String>> ent = it.next(); 1393 packages[i] = ent.getKey(); 1394 components[i] = ent.getValue(); 1395 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1396 uids[i] = (ps != null) 1397 ? UserHandle.getUid(packageUserId, ps.appId) 1398 : -1; 1399 i++; 1400 } 1401 } 1402 size = i; 1403 mPendingBroadcasts.clear(); 1404 } 1405 // Send broadcasts 1406 for (int i = 0; i < size; i++) { 1407 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1408 } 1409 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1410 break; 1411 } 1412 case START_CLEANING_PACKAGE: { 1413 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1414 final String packageName = (String)msg.obj; 1415 final int userId = msg.arg1; 1416 final boolean andCode = msg.arg2 != 0; 1417 synchronized (mPackages) { 1418 if (userId == UserHandle.USER_ALL) { 1419 int[] users = sUserManager.getUserIds(); 1420 for (int user : users) { 1421 mSettings.addPackageToCleanLPw( 1422 new PackageCleanItem(user, packageName, andCode)); 1423 } 1424 } else { 1425 mSettings.addPackageToCleanLPw( 1426 new PackageCleanItem(userId, packageName, andCode)); 1427 } 1428 } 1429 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1430 startCleaningPackages(); 1431 } break; 1432 case POST_INSTALL: { 1433 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1434 1435 PostInstallData data = mRunningInstalls.get(msg.arg1); 1436 mRunningInstalls.delete(msg.arg1); 1437 1438 if (data != null) { 1439 InstallArgs args = data.args; 1440 PackageInstalledInfo parentRes = data.res; 1441 1442 final boolean grantPermissions = (args.installFlags 1443 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1444 final boolean killApp = (args.installFlags 1445 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1446 final String[] grantedPermissions = args.installGrantPermissions; 1447 1448 // Handle the parent package 1449 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1450 grantedPermissions, args.observer); 1451 1452 // Handle the child packages 1453 final int childCount = (parentRes.addedChildPackages != null) 1454 ? parentRes.addedChildPackages.size() : 0; 1455 for (int i = 0; i < childCount; i++) { 1456 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1457 handlePackagePostInstall(childRes, grantPermissions, killApp, 1458 grantedPermissions, args.observer); 1459 } 1460 1461 // Log tracing if needed 1462 if (args.traceMethod != null) { 1463 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1464 args.traceCookie); 1465 } 1466 } else { 1467 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1468 } 1469 1470 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1471 } break; 1472 case UPDATED_MEDIA_STATUS: { 1473 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1474 boolean reportStatus = msg.arg1 == 1; 1475 boolean doGc = msg.arg2 == 1; 1476 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1477 if (doGc) { 1478 // Force a gc to clear up stale containers. 1479 Runtime.getRuntime().gc(); 1480 } 1481 if (msg.obj != null) { 1482 @SuppressWarnings("unchecked") 1483 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1484 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1485 // Unload containers 1486 unloadAllContainers(args); 1487 } 1488 if (reportStatus) { 1489 try { 1490 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1491 PackageHelper.getMountService().finishMediaUpdate(); 1492 } catch (RemoteException e) { 1493 Log.e(TAG, "MountService not running?"); 1494 } 1495 } 1496 } break; 1497 case WRITE_SETTINGS: { 1498 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1499 synchronized (mPackages) { 1500 removeMessages(WRITE_SETTINGS); 1501 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1502 mSettings.writeLPr(); 1503 mDirtyUsers.clear(); 1504 } 1505 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1506 } break; 1507 case WRITE_PACKAGE_RESTRICTIONS: { 1508 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1509 synchronized (mPackages) { 1510 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1511 for (int userId : mDirtyUsers) { 1512 mSettings.writePackageRestrictionsLPr(userId); 1513 } 1514 mDirtyUsers.clear(); 1515 } 1516 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1517 } break; 1518 case CHECK_PENDING_VERIFICATION: { 1519 final int verificationId = msg.arg1; 1520 final PackageVerificationState state = mPendingVerification.get(verificationId); 1521 1522 if ((state != null) && !state.timeoutExtended()) { 1523 final InstallArgs args = state.getInstallArgs(); 1524 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1525 1526 Slog.i(TAG, "Verification timed out for " + originUri); 1527 mPendingVerification.remove(verificationId); 1528 1529 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1530 1531 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1532 Slog.i(TAG, "Continuing with installation of " + originUri); 1533 state.setVerifierResponse(Binder.getCallingUid(), 1534 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1535 broadcastPackageVerified(verificationId, originUri, 1536 PackageManager.VERIFICATION_ALLOW, 1537 state.getInstallArgs().getUser()); 1538 try { 1539 ret = args.copyApk(mContainerService, true); 1540 } catch (RemoteException e) { 1541 Slog.e(TAG, "Could not contact the ContainerService"); 1542 } 1543 } else { 1544 broadcastPackageVerified(verificationId, originUri, 1545 PackageManager.VERIFICATION_REJECT, 1546 state.getInstallArgs().getUser()); 1547 } 1548 1549 Trace.asyncTraceEnd( 1550 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1551 1552 processPendingInstall(args, ret); 1553 mHandler.sendEmptyMessage(MCS_UNBIND); 1554 } 1555 break; 1556 } 1557 case PACKAGE_VERIFIED: { 1558 final int verificationId = msg.arg1; 1559 1560 final PackageVerificationState state = mPendingVerification.get(verificationId); 1561 if (state == null) { 1562 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1563 break; 1564 } 1565 1566 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1567 1568 state.setVerifierResponse(response.callerUid, response.code); 1569 1570 if (state.isVerificationComplete()) { 1571 mPendingVerification.remove(verificationId); 1572 1573 final InstallArgs args = state.getInstallArgs(); 1574 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1575 1576 int ret; 1577 if (state.isInstallAllowed()) { 1578 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1579 broadcastPackageVerified(verificationId, originUri, 1580 response.code, state.getInstallArgs().getUser()); 1581 try { 1582 ret = args.copyApk(mContainerService, true); 1583 } catch (RemoteException e) { 1584 Slog.e(TAG, "Could not contact the ContainerService"); 1585 } 1586 } else { 1587 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1588 } 1589 1590 Trace.asyncTraceEnd( 1591 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1592 1593 processPendingInstall(args, ret); 1594 mHandler.sendEmptyMessage(MCS_UNBIND); 1595 } 1596 1597 break; 1598 } 1599 case START_INTENT_FILTER_VERIFICATIONS: { 1600 IFVerificationParams params = (IFVerificationParams) msg.obj; 1601 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1602 params.replacing, params.pkg); 1603 break; 1604 } 1605 case INTENT_FILTER_VERIFIED: { 1606 final int verificationId = msg.arg1; 1607 1608 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1609 verificationId); 1610 if (state == null) { 1611 Slog.w(TAG, "Invalid IntentFilter verification token " 1612 + verificationId + " received"); 1613 break; 1614 } 1615 1616 final int userId = state.getUserId(); 1617 1618 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1619 "Processing IntentFilter verification with token:" 1620 + verificationId + " and userId:" + userId); 1621 1622 final IntentFilterVerificationResponse response = 1623 (IntentFilterVerificationResponse) msg.obj; 1624 1625 state.setVerifierResponse(response.callerUid, response.code); 1626 1627 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1628 "IntentFilter verification with token:" + verificationId 1629 + " and userId:" + userId 1630 + " is settings verifier response with response code:" 1631 + response.code); 1632 1633 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1634 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1635 + response.getFailedDomainsString()); 1636 } 1637 1638 if (state.isVerificationComplete()) { 1639 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1640 } else { 1641 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1642 "IntentFilter verification with token:" + verificationId 1643 + " was not said to be complete"); 1644 } 1645 1646 break; 1647 } 1648 } 1649 } 1650 } 1651 1652 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1653 boolean killApp, String[] grantedPermissions, 1654 IPackageInstallObserver2 installObserver) { 1655 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1656 // Send the removed broadcasts 1657 if (res.removedInfo != null) { 1658 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1659 } 1660 1661 // Now that we successfully installed the package, grant runtime 1662 // permissions if requested before broadcasting the install. 1663 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1664 >= Build.VERSION_CODES.M) { 1665 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1666 } 1667 1668 final boolean update = res.removedInfo != null 1669 && res.removedInfo.removedPackage != null; 1670 1671 // If this is the first time we have child packages for a disabled privileged 1672 // app that had no children, we grant requested runtime permissions to the new 1673 // children if the parent on the system image had them already granted. 1674 if (res.pkg.parentPackage != null) { 1675 synchronized (mPackages) { 1676 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1677 } 1678 } 1679 1680 synchronized (mPackages) { 1681 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1682 } 1683 1684 final String packageName = res.pkg.applicationInfo.packageName; 1685 Bundle extras = new Bundle(1); 1686 extras.putInt(Intent.EXTRA_UID, res.uid); 1687 1688 // Determine the set of users who are adding this package for 1689 // the first time vs. those who are seeing an update. 1690 int[] firstUsers = EMPTY_INT_ARRAY; 1691 int[] updateUsers = EMPTY_INT_ARRAY; 1692 if (res.origUsers == null || res.origUsers.length == 0) { 1693 firstUsers = res.newUsers; 1694 } else { 1695 for (int newUser : res.newUsers) { 1696 boolean isNew = true; 1697 for (int origUser : res.origUsers) { 1698 if (origUser == newUser) { 1699 isNew = false; 1700 break; 1701 } 1702 } 1703 if (isNew) { 1704 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1705 } else { 1706 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1707 } 1708 } 1709 } 1710 1711 // Send installed broadcasts if the install/update is not ephemeral 1712 if (!isEphemeral(res.pkg)) { 1713 // Send added for users that see the package for the first time 1714 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1715 extras, 0 /*flags*/, null /*targetPackage*/, 1716 null /*finishedReceiver*/, firstUsers); 1717 1718 // Send added for users that don't see the package for the first time 1719 if (update) { 1720 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1721 } 1722 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1723 extras, 0 /*flags*/, null /*targetPackage*/, 1724 null /*finishedReceiver*/, updateUsers); 1725 1726 // Send replaced for users that don't see the package for the first time 1727 if (update) { 1728 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1729 packageName, extras, 0 /*flags*/, 1730 null /*targetPackage*/, null /*finishedReceiver*/, 1731 updateUsers); 1732 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1733 null /*package*/, null /*extras*/, 0 /*flags*/, 1734 packageName /*targetPackage*/, 1735 null /*finishedReceiver*/, updateUsers); 1736 } 1737 1738 // Send broadcast package appeared if forward locked/external for all users 1739 // treat asec-hosted packages like removable media on upgrade 1740 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1741 if (DEBUG_INSTALL) { 1742 Slog.i(TAG, "upgrading pkg " + res.pkg 1743 + " is ASEC-hosted -> AVAILABLE"); 1744 } 1745 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1746 ArrayList<String> pkgList = new ArrayList<>(1); 1747 pkgList.add(packageName); 1748 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1749 } 1750 } 1751 1752 // Work that needs to happen on first install within each user 1753 if (firstUsers != null && firstUsers.length > 0) { 1754 synchronized (mPackages) { 1755 for (int userId : firstUsers) { 1756 // If this app is a browser and it's newly-installed for some 1757 // users, clear any default-browser state in those users. The 1758 // app's nature doesn't depend on the user, so we can just check 1759 // its browser nature in any user and generalize. 1760 if (packageIsBrowser(packageName, userId)) { 1761 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1762 } 1763 1764 // We may also need to apply pending (restored) runtime 1765 // permission grants within these users. 1766 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1767 } 1768 } 1769 } 1770 1771 // Log current value of "unknown sources" setting 1772 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1773 getUnknownSourcesSettings()); 1774 1775 // Force a gc to clear up things 1776 Runtime.getRuntime().gc(); 1777 1778 // Remove the replaced package's older resources safely now 1779 // We delete after a gc for applications on sdcard. 1780 if (res.removedInfo != null && res.removedInfo.args != null) { 1781 synchronized (mInstallLock) { 1782 res.removedInfo.args.doPostDeleteLI(true); 1783 } 1784 } 1785 } 1786 1787 // If someone is watching installs - notify them 1788 if (installObserver != null) { 1789 try { 1790 Bundle extras = extrasForInstallResult(res); 1791 installObserver.onPackageInstalled(res.name, res.returnCode, 1792 res.returnMsg, extras); 1793 } catch (RemoteException e) { 1794 Slog.i(TAG, "Observer no longer exists."); 1795 } 1796 } 1797 } 1798 1799 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1800 PackageParser.Package pkg) { 1801 if (pkg.parentPackage == null) { 1802 return; 1803 } 1804 if (pkg.requestedPermissions == null) { 1805 return; 1806 } 1807 final PackageSetting disabledSysParentPs = mSettings 1808 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1809 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1810 || !disabledSysParentPs.isPrivileged() 1811 || (disabledSysParentPs.childPackageNames != null 1812 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1813 return; 1814 } 1815 final int[] allUserIds = sUserManager.getUserIds(); 1816 final int permCount = pkg.requestedPermissions.size(); 1817 for (int i = 0; i < permCount; i++) { 1818 String permission = pkg.requestedPermissions.get(i); 1819 BasePermission bp = mSettings.mPermissions.get(permission); 1820 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1821 continue; 1822 } 1823 for (int userId : allUserIds) { 1824 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1825 permission, userId)) { 1826 grantRuntimePermission(pkg.packageName, permission, userId); 1827 } 1828 } 1829 } 1830 } 1831 1832 private StorageEventListener mStorageListener = new StorageEventListener() { 1833 @Override 1834 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1835 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1836 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1837 final String volumeUuid = vol.getFsUuid(); 1838 1839 // Clean up any users or apps that were removed or recreated 1840 // while this volume was missing 1841 reconcileUsers(volumeUuid); 1842 reconcileApps(volumeUuid); 1843 1844 // Clean up any install sessions that expired or were 1845 // cancelled while this volume was missing 1846 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1847 1848 loadPrivatePackages(vol); 1849 1850 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1851 unloadPrivatePackages(vol); 1852 } 1853 } 1854 1855 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1856 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1857 updateExternalMediaStatus(true, false); 1858 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1859 updateExternalMediaStatus(false, false); 1860 } 1861 } 1862 } 1863 1864 @Override 1865 public void onVolumeForgotten(String fsUuid) { 1866 if (TextUtils.isEmpty(fsUuid)) { 1867 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1868 return; 1869 } 1870 1871 // Remove any apps installed on the forgotten volume 1872 synchronized (mPackages) { 1873 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1874 for (PackageSetting ps : packages) { 1875 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1876 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1877 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1878 } 1879 1880 mSettings.onVolumeForgotten(fsUuid); 1881 mSettings.writeLPr(); 1882 } 1883 } 1884 }; 1885 1886 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1887 String[] grantedPermissions) { 1888 for (int userId : userIds) { 1889 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1890 } 1891 1892 // We could have touched GID membership, so flush out packages.list 1893 synchronized (mPackages) { 1894 mSettings.writePackageListLPr(); 1895 } 1896 } 1897 1898 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1899 String[] grantedPermissions) { 1900 SettingBase sb = (SettingBase) pkg.mExtras; 1901 if (sb == null) { 1902 return; 1903 } 1904 1905 PermissionsState permissionsState = sb.getPermissionsState(); 1906 1907 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1908 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1909 1910 synchronized (mPackages) { 1911 for (String permission : pkg.requestedPermissions) { 1912 BasePermission bp = mSettings.mPermissions.get(permission); 1913 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1914 && (grantedPermissions == null 1915 || ArrayUtils.contains(grantedPermissions, permission))) { 1916 final int flags = permissionsState.getPermissionFlags(permission, userId); 1917 // Installer cannot change immutable permissions. 1918 if ((flags & immutableFlags) == 0) { 1919 grantRuntimePermission(pkg.packageName, permission, userId); 1920 } 1921 } 1922 } 1923 } 1924 } 1925 1926 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1927 Bundle extras = null; 1928 switch (res.returnCode) { 1929 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1930 extras = new Bundle(); 1931 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1932 res.origPermission); 1933 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1934 res.origPackage); 1935 break; 1936 } 1937 case PackageManager.INSTALL_SUCCEEDED: { 1938 extras = new Bundle(); 1939 extras.putBoolean(Intent.EXTRA_REPLACING, 1940 res.removedInfo != null && res.removedInfo.removedPackage != null); 1941 break; 1942 } 1943 } 1944 return extras; 1945 } 1946 1947 void scheduleWriteSettingsLocked() { 1948 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1949 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1950 } 1951 } 1952 1953 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 1954 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 1955 scheduleWritePackageRestrictionsLocked(userId); 1956 } 1957 1958 void scheduleWritePackageRestrictionsLocked(int userId) { 1959 final int[] userIds = (userId == UserHandle.USER_ALL) 1960 ? sUserManager.getUserIds() : new int[]{userId}; 1961 for (int nextUserId : userIds) { 1962 if (!sUserManager.exists(nextUserId)) return; 1963 mDirtyUsers.add(nextUserId); 1964 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1965 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1966 } 1967 } 1968 } 1969 1970 public static PackageManagerService main(Context context, Installer installer, 1971 boolean factoryTest, boolean onlyCore) { 1972 // Self-check for initial settings. 1973 PackageManagerServiceCompilerMapping.checkProperties(); 1974 1975 PackageManagerService m = new PackageManagerService(context, installer, 1976 factoryTest, onlyCore); 1977 m.enableSystemUserPackages(); 1978 ServiceManager.addService("package", m); 1979 return m; 1980 } 1981 1982 private void enableSystemUserPackages() { 1983 if (!UserManager.isSplitSystemUser()) { 1984 return; 1985 } 1986 // For system user, enable apps based on the following conditions: 1987 // - app is whitelisted or belong to one of these groups: 1988 // -- system app which has no launcher icons 1989 // -- system app which has INTERACT_ACROSS_USERS permission 1990 // -- system IME app 1991 // - app is not in the blacklist 1992 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 1993 Set<String> enableApps = new ArraySet<>(); 1994 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 1995 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 1996 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 1997 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 1998 enableApps.addAll(wlApps); 1999 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2000 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2001 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2002 enableApps.removeAll(blApps); 2003 Log.i(TAG, "Applications installed for system user: " + enableApps); 2004 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2005 UserHandle.SYSTEM); 2006 final int allAppsSize = allAps.size(); 2007 synchronized (mPackages) { 2008 for (int i = 0; i < allAppsSize; i++) { 2009 String pName = allAps.get(i); 2010 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2011 // Should not happen, but we shouldn't be failing if it does 2012 if (pkgSetting == null) { 2013 continue; 2014 } 2015 boolean install = enableApps.contains(pName); 2016 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2017 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2018 + " for system user"); 2019 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2020 } 2021 } 2022 } 2023 } 2024 2025 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2026 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2027 Context.DISPLAY_SERVICE); 2028 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2029 } 2030 2031 public PackageManagerService(Context context, Installer installer, 2032 boolean factoryTest, boolean onlyCore) { 2033 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2034 SystemClock.uptimeMillis()); 2035 2036 if (mSdkVersion <= 0) { 2037 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2038 } 2039 2040 mContext = context; 2041 mFactoryTest = factoryTest; 2042 mOnlyCore = onlyCore; 2043 mMetrics = new DisplayMetrics(); 2044 mSettings = new Settings(mPackages); 2045 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2046 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2047 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2048 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2049 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2050 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2051 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2052 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2053 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2054 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2055 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2056 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2057 2058 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2059 if (separateProcesses != null && separateProcesses.length() > 0) { 2060 if ("*".equals(separateProcesses)) { 2061 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2062 mSeparateProcesses = null; 2063 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2064 } else { 2065 mDefParseFlags = 0; 2066 mSeparateProcesses = separateProcesses.split(","); 2067 Slog.w(TAG, "Running with debug.separate_processes: " 2068 + separateProcesses); 2069 } 2070 } else { 2071 mDefParseFlags = 0; 2072 mSeparateProcesses = null; 2073 } 2074 2075 mInstaller = installer; 2076 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2077 "*dexopt*"); 2078 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2079 2080 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2081 FgThread.get().getLooper()); 2082 2083 getDefaultDisplayMetrics(context, mMetrics); 2084 2085 SystemConfig systemConfig = SystemConfig.getInstance(); 2086 mGlobalGids = systemConfig.getGlobalGids(); 2087 mSystemPermissions = systemConfig.getSystemPermissions(); 2088 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2089 2090 synchronized (mInstallLock) { 2091 // writer 2092 synchronized (mPackages) { 2093 mHandlerThread = new ServiceThread(TAG, 2094 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2095 mHandlerThread.start(); 2096 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2097 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2098 2099 File dataDir = Environment.getDataDirectory(); 2100 mAppInstallDir = new File(dataDir, "app"); 2101 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2102 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2103 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2104 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2105 2106 sUserManager = new UserManagerService(context, this, mPackages); 2107 2108 // Propagate permission configuration in to package manager. 2109 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2110 = systemConfig.getPermissions(); 2111 for (int i=0; i<permConfig.size(); i++) { 2112 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2113 BasePermission bp = mSettings.mPermissions.get(perm.name); 2114 if (bp == null) { 2115 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2116 mSettings.mPermissions.put(perm.name, bp); 2117 } 2118 if (perm.gids != null) { 2119 bp.setGids(perm.gids, perm.perUser); 2120 } 2121 } 2122 2123 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2124 for (int i=0; i<libConfig.size(); i++) { 2125 mSharedLibraries.put(libConfig.keyAt(i), 2126 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2127 } 2128 2129 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2130 2131 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2132 2133 String customResolverActivity = Resources.getSystem().getString( 2134 R.string.config_customResolverActivity); 2135 if (TextUtils.isEmpty(customResolverActivity)) { 2136 customResolverActivity = null; 2137 } else { 2138 mCustomResolverComponentName = ComponentName.unflattenFromString( 2139 customResolverActivity); 2140 } 2141 2142 long startTime = SystemClock.uptimeMillis(); 2143 2144 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2145 startTime); 2146 2147 // Set flag to monitor and not change apk file paths when 2148 // scanning install directories. 2149 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2150 2151 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2152 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2153 2154 if (bootClassPath == null) { 2155 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2156 } 2157 2158 if (systemServerClassPath == null) { 2159 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2160 } 2161 2162 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2163 final String[] dexCodeInstructionSets = 2164 getDexCodeInstructionSets( 2165 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2166 2167 /** 2168 * Ensure all external libraries have had dexopt run on them. 2169 */ 2170 if (mSharedLibraries.size() > 0) { 2171 // NOTE: For now, we're compiling these system "shared libraries" 2172 // (and framework jars) into all available architectures. It's possible 2173 // to compile them only when we come across an app that uses them (there's 2174 // already logic for that in scanPackageLI) but that adds some complexity. 2175 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2176 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2177 final String lib = libEntry.path; 2178 if (lib == null) { 2179 continue; 2180 } 2181 2182 try { 2183 // Shared libraries do not have profiles so we perform a full 2184 // AOT compilation (if needed). 2185 int dexoptNeeded = DexFile.getDexOptNeeded( 2186 lib, dexCodeInstructionSet, 2187 getCompilerFilterForReason(REASON_SHARED_APK), 2188 false /* newProfile */); 2189 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2190 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2191 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2192 getCompilerFilterForReason(REASON_SHARED_APK), 2193 StorageManager.UUID_PRIVATE_INTERNAL); 2194 } 2195 } catch (FileNotFoundException e) { 2196 Slog.w(TAG, "Library not found: " + lib); 2197 } catch (IOException | InstallerException e) { 2198 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2199 + e.getMessage()); 2200 } 2201 } 2202 } 2203 } 2204 2205 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2206 2207 final VersionInfo ver = mSettings.getInternalVersion(); 2208 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2209 // when upgrading from pre-M, promote system app permissions from install to runtime 2210 mPromoteSystemApps = 2211 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2212 2213 // save off the names of pre-existing system packages prior to scanning; we don't 2214 // want to automatically grant runtime permissions for new system apps 2215 if (mPromoteSystemApps) { 2216 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2217 while (pkgSettingIter.hasNext()) { 2218 PackageSetting ps = pkgSettingIter.next(); 2219 if (isSystemApp(ps)) { 2220 mExistingSystemPackages.add(ps.name); 2221 } 2222 } 2223 } 2224 2225 // Collect vendor overlay packages. 2226 // (Do this before scanning any apps.) 2227 // For security and version matching reason, only consider 2228 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2229 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2230 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2231 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2232 2233 // Find base frameworks (resource packages without code). 2234 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2235 | PackageParser.PARSE_IS_SYSTEM_DIR 2236 | PackageParser.PARSE_IS_PRIVILEGED, 2237 scanFlags | SCAN_NO_DEX, 0); 2238 2239 // Collected privileged system packages. 2240 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2241 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2242 | PackageParser.PARSE_IS_SYSTEM_DIR 2243 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2244 2245 // Collect ordinary system packages. 2246 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2247 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2248 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2249 2250 // Collect all vendor packages. 2251 File vendorAppDir = new File("/vendor/app"); 2252 try { 2253 vendorAppDir = vendorAppDir.getCanonicalFile(); 2254 } catch (IOException e) { 2255 // failed to look up canonical path, continue with original one 2256 } 2257 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2258 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2259 2260 // Collect all OEM packages. 2261 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2262 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2263 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2264 2265 // Prune any system packages that no longer exist. 2266 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2267 if (!mOnlyCore) { 2268 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2269 while (psit.hasNext()) { 2270 PackageSetting ps = psit.next(); 2271 2272 /* 2273 * If this is not a system app, it can't be a 2274 * disable system app. 2275 */ 2276 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2277 continue; 2278 } 2279 2280 /* 2281 * If the package is scanned, it's not erased. 2282 */ 2283 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2284 if (scannedPkg != null) { 2285 /* 2286 * If the system app is both scanned and in the 2287 * disabled packages list, then it must have been 2288 * added via OTA. Remove it from the currently 2289 * scanned package so the previously user-installed 2290 * application can be scanned. 2291 */ 2292 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2293 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2294 + ps.name + "; removing system app. Last known codePath=" 2295 + ps.codePathString + ", installStatus=" + ps.installStatus 2296 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2297 + scannedPkg.mVersionCode); 2298 removePackageLI(scannedPkg, true); 2299 mExpectingBetter.put(ps.name, ps.codePath); 2300 } 2301 2302 continue; 2303 } 2304 2305 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2306 psit.remove(); 2307 logCriticalInfo(Log.WARN, "System package " + ps.name 2308 + " no longer exists; wiping its data"); 2309 removeDataDirsLI(null, ps.name); 2310 } else { 2311 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2312 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2313 possiblyDeletedUpdatedSystemApps.add(ps.name); 2314 } 2315 } 2316 } 2317 } 2318 2319 //look for any incomplete package installations 2320 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2321 //clean up list 2322 for(int i = 0; i < deletePkgsList.size(); i++) { 2323 //clean up here 2324 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2325 } 2326 //delete tmp files 2327 deleteTempPackageFiles(); 2328 2329 // Remove any shared userIDs that have no associated packages 2330 mSettings.pruneSharedUsersLPw(); 2331 2332 if (!mOnlyCore) { 2333 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2334 SystemClock.uptimeMillis()); 2335 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2336 2337 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2338 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2339 2340 scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL, 2341 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2342 2343 /** 2344 * Remove disable package settings for any updated system 2345 * apps that were removed via an OTA. If they're not a 2346 * previously-updated app, remove them completely. 2347 * Otherwise, just revoke their system-level permissions. 2348 */ 2349 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2350 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2351 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2352 2353 String msg; 2354 if (deletedPkg == null) { 2355 msg = "Updated system package " + deletedAppName 2356 + " no longer exists; wiping its data"; 2357 removeDataDirsLI(null, deletedAppName); 2358 } else { 2359 msg = "Updated system app + " + deletedAppName 2360 + " no longer present; removing system privileges for " 2361 + deletedAppName; 2362 2363 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2364 2365 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2366 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2367 } 2368 logCriticalInfo(Log.WARN, msg); 2369 } 2370 2371 /** 2372 * Make sure all system apps that we expected to appear on 2373 * the userdata partition actually showed up. If they never 2374 * appeared, crawl back and revive the system version. 2375 */ 2376 for (int i = 0; i < mExpectingBetter.size(); i++) { 2377 final String packageName = mExpectingBetter.keyAt(i); 2378 if (!mPackages.containsKey(packageName)) { 2379 final File scanFile = mExpectingBetter.valueAt(i); 2380 2381 logCriticalInfo(Log.WARN, "Expected better " + packageName 2382 + " but never showed up; reverting to system"); 2383 2384 final int reparseFlags; 2385 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2386 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2387 | PackageParser.PARSE_IS_SYSTEM_DIR 2388 | PackageParser.PARSE_IS_PRIVILEGED; 2389 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2390 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2391 | PackageParser.PARSE_IS_SYSTEM_DIR; 2392 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2393 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2394 | PackageParser.PARSE_IS_SYSTEM_DIR; 2395 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2396 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2397 | PackageParser.PARSE_IS_SYSTEM_DIR; 2398 } else { 2399 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2400 continue; 2401 } 2402 2403 mSettings.enableSystemPackageLPw(packageName); 2404 2405 try { 2406 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2407 } catch (PackageManagerException e) { 2408 Slog.e(TAG, "Failed to parse original system package: " 2409 + e.getMessage()); 2410 } 2411 } 2412 } 2413 } 2414 mExpectingBetter.clear(); 2415 2416 // Now that we know all of the shared libraries, update all clients to have 2417 // the correct library paths. 2418 updateAllSharedLibrariesLPw(); 2419 2420 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2421 // NOTE: We ignore potential failures here during a system scan (like 2422 // the rest of the commands above) because there's precious little we 2423 // can do about it. A settings error is reported, though. 2424 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2425 false /* boot complete */); 2426 } 2427 2428 // Now that we know all the packages we are keeping, 2429 // read and update their last usage times. 2430 mPackageUsage.readLP(); 2431 2432 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2433 SystemClock.uptimeMillis()); 2434 Slog.i(TAG, "Time to scan packages: " 2435 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2436 + " seconds"); 2437 2438 // If the platform SDK has changed since the last time we booted, 2439 // we need to re-grant app permission to catch any new ones that 2440 // appear. This is really a hack, and means that apps can in some 2441 // cases get permissions that the user didn't initially explicitly 2442 // allow... it would be nice to have some better way to handle 2443 // this situation. 2444 int updateFlags = UPDATE_PERMISSIONS_ALL; 2445 if (ver.sdkVersion != mSdkVersion) { 2446 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2447 + mSdkVersion + "; regranting permissions for internal storage"); 2448 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2449 } 2450 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2451 ver.sdkVersion = mSdkVersion; 2452 2453 // If this is the first boot or an update from pre-M, and it is a normal 2454 // boot, then we need to initialize the default preferred apps across 2455 // all defined users. 2456 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2457 for (UserInfo user : sUserManager.getUsers(true)) { 2458 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2459 applyFactoryDefaultBrowserLPw(user.id); 2460 primeDomainVerificationsLPw(user.id); 2461 } 2462 } 2463 2464 // Prepare storage for system user really early during boot, 2465 // since core system apps like SettingsProvider and SystemUI 2466 // can't wait for user to start 2467 final int storageFlags; 2468 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2469 storageFlags = StorageManager.FLAG_STORAGE_DE; 2470 } else { 2471 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2472 } 2473 reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2474 storageFlags); 2475 2476 // If this is first boot after an OTA, and a normal boot, then 2477 // we need to clear code cache directories. 2478 if (mIsUpgrade && !onlyCore) { 2479 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2480 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2481 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2482 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2483 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2484 } 2485 } 2486 ver.fingerprint = Build.FINGERPRINT; 2487 } 2488 2489 checkDefaultBrowser(); 2490 2491 // clear only after permissions and other defaults have been updated 2492 mExistingSystemPackages.clear(); 2493 mPromoteSystemApps = false; 2494 2495 // All the changes are done during package scanning. 2496 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2497 2498 // can downgrade to reader 2499 mSettings.writeLPr(); 2500 2501 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2502 SystemClock.uptimeMillis()); 2503 2504 if (!mOnlyCore) { 2505 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2506 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2507 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2508 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2509 mIntentFilterVerifierComponent); 2510 } else { 2511 mRequiredVerifierPackage = null; 2512 mRequiredInstallerPackage = null; 2513 mIntentFilterVerifierComponent = null; 2514 mIntentFilterVerifier = null; 2515 } 2516 2517 mInstallerService = new PackageInstallerService(context, this); 2518 2519 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2520 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2521 // both the installer and resolver must be present to enable ephemeral 2522 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2523 if (DEBUG_EPHEMERAL) { 2524 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2525 + " installer:" + ephemeralInstallerComponent); 2526 } 2527 mEphemeralResolverComponent = ephemeralResolverComponent; 2528 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2529 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2530 mEphemeralResolverConnection = 2531 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2532 } else { 2533 if (DEBUG_EPHEMERAL) { 2534 final String missingComponent = 2535 (ephemeralResolverComponent == null) 2536 ? (ephemeralInstallerComponent == null) 2537 ? "resolver and installer" 2538 : "resolver" 2539 : "installer"; 2540 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2541 } 2542 mEphemeralResolverComponent = null; 2543 mEphemeralInstallerComponent = null; 2544 mEphemeralResolverConnection = null; 2545 } 2546 2547 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2548 } // synchronized (mPackages) 2549 } // synchronized (mInstallLock) 2550 2551 // Now after opening every single application zip, make sure they 2552 // are all flushed. Not really needed, but keeps things nice and 2553 // tidy. 2554 Runtime.getRuntime().gc(); 2555 2556 // The initial scanning above does many calls into installd while 2557 // holding the mPackages lock, but we're mostly interested in yelling 2558 // once we have a booted system. 2559 mInstaller.setWarnIfHeld(mPackages); 2560 2561 // Expose private service for system components to use. 2562 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2563 } 2564 2565 @Override 2566 public boolean isFirstBoot() { 2567 return !mRestoredSettings; 2568 } 2569 2570 @Override 2571 public boolean isOnlyCoreApps() { 2572 return mOnlyCore; 2573 } 2574 2575 @Override 2576 public boolean isUpgrade() { 2577 return mIsUpgrade; 2578 } 2579 2580 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2581 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2582 2583 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2584 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2585 UserHandle.USER_SYSTEM); 2586 if (matches.size() == 1) { 2587 return matches.get(0).getComponentInfo().packageName; 2588 } else { 2589 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2590 return null; 2591 } 2592 } 2593 2594 private @NonNull String getRequiredInstallerLPr() { 2595 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2596 intent.addCategory(Intent.CATEGORY_DEFAULT); 2597 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2598 2599 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2600 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2601 UserHandle.USER_SYSTEM); 2602 if (matches.size() == 1) { 2603 return matches.get(0).getComponentInfo().packageName; 2604 } else { 2605 throw new RuntimeException("There must be exactly one installer; found " + matches); 2606 } 2607 } 2608 2609 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2610 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2611 2612 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2613 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2614 UserHandle.USER_SYSTEM); 2615 ResolveInfo best = null; 2616 final int N = matches.size(); 2617 for (int i = 0; i < N; i++) { 2618 final ResolveInfo cur = matches.get(i); 2619 final String packageName = cur.getComponentInfo().packageName; 2620 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2621 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2622 continue; 2623 } 2624 2625 if (best == null || cur.priority > best.priority) { 2626 best = cur; 2627 } 2628 } 2629 2630 if (best != null) { 2631 return best.getComponentInfo().getComponentName(); 2632 } else { 2633 throw new RuntimeException("There must be at least one intent filter verifier"); 2634 } 2635 } 2636 2637 private @Nullable ComponentName getEphemeralResolverLPr() { 2638 final String[] packageArray = 2639 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2640 if (packageArray.length == 0) { 2641 if (DEBUG_EPHEMERAL) { 2642 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2643 } 2644 return null; 2645 } 2646 2647 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2648 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2649 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2650 UserHandle.USER_SYSTEM); 2651 2652 final int N = resolvers.size(); 2653 if (N == 0) { 2654 if (DEBUG_EPHEMERAL) { 2655 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2656 } 2657 return null; 2658 } 2659 2660 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2661 for (int i = 0; i < N; i++) { 2662 final ResolveInfo info = resolvers.get(i); 2663 2664 if (info.serviceInfo == null) { 2665 continue; 2666 } 2667 2668 final String packageName = info.serviceInfo.packageName; 2669 if (!possiblePackages.contains(packageName)) { 2670 if (DEBUG_EPHEMERAL) { 2671 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2672 + " pkg: " + packageName + ", info:" + info); 2673 } 2674 continue; 2675 } 2676 2677 if (DEBUG_EPHEMERAL) { 2678 Slog.v(TAG, "Ephemeral resolver found;" 2679 + " pkg: " + packageName + ", info:" + info); 2680 } 2681 return new ComponentName(packageName, info.serviceInfo.name); 2682 } 2683 if (DEBUG_EPHEMERAL) { 2684 Slog.v(TAG, "Ephemeral resolver NOT found"); 2685 } 2686 return null; 2687 } 2688 2689 private @Nullable ComponentName getEphemeralInstallerLPr() { 2690 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2691 intent.addCategory(Intent.CATEGORY_DEFAULT); 2692 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2693 2694 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2695 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2696 UserHandle.USER_SYSTEM); 2697 if (matches.size() == 0) { 2698 return null; 2699 } else if (matches.size() == 1) { 2700 return matches.get(0).getComponentInfo().getComponentName(); 2701 } else { 2702 throw new RuntimeException( 2703 "There must be at most one ephemeral installer; found " + matches); 2704 } 2705 } 2706 2707 private void primeDomainVerificationsLPw(int userId) { 2708 if (DEBUG_DOMAIN_VERIFICATION) { 2709 Slog.d(TAG, "Priming domain verifications in user " + userId); 2710 } 2711 2712 SystemConfig systemConfig = SystemConfig.getInstance(); 2713 ArraySet<String> packages = systemConfig.getLinkedApps(); 2714 ArraySet<String> domains = new ArraySet<String>(); 2715 2716 for (String packageName : packages) { 2717 PackageParser.Package pkg = mPackages.get(packageName); 2718 if (pkg != null) { 2719 if (!pkg.isSystemApp()) { 2720 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2721 continue; 2722 } 2723 2724 domains.clear(); 2725 for (PackageParser.Activity a : pkg.activities) { 2726 for (ActivityIntentInfo filter : a.intents) { 2727 if (hasValidDomains(filter)) { 2728 domains.addAll(filter.getHostsList()); 2729 } 2730 } 2731 } 2732 2733 if (domains.size() > 0) { 2734 if (DEBUG_DOMAIN_VERIFICATION) { 2735 Slog.v(TAG, " + " + packageName); 2736 } 2737 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2738 // state w.r.t. the formal app-linkage "no verification attempted" state; 2739 // and then 'always' in the per-user state actually used for intent resolution. 2740 final IntentFilterVerificationInfo ivi; 2741 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2742 new ArrayList<String>(domains)); 2743 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2744 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2745 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2746 } else { 2747 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2748 + "' does not handle web links"); 2749 } 2750 } else { 2751 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2752 } 2753 } 2754 2755 scheduleWritePackageRestrictionsLocked(userId); 2756 scheduleWriteSettingsLocked(); 2757 } 2758 2759 private void applyFactoryDefaultBrowserLPw(int userId) { 2760 // The default browser app's package name is stored in a string resource, 2761 // with a product-specific overlay used for vendor customization. 2762 String browserPkg = mContext.getResources().getString( 2763 com.android.internal.R.string.default_browser); 2764 if (!TextUtils.isEmpty(browserPkg)) { 2765 // non-empty string => required to be a known package 2766 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2767 if (ps == null) { 2768 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2769 browserPkg = null; 2770 } else { 2771 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2772 } 2773 } 2774 2775 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2776 // default. If there's more than one, just leave everything alone. 2777 if (browserPkg == null) { 2778 calculateDefaultBrowserLPw(userId); 2779 } 2780 } 2781 2782 private void calculateDefaultBrowserLPw(int userId) { 2783 List<String> allBrowsers = resolveAllBrowserApps(userId); 2784 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2785 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2786 } 2787 2788 private List<String> resolveAllBrowserApps(int userId) { 2789 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2790 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2791 PackageManager.MATCH_ALL, userId); 2792 2793 final int count = list.size(); 2794 List<String> result = new ArrayList<String>(count); 2795 for (int i=0; i<count; i++) { 2796 ResolveInfo info = list.get(i); 2797 if (info.activityInfo == null 2798 || !info.handleAllWebDataURI 2799 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2800 || result.contains(info.activityInfo.packageName)) { 2801 continue; 2802 } 2803 result.add(info.activityInfo.packageName); 2804 } 2805 2806 return result; 2807 } 2808 2809 private boolean packageIsBrowser(String packageName, int userId) { 2810 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2811 PackageManager.MATCH_ALL, userId); 2812 final int N = list.size(); 2813 for (int i = 0; i < N; i++) { 2814 ResolveInfo info = list.get(i); 2815 if (packageName.equals(info.activityInfo.packageName)) { 2816 return true; 2817 } 2818 } 2819 return false; 2820 } 2821 2822 private void checkDefaultBrowser() { 2823 final int myUserId = UserHandle.myUserId(); 2824 final String packageName = getDefaultBrowserPackageName(myUserId); 2825 if (packageName != null) { 2826 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2827 if (info == null) { 2828 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2829 synchronized (mPackages) { 2830 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2831 } 2832 } 2833 } 2834 } 2835 2836 @Override 2837 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2838 throws RemoteException { 2839 try { 2840 return super.onTransact(code, data, reply, flags); 2841 } catch (RuntimeException e) { 2842 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2843 Slog.wtf(TAG, "Package Manager Crash", e); 2844 } 2845 throw e; 2846 } 2847 } 2848 2849 void cleanupInstallFailedPackage(PackageSetting ps) { 2850 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2851 2852 removeDataDirsLI(ps.volumeUuid, ps.name); 2853 if (ps.codePath != null) { 2854 removeCodePathLI(ps.codePath); 2855 } 2856 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2857 if (ps.resourcePath.isDirectory()) { 2858 FileUtils.deleteContents(ps.resourcePath); 2859 } 2860 ps.resourcePath.delete(); 2861 } 2862 mSettings.removePackageLPw(ps.name); 2863 } 2864 2865 static int[] appendInts(int[] cur, int[] add) { 2866 if (add == null) return cur; 2867 if (cur == null) return add; 2868 final int N = add.length; 2869 for (int i=0; i<N; i++) { 2870 cur = appendInt(cur, add[i]); 2871 } 2872 return cur; 2873 } 2874 2875 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2876 if (!sUserManager.exists(userId)) return null; 2877 final PackageSetting ps = (PackageSetting) p.mExtras; 2878 if (ps == null) { 2879 return null; 2880 } 2881 2882 final PermissionsState permissionsState = ps.getPermissionsState(); 2883 2884 final int[] gids = permissionsState.computeGids(userId); 2885 final Set<String> permissions = permissionsState.getPermissions(userId); 2886 final PackageUserState state = ps.readUserState(userId); 2887 2888 return PackageParser.generatePackageInfo(p, gids, flags, 2889 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2890 } 2891 2892 @Override 2893 public void checkPackageStartable(String packageName, int userId) { 2894 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 2895 2896 synchronized (mPackages) { 2897 final PackageSetting ps = mSettings.mPackages.get(packageName); 2898 if (ps == null) { 2899 throw new SecurityException("Package " + packageName + " was not found!"); 2900 } 2901 2902 if (!ps.getInstalled(userId)) { 2903 throw new SecurityException( 2904 "Package " + packageName + " was not installed for user " + userId + "!"); 2905 } 2906 2907 if (mSafeMode && !ps.isSystem()) { 2908 throw new SecurityException("Package " + packageName + " not a system app!"); 2909 } 2910 2911 if (ps.frozen) { 2912 throw new SecurityException("Package " + packageName + " is currently frozen!"); 2913 } 2914 2915 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 2916 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 2917 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 2918 } 2919 } 2920 } 2921 2922 @Override 2923 public boolean isPackageAvailable(String packageName, int userId) { 2924 if (!sUserManager.exists(userId)) return false; 2925 enforceCrossUserPermission(Binder.getCallingUid(), userId, 2926 false /* requireFullPermission */, false /* checkShell */, "is package available"); 2927 synchronized (mPackages) { 2928 PackageParser.Package p = mPackages.get(packageName); 2929 if (p != null) { 2930 final PackageSetting ps = (PackageSetting) p.mExtras; 2931 if (ps != null) { 2932 final PackageUserState state = ps.readUserState(userId); 2933 if (state != null) { 2934 return PackageParser.isAvailable(state); 2935 } 2936 } 2937 } 2938 } 2939 return false; 2940 } 2941 2942 @Override 2943 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2944 if (!sUserManager.exists(userId)) return null; 2945 flags = updateFlagsForPackage(flags, userId, packageName); 2946 enforceCrossUserPermission(Binder.getCallingUid(), userId, 2947 false /* requireFullPermission */, false /* checkShell */, "get package info"); 2948 // reader 2949 synchronized (mPackages) { 2950 PackageParser.Package p = mPackages.get(packageName); 2951 if (DEBUG_PACKAGE_INFO) 2952 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2953 if (p != null) { 2954 return generatePackageInfo(p, flags, userId); 2955 } 2956 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2957 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2958 } 2959 } 2960 return null; 2961 } 2962 2963 @Override 2964 public String[] currentToCanonicalPackageNames(String[] names) { 2965 String[] out = new String[names.length]; 2966 // reader 2967 synchronized (mPackages) { 2968 for (int i=names.length-1; i>=0; i--) { 2969 PackageSetting ps = mSettings.mPackages.get(names[i]); 2970 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2971 } 2972 } 2973 return out; 2974 } 2975 2976 @Override 2977 public String[] canonicalToCurrentPackageNames(String[] names) { 2978 String[] out = new String[names.length]; 2979 // reader 2980 synchronized (mPackages) { 2981 for (int i=names.length-1; i>=0; i--) { 2982 String cur = mSettings.mRenamedPackages.get(names[i]); 2983 out[i] = cur != null ? cur : names[i]; 2984 } 2985 } 2986 return out; 2987 } 2988 2989 @Override 2990 public int getPackageUid(String packageName, int flags, int userId) { 2991 if (!sUserManager.exists(userId)) return -1; 2992 flags = updateFlagsForPackage(flags, userId, packageName); 2993 enforceCrossUserPermission(Binder.getCallingUid(), userId, 2994 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 2995 2996 // reader 2997 synchronized (mPackages) { 2998 final PackageParser.Package p = mPackages.get(packageName); 2999 if (p != null && p.isMatch(flags)) { 3000 return UserHandle.getUid(userId, p.applicationInfo.uid); 3001 } 3002 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3003 final PackageSetting ps = mSettings.mPackages.get(packageName); 3004 if (ps != null && ps.isMatch(flags)) { 3005 return UserHandle.getUid(userId, ps.appId); 3006 } 3007 } 3008 } 3009 3010 return -1; 3011 } 3012 3013 @Override 3014 public int[] getPackageGids(String packageName, int flags, int userId) { 3015 if (!sUserManager.exists(userId)) return null; 3016 flags = updateFlagsForPackage(flags, userId, packageName); 3017 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3018 false /* requireFullPermission */, false /* checkShell */, 3019 "getPackageGids"); 3020 3021 // reader 3022 synchronized (mPackages) { 3023 final PackageParser.Package p = mPackages.get(packageName); 3024 if (p != null && p.isMatch(flags)) { 3025 PackageSetting ps = (PackageSetting) p.mExtras; 3026 return ps.getPermissionsState().computeGids(userId); 3027 } 3028 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3029 final PackageSetting ps = mSettings.mPackages.get(packageName); 3030 if (ps != null && ps.isMatch(flags)) { 3031 return ps.getPermissionsState().computeGids(userId); 3032 } 3033 } 3034 } 3035 3036 return null; 3037 } 3038 3039 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3040 if (bp.perm != null) { 3041 return PackageParser.generatePermissionInfo(bp.perm, flags); 3042 } 3043 PermissionInfo pi = new PermissionInfo(); 3044 pi.name = bp.name; 3045 pi.packageName = bp.sourcePackage; 3046 pi.nonLocalizedLabel = bp.name; 3047 pi.protectionLevel = bp.protectionLevel; 3048 return pi; 3049 } 3050 3051 @Override 3052 public PermissionInfo getPermissionInfo(String name, int flags) { 3053 // reader 3054 synchronized (mPackages) { 3055 final BasePermission p = mSettings.mPermissions.get(name); 3056 if (p != null) { 3057 return generatePermissionInfo(p, flags); 3058 } 3059 return null; 3060 } 3061 } 3062 3063 @Override 3064 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3065 int flags) { 3066 // reader 3067 synchronized (mPackages) { 3068 if (group != null && !mPermissionGroups.containsKey(group)) { 3069 // This is thrown as NameNotFoundException 3070 return null; 3071 } 3072 3073 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3074 for (BasePermission p : mSettings.mPermissions.values()) { 3075 if (group == null) { 3076 if (p.perm == null || p.perm.info.group == null) { 3077 out.add(generatePermissionInfo(p, flags)); 3078 } 3079 } else { 3080 if (p.perm != null && group.equals(p.perm.info.group)) { 3081 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3082 } 3083 } 3084 } 3085 return new ParceledListSlice<>(out); 3086 } 3087 } 3088 3089 @Override 3090 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3091 // reader 3092 synchronized (mPackages) { 3093 return PackageParser.generatePermissionGroupInfo( 3094 mPermissionGroups.get(name), flags); 3095 } 3096 } 3097 3098 @Override 3099 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3100 // reader 3101 synchronized (mPackages) { 3102 final int N = mPermissionGroups.size(); 3103 ArrayList<PermissionGroupInfo> out 3104 = new ArrayList<PermissionGroupInfo>(N); 3105 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3106 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3107 } 3108 return new ParceledListSlice<>(out); 3109 } 3110 } 3111 3112 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3113 int userId) { 3114 if (!sUserManager.exists(userId)) return null; 3115 PackageSetting ps = mSettings.mPackages.get(packageName); 3116 if (ps != null) { 3117 if (ps.pkg == null) { 3118 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 3119 flags, userId); 3120 if (pInfo != null) { 3121 return pInfo.applicationInfo; 3122 } 3123 return null; 3124 } 3125 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3126 ps.readUserState(userId), userId); 3127 } 3128 return null; 3129 } 3130 3131 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 3132 int userId) { 3133 if (!sUserManager.exists(userId)) return null; 3134 PackageSetting ps = mSettings.mPackages.get(packageName); 3135 if (ps != null) { 3136 PackageParser.Package pkg = ps.pkg; 3137 if (pkg == null) { 3138 if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) { 3139 return null; 3140 } 3141 // Only data remains, so we aren't worried about code paths 3142 pkg = new PackageParser.Package(packageName); 3143 pkg.applicationInfo.packageName = packageName; 3144 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 3145 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 3146 pkg.applicationInfo.uid = ps.appId; 3147 pkg.applicationInfo.initForUser(userId); 3148 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 3149 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 3150 } 3151 return generatePackageInfo(pkg, flags, userId); 3152 } 3153 return null; 3154 } 3155 3156 @Override 3157 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3158 if (!sUserManager.exists(userId)) return null; 3159 flags = updateFlagsForApplication(flags, userId, packageName); 3160 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3161 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3162 // writer 3163 synchronized (mPackages) { 3164 PackageParser.Package p = mPackages.get(packageName); 3165 if (DEBUG_PACKAGE_INFO) Log.v( 3166 TAG, "getApplicationInfo " + packageName 3167 + ": " + p); 3168 if (p != null) { 3169 PackageSetting ps = mSettings.mPackages.get(packageName); 3170 if (ps == null) return null; 3171 // Note: isEnabledLP() does not apply here - always return info 3172 return PackageParser.generateApplicationInfo( 3173 p, flags, ps.readUserState(userId), userId); 3174 } 3175 if ("android".equals(packageName)||"system".equals(packageName)) { 3176 return mAndroidApplication; 3177 } 3178 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3179 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3180 } 3181 } 3182 return null; 3183 } 3184 3185 @Override 3186 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3187 final IPackageDataObserver observer) { 3188 mContext.enforceCallingOrSelfPermission( 3189 android.Manifest.permission.CLEAR_APP_CACHE, null); 3190 // Queue up an async operation since clearing cache may take a little while. 3191 mHandler.post(new Runnable() { 3192 public void run() { 3193 mHandler.removeCallbacks(this); 3194 boolean success = true; 3195 synchronized (mInstallLock) { 3196 try { 3197 mInstaller.freeCache(volumeUuid, freeStorageSize); 3198 } catch (InstallerException e) { 3199 Slog.w(TAG, "Couldn't clear application caches: " + e); 3200 success = false; 3201 } 3202 } 3203 if (observer != null) { 3204 try { 3205 observer.onRemoveCompleted(null, success); 3206 } catch (RemoteException e) { 3207 Slog.w(TAG, "RemoveException when invoking call back"); 3208 } 3209 } 3210 } 3211 }); 3212 } 3213 3214 @Override 3215 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3216 final IntentSender pi) { 3217 mContext.enforceCallingOrSelfPermission( 3218 android.Manifest.permission.CLEAR_APP_CACHE, null); 3219 // Queue up an async operation since clearing cache may take a little while. 3220 mHandler.post(new Runnable() { 3221 public void run() { 3222 mHandler.removeCallbacks(this); 3223 boolean success = true; 3224 synchronized (mInstallLock) { 3225 try { 3226 mInstaller.freeCache(volumeUuid, freeStorageSize); 3227 } catch (InstallerException e) { 3228 Slog.w(TAG, "Couldn't clear application caches: " + e); 3229 success = false; 3230 } 3231 } 3232 if(pi != null) { 3233 try { 3234 // Callback via pending intent 3235 int code = success ? 1 : 0; 3236 pi.sendIntent(null, code, null, 3237 null, null); 3238 } catch (SendIntentException e1) { 3239 Slog.i(TAG, "Failed to send pending intent"); 3240 } 3241 } 3242 } 3243 }); 3244 } 3245 3246 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3247 synchronized (mInstallLock) { 3248 try { 3249 mInstaller.freeCache(volumeUuid, freeStorageSize); 3250 } catch (InstallerException e) { 3251 throw new IOException("Failed to free enough space", e); 3252 } 3253 } 3254 } 3255 3256 /** 3257 * Return if the user key is currently unlocked. 3258 */ 3259 private boolean isUserKeyUnlocked(int userId) { 3260 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 3261 final IMountService mount = IMountService.Stub 3262 .asInterface(ServiceManager.getService("mount")); 3263 if (mount == null) { 3264 Slog.w(TAG, "Early during boot, assuming locked"); 3265 return false; 3266 } 3267 final long token = Binder.clearCallingIdentity(); 3268 try { 3269 return mount.isUserKeyUnlocked(userId); 3270 } catch (RemoteException e) { 3271 throw e.rethrowAsRuntimeException(); 3272 } finally { 3273 Binder.restoreCallingIdentity(token); 3274 } 3275 } else { 3276 return true; 3277 } 3278 } 3279 3280 /** 3281 * Update given flags based on encryption status of current user. 3282 */ 3283 private int updateFlags(int flags, int userId) { 3284 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3285 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3286 // Caller expressed an explicit opinion about what encryption 3287 // aware/unaware components they want to see, so fall through and 3288 // give them what they want 3289 } else { 3290 // Caller expressed no opinion, so match based on user state 3291 if (isUserKeyUnlocked(userId)) { 3292 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3293 } else { 3294 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3295 } 3296 } 3297 return flags; 3298 } 3299 3300 /** 3301 * Update given flags when being used to request {@link PackageInfo}. 3302 */ 3303 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3304 boolean triaged = true; 3305 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3306 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3307 // Caller is asking for component details, so they'd better be 3308 // asking for specific encryption matching behavior, or be triaged 3309 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3310 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3311 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3312 triaged = false; 3313 } 3314 } 3315 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3316 | PackageManager.MATCH_SYSTEM_ONLY 3317 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3318 triaged = false; 3319 } 3320 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3321 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3322 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3323 } 3324 return updateFlags(flags, userId); 3325 } 3326 3327 /** 3328 * Update given flags when being used to request {@link ApplicationInfo}. 3329 */ 3330 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3331 return updateFlagsForPackage(flags, userId, cookie); 3332 } 3333 3334 /** 3335 * Update given flags when being used to request {@link ComponentInfo}. 3336 */ 3337 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3338 if (cookie instanceof Intent) { 3339 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3340 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3341 } 3342 } 3343 3344 boolean triaged = true; 3345 // Caller is asking for component details, so they'd better be 3346 // asking for specific encryption matching behavior, or be triaged 3347 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3348 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3349 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3350 triaged = false; 3351 } 3352 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3353 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3354 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3355 } 3356 3357 return updateFlags(flags, userId); 3358 } 3359 3360 /** 3361 * Update given flags when being used to request {@link ResolveInfo}. 3362 */ 3363 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3364 // Safe mode means we shouldn't match any third-party components 3365 if (mSafeMode) { 3366 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3367 } 3368 3369 return updateFlagsForComponent(flags, userId, cookie); 3370 } 3371 3372 @Override 3373 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3374 if (!sUserManager.exists(userId)) return null; 3375 flags = updateFlagsForComponent(flags, userId, component); 3376 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3377 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3378 synchronized (mPackages) { 3379 PackageParser.Activity a = mActivities.mActivities.get(component); 3380 3381 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3382 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3383 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3384 if (ps == null) return null; 3385 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3386 userId); 3387 } 3388 if (mResolveComponentName.equals(component)) { 3389 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3390 new PackageUserState(), userId); 3391 } 3392 } 3393 return null; 3394 } 3395 3396 @Override 3397 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3398 String resolvedType) { 3399 synchronized (mPackages) { 3400 if (component.equals(mResolveComponentName)) { 3401 // The resolver supports EVERYTHING! 3402 return true; 3403 } 3404 PackageParser.Activity a = mActivities.mActivities.get(component); 3405 if (a == null) { 3406 return false; 3407 } 3408 for (int i=0; i<a.intents.size(); i++) { 3409 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3410 intent.getData(), intent.getCategories(), TAG) >= 0) { 3411 return true; 3412 } 3413 } 3414 return false; 3415 } 3416 } 3417 3418 @Override 3419 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3420 if (!sUserManager.exists(userId)) return null; 3421 flags = updateFlagsForComponent(flags, userId, component); 3422 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3423 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3424 synchronized (mPackages) { 3425 PackageParser.Activity a = mReceivers.mActivities.get(component); 3426 if (DEBUG_PACKAGE_INFO) Log.v( 3427 TAG, "getReceiverInfo " + component + ": " + a); 3428 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3429 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3430 if (ps == null) return null; 3431 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3432 userId); 3433 } 3434 } 3435 return null; 3436 } 3437 3438 @Override 3439 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3440 if (!sUserManager.exists(userId)) return null; 3441 flags = updateFlagsForComponent(flags, userId, component); 3442 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3443 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3444 synchronized (mPackages) { 3445 PackageParser.Service s = mServices.mServices.get(component); 3446 if (DEBUG_PACKAGE_INFO) Log.v( 3447 TAG, "getServiceInfo " + component + ": " + s); 3448 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3449 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3450 if (ps == null) return null; 3451 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3452 userId); 3453 } 3454 } 3455 return null; 3456 } 3457 3458 @Override 3459 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3460 if (!sUserManager.exists(userId)) return null; 3461 flags = updateFlagsForComponent(flags, userId, component); 3462 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3463 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3464 synchronized (mPackages) { 3465 PackageParser.Provider p = mProviders.mProviders.get(component); 3466 if (DEBUG_PACKAGE_INFO) Log.v( 3467 TAG, "getProviderInfo " + component + ": " + p); 3468 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3469 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3470 if (ps == null) return null; 3471 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3472 userId); 3473 } 3474 } 3475 return null; 3476 } 3477 3478 @Override 3479 public String[] getSystemSharedLibraryNames() { 3480 Set<String> libSet; 3481 synchronized (mPackages) { 3482 libSet = mSharedLibraries.keySet(); 3483 int size = libSet.size(); 3484 if (size > 0) { 3485 String[] libs = new String[size]; 3486 libSet.toArray(libs); 3487 return libs; 3488 } 3489 } 3490 return null; 3491 } 3492 3493 @Override 3494 public @Nullable String getServicesSystemSharedLibraryPackageName() { 3495 synchronized (mPackages) { 3496 SharedLibraryEntry libraryEntry = mSharedLibraries.get( 3497 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 3498 if (libraryEntry != null) { 3499 return libraryEntry.apk; 3500 } 3501 } 3502 return null; 3503 } 3504 3505 @Override 3506 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3507 synchronized (mPackages) { 3508 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3509 3510 final FeatureInfo fi = new FeatureInfo(); 3511 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3512 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3513 res.add(fi); 3514 3515 return new ParceledListSlice<>(res); 3516 } 3517 } 3518 3519 @Override 3520 public boolean hasSystemFeature(String name, int version) { 3521 synchronized (mPackages) { 3522 final FeatureInfo feat = mAvailableFeatures.get(name); 3523 if (feat == null) { 3524 return false; 3525 } else { 3526 return feat.version >= version; 3527 } 3528 } 3529 } 3530 3531 @Override 3532 public int checkPermission(String permName, String pkgName, int userId) { 3533 if (!sUserManager.exists(userId)) { 3534 return PackageManager.PERMISSION_DENIED; 3535 } 3536 3537 synchronized (mPackages) { 3538 final PackageParser.Package p = mPackages.get(pkgName); 3539 if (p != null && p.mExtras != null) { 3540 final PackageSetting ps = (PackageSetting) p.mExtras; 3541 final PermissionsState permissionsState = ps.getPermissionsState(); 3542 if (permissionsState.hasPermission(permName, userId)) { 3543 return PackageManager.PERMISSION_GRANTED; 3544 } 3545 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3546 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3547 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3548 return PackageManager.PERMISSION_GRANTED; 3549 } 3550 } 3551 } 3552 3553 return PackageManager.PERMISSION_DENIED; 3554 } 3555 3556 @Override 3557 public int checkUidPermission(String permName, int uid) { 3558 final int userId = UserHandle.getUserId(uid); 3559 3560 if (!sUserManager.exists(userId)) { 3561 return PackageManager.PERMISSION_DENIED; 3562 } 3563 3564 synchronized (mPackages) { 3565 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3566 if (obj != null) { 3567 final SettingBase ps = (SettingBase) obj; 3568 final PermissionsState permissionsState = ps.getPermissionsState(); 3569 if (permissionsState.hasPermission(permName, userId)) { 3570 return PackageManager.PERMISSION_GRANTED; 3571 } 3572 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3573 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3574 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3575 return PackageManager.PERMISSION_GRANTED; 3576 } 3577 } else { 3578 ArraySet<String> perms = mSystemPermissions.get(uid); 3579 if (perms != null) { 3580 if (perms.contains(permName)) { 3581 return PackageManager.PERMISSION_GRANTED; 3582 } 3583 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3584 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3585 return PackageManager.PERMISSION_GRANTED; 3586 } 3587 } 3588 } 3589 } 3590 3591 return PackageManager.PERMISSION_DENIED; 3592 } 3593 3594 @Override 3595 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3596 if (UserHandle.getCallingUserId() != userId) { 3597 mContext.enforceCallingPermission( 3598 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3599 "isPermissionRevokedByPolicy for user " + userId); 3600 } 3601 3602 if (checkPermission(permission, packageName, userId) 3603 == PackageManager.PERMISSION_GRANTED) { 3604 return false; 3605 } 3606 3607 final long identity = Binder.clearCallingIdentity(); 3608 try { 3609 final int flags = getPermissionFlags(permission, packageName, userId); 3610 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3611 } finally { 3612 Binder.restoreCallingIdentity(identity); 3613 } 3614 } 3615 3616 @Override 3617 public String getPermissionControllerPackageName() { 3618 synchronized (mPackages) { 3619 return mRequiredInstallerPackage; 3620 } 3621 } 3622 3623 /** 3624 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3625 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3626 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3627 * @param message the message to log on security exception 3628 */ 3629 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3630 boolean checkShell, String message) { 3631 if (userId < 0) { 3632 throw new IllegalArgumentException("Invalid userId " + userId); 3633 } 3634 if (checkShell) { 3635 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3636 } 3637 if (userId == UserHandle.getUserId(callingUid)) return; 3638 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3639 if (requireFullPermission) { 3640 mContext.enforceCallingOrSelfPermission( 3641 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3642 } else { 3643 try { 3644 mContext.enforceCallingOrSelfPermission( 3645 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3646 } catch (SecurityException se) { 3647 mContext.enforceCallingOrSelfPermission( 3648 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3649 } 3650 } 3651 } 3652 } 3653 3654 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3655 if (callingUid == Process.SHELL_UID) { 3656 if (userHandle >= 0 3657 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3658 throw new SecurityException("Shell does not have permission to access user " 3659 + userHandle); 3660 } else if (userHandle < 0) { 3661 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3662 + Debug.getCallers(3)); 3663 } 3664 } 3665 } 3666 3667 private BasePermission findPermissionTreeLP(String permName) { 3668 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3669 if (permName.startsWith(bp.name) && 3670 permName.length() > bp.name.length() && 3671 permName.charAt(bp.name.length()) == '.') { 3672 return bp; 3673 } 3674 } 3675 return null; 3676 } 3677 3678 private BasePermission checkPermissionTreeLP(String permName) { 3679 if (permName != null) { 3680 BasePermission bp = findPermissionTreeLP(permName); 3681 if (bp != null) { 3682 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3683 return bp; 3684 } 3685 throw new SecurityException("Calling uid " 3686 + Binder.getCallingUid() 3687 + " is not allowed to add to permission tree " 3688 + bp.name + " owned by uid " + bp.uid); 3689 } 3690 } 3691 throw new SecurityException("No permission tree found for " + permName); 3692 } 3693 3694 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3695 if (s1 == null) { 3696 return s2 == null; 3697 } 3698 if (s2 == null) { 3699 return false; 3700 } 3701 if (s1.getClass() != s2.getClass()) { 3702 return false; 3703 } 3704 return s1.equals(s2); 3705 } 3706 3707 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3708 if (pi1.icon != pi2.icon) return false; 3709 if (pi1.logo != pi2.logo) return false; 3710 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3711 if (!compareStrings(pi1.name, pi2.name)) return false; 3712 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3713 // We'll take care of setting this one. 3714 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3715 // These are not currently stored in settings. 3716 //if (!compareStrings(pi1.group, pi2.group)) return false; 3717 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3718 //if (pi1.labelRes != pi2.labelRes) return false; 3719 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3720 return true; 3721 } 3722 3723 int permissionInfoFootprint(PermissionInfo info) { 3724 int size = info.name.length(); 3725 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3726 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3727 return size; 3728 } 3729 3730 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3731 int size = 0; 3732 for (BasePermission perm : mSettings.mPermissions.values()) { 3733 if (perm.uid == tree.uid) { 3734 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3735 } 3736 } 3737 return size; 3738 } 3739 3740 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3741 // We calculate the max size of permissions defined by this uid and throw 3742 // if that plus the size of 'info' would exceed our stated maximum. 3743 if (tree.uid != Process.SYSTEM_UID) { 3744 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3745 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3746 throw new SecurityException("Permission tree size cap exceeded"); 3747 } 3748 } 3749 } 3750 3751 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3752 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3753 throw new SecurityException("Label must be specified in permission"); 3754 } 3755 BasePermission tree = checkPermissionTreeLP(info.name); 3756 BasePermission bp = mSettings.mPermissions.get(info.name); 3757 boolean added = bp == null; 3758 boolean changed = true; 3759 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3760 if (added) { 3761 enforcePermissionCapLocked(info, tree); 3762 bp = new BasePermission(info.name, tree.sourcePackage, 3763 BasePermission.TYPE_DYNAMIC); 3764 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3765 throw new SecurityException( 3766 "Not allowed to modify non-dynamic permission " 3767 + info.name); 3768 } else { 3769 if (bp.protectionLevel == fixedLevel 3770 && bp.perm.owner.equals(tree.perm.owner) 3771 && bp.uid == tree.uid 3772 && comparePermissionInfos(bp.perm.info, info)) { 3773 changed = false; 3774 } 3775 } 3776 bp.protectionLevel = fixedLevel; 3777 info = new PermissionInfo(info); 3778 info.protectionLevel = fixedLevel; 3779 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3780 bp.perm.info.packageName = tree.perm.info.packageName; 3781 bp.uid = tree.uid; 3782 if (added) { 3783 mSettings.mPermissions.put(info.name, bp); 3784 } 3785 if (changed) { 3786 if (!async) { 3787 mSettings.writeLPr(); 3788 } else { 3789 scheduleWriteSettingsLocked(); 3790 } 3791 } 3792 return added; 3793 } 3794 3795 @Override 3796 public boolean addPermission(PermissionInfo info) { 3797 synchronized (mPackages) { 3798 return addPermissionLocked(info, false); 3799 } 3800 } 3801 3802 @Override 3803 public boolean addPermissionAsync(PermissionInfo info) { 3804 synchronized (mPackages) { 3805 return addPermissionLocked(info, true); 3806 } 3807 } 3808 3809 @Override 3810 public void removePermission(String name) { 3811 synchronized (mPackages) { 3812 checkPermissionTreeLP(name); 3813 BasePermission bp = mSettings.mPermissions.get(name); 3814 if (bp != null) { 3815 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3816 throw new SecurityException( 3817 "Not allowed to modify non-dynamic permission " 3818 + name); 3819 } 3820 mSettings.mPermissions.remove(name); 3821 mSettings.writeLPr(); 3822 } 3823 } 3824 } 3825 3826 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3827 BasePermission bp) { 3828 int index = pkg.requestedPermissions.indexOf(bp.name); 3829 if (index == -1) { 3830 throw new SecurityException("Package " + pkg.packageName 3831 + " has not requested permission " + bp.name); 3832 } 3833 if (!bp.isRuntime() && !bp.isDevelopment()) { 3834 throw new SecurityException("Permission " + bp.name 3835 + " is not a changeable permission type"); 3836 } 3837 } 3838 3839 @Override 3840 public void grantRuntimePermission(String packageName, String name, final int userId) { 3841 if (!sUserManager.exists(userId)) { 3842 Log.e(TAG, "No such user:" + userId); 3843 return; 3844 } 3845 3846 mContext.enforceCallingOrSelfPermission( 3847 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3848 "grantRuntimePermission"); 3849 3850 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3851 true /* requireFullPermission */, true /* checkShell */, 3852 "grantRuntimePermission"); 3853 3854 final int uid; 3855 final SettingBase sb; 3856 3857 synchronized (mPackages) { 3858 final PackageParser.Package pkg = mPackages.get(packageName); 3859 if (pkg == null) { 3860 throw new IllegalArgumentException("Unknown package: " + packageName); 3861 } 3862 3863 final BasePermission bp = mSettings.mPermissions.get(name); 3864 if (bp == null) { 3865 throw new IllegalArgumentException("Unknown permission: " + name); 3866 } 3867 3868 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3869 3870 // If a permission review is required for legacy apps we represent 3871 // their permissions as always granted runtime ones since we need 3872 // to keep the review required permission flag per user while an 3873 // install permission's state is shared across all users. 3874 if (Build.PERMISSIONS_REVIEW_REQUIRED 3875 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3876 && bp.isRuntime()) { 3877 return; 3878 } 3879 3880 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3881 sb = (SettingBase) pkg.mExtras; 3882 if (sb == null) { 3883 throw new IllegalArgumentException("Unknown package: " + packageName); 3884 } 3885 3886 final PermissionsState permissionsState = sb.getPermissionsState(); 3887 3888 final int flags = permissionsState.getPermissionFlags(name, userId); 3889 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3890 throw new SecurityException("Cannot grant system fixed permission " 3891 + name + " for package " + packageName); 3892 } 3893 3894 if (bp.isDevelopment()) { 3895 // Development permissions must be handled specially, since they are not 3896 // normal runtime permissions. For now they apply to all users. 3897 if (permissionsState.grantInstallPermission(bp) != 3898 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3899 scheduleWriteSettingsLocked(); 3900 } 3901 return; 3902 } 3903 3904 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 3905 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 3906 return; 3907 } 3908 3909 final int result = permissionsState.grantRuntimePermission(bp, userId); 3910 switch (result) { 3911 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3912 return; 3913 } 3914 3915 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3916 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3917 mHandler.post(new Runnable() { 3918 @Override 3919 public void run() { 3920 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3921 } 3922 }); 3923 } 3924 break; 3925 } 3926 3927 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3928 3929 // Not critical if that is lost - app has to request again. 3930 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3931 } 3932 3933 // Only need to do this if user is initialized. Otherwise it's a new user 3934 // and there are no processes running as the user yet and there's no need 3935 // to make an expensive call to remount processes for the changed permissions. 3936 if (READ_EXTERNAL_STORAGE.equals(name) 3937 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3938 final long token = Binder.clearCallingIdentity(); 3939 try { 3940 if (sUserManager.isInitialized(userId)) { 3941 MountServiceInternal mountServiceInternal = LocalServices.getService( 3942 MountServiceInternal.class); 3943 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3944 } 3945 } finally { 3946 Binder.restoreCallingIdentity(token); 3947 } 3948 } 3949 } 3950 3951 @Override 3952 public void revokeRuntimePermission(String packageName, String name, int userId) { 3953 if (!sUserManager.exists(userId)) { 3954 Log.e(TAG, "No such user:" + userId); 3955 return; 3956 } 3957 3958 mContext.enforceCallingOrSelfPermission( 3959 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3960 "revokeRuntimePermission"); 3961 3962 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3963 true /* requireFullPermission */, true /* checkShell */, 3964 "revokeRuntimePermission"); 3965 3966 final int appId; 3967 3968 synchronized (mPackages) { 3969 final PackageParser.Package pkg = mPackages.get(packageName); 3970 if (pkg == null) { 3971 throw new IllegalArgumentException("Unknown package: " + packageName); 3972 } 3973 3974 final BasePermission bp = mSettings.mPermissions.get(name); 3975 if (bp == null) { 3976 throw new IllegalArgumentException("Unknown permission: " + name); 3977 } 3978 3979 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3980 3981 // If a permission review is required for legacy apps we represent 3982 // their permissions as always granted runtime ones since we need 3983 // to keep the review required permission flag per user while an 3984 // install permission's state is shared across all users. 3985 if (Build.PERMISSIONS_REVIEW_REQUIRED 3986 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3987 && bp.isRuntime()) { 3988 return; 3989 } 3990 3991 SettingBase sb = (SettingBase) pkg.mExtras; 3992 if (sb == null) { 3993 throw new IllegalArgumentException("Unknown package: " + packageName); 3994 } 3995 3996 final PermissionsState permissionsState = sb.getPermissionsState(); 3997 3998 final int flags = permissionsState.getPermissionFlags(name, userId); 3999 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4000 throw new SecurityException("Cannot revoke system fixed permission " 4001 + name + " for package " + packageName); 4002 } 4003 4004 if (bp.isDevelopment()) { 4005 // Development permissions must be handled specially, since they are not 4006 // normal runtime permissions. For now they apply to all users. 4007 if (permissionsState.revokeInstallPermission(bp) != 4008 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4009 scheduleWriteSettingsLocked(); 4010 } 4011 return; 4012 } 4013 4014 if (permissionsState.revokeRuntimePermission(bp, userId) == 4015 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4016 return; 4017 } 4018 4019 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4020 4021 // Critical, after this call app should never have the permission. 4022 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4023 4024 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4025 } 4026 4027 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4028 } 4029 4030 @Override 4031 public void resetRuntimePermissions() { 4032 mContext.enforceCallingOrSelfPermission( 4033 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4034 "revokeRuntimePermission"); 4035 4036 int callingUid = Binder.getCallingUid(); 4037 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4038 mContext.enforceCallingOrSelfPermission( 4039 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4040 "resetRuntimePermissions"); 4041 } 4042 4043 synchronized (mPackages) { 4044 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4045 for (int userId : UserManagerService.getInstance().getUserIds()) { 4046 final int packageCount = mPackages.size(); 4047 for (int i = 0; i < packageCount; i++) { 4048 PackageParser.Package pkg = mPackages.valueAt(i); 4049 if (!(pkg.mExtras instanceof PackageSetting)) { 4050 continue; 4051 } 4052 PackageSetting ps = (PackageSetting) pkg.mExtras; 4053 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4054 } 4055 } 4056 } 4057 } 4058 4059 @Override 4060 public int getPermissionFlags(String name, String packageName, int userId) { 4061 if (!sUserManager.exists(userId)) { 4062 return 0; 4063 } 4064 4065 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4066 4067 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4068 true /* requireFullPermission */, false /* checkShell */, 4069 "getPermissionFlags"); 4070 4071 synchronized (mPackages) { 4072 final PackageParser.Package pkg = mPackages.get(packageName); 4073 if (pkg == null) { 4074 throw new IllegalArgumentException("Unknown package: " + packageName); 4075 } 4076 4077 final BasePermission bp = mSettings.mPermissions.get(name); 4078 if (bp == null) { 4079 throw new IllegalArgumentException("Unknown permission: " + name); 4080 } 4081 4082 SettingBase sb = (SettingBase) pkg.mExtras; 4083 if (sb == null) { 4084 throw new IllegalArgumentException("Unknown package: " + packageName); 4085 } 4086 4087 PermissionsState permissionsState = sb.getPermissionsState(); 4088 return permissionsState.getPermissionFlags(name, userId); 4089 } 4090 } 4091 4092 @Override 4093 public void updatePermissionFlags(String name, String packageName, int flagMask, 4094 int flagValues, int userId) { 4095 if (!sUserManager.exists(userId)) { 4096 return; 4097 } 4098 4099 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4100 4101 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4102 true /* requireFullPermission */, true /* checkShell */, 4103 "updatePermissionFlags"); 4104 4105 // Only the system can change these flags and nothing else. 4106 if (getCallingUid() != Process.SYSTEM_UID) { 4107 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4108 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4109 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4110 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4111 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4112 } 4113 4114 synchronized (mPackages) { 4115 final PackageParser.Package pkg = mPackages.get(packageName); 4116 if (pkg == null) { 4117 throw new IllegalArgumentException("Unknown package: " + packageName); 4118 } 4119 4120 final BasePermission bp = mSettings.mPermissions.get(name); 4121 if (bp == null) { 4122 throw new IllegalArgumentException("Unknown permission: " + name); 4123 } 4124 4125 SettingBase sb = (SettingBase) pkg.mExtras; 4126 if (sb == null) { 4127 throw new IllegalArgumentException("Unknown package: " + packageName); 4128 } 4129 4130 PermissionsState permissionsState = sb.getPermissionsState(); 4131 4132 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4133 4134 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4135 // Install and runtime permissions are stored in different places, 4136 // so figure out what permission changed and persist the change. 4137 if (permissionsState.getInstallPermissionState(name) != null) { 4138 scheduleWriteSettingsLocked(); 4139 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4140 || hadState) { 4141 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4142 } 4143 } 4144 } 4145 } 4146 4147 /** 4148 * Update the permission flags for all packages and runtime permissions of a user in order 4149 * to allow device or profile owner to remove POLICY_FIXED. 4150 */ 4151 @Override 4152 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4153 if (!sUserManager.exists(userId)) { 4154 return; 4155 } 4156 4157 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4158 4159 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4160 true /* requireFullPermission */, true /* checkShell */, 4161 "updatePermissionFlagsForAllApps"); 4162 4163 // Only the system can change system fixed flags. 4164 if (getCallingUid() != Process.SYSTEM_UID) { 4165 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4166 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4167 } 4168 4169 synchronized (mPackages) { 4170 boolean changed = false; 4171 final int packageCount = mPackages.size(); 4172 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4173 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4174 SettingBase sb = (SettingBase) pkg.mExtras; 4175 if (sb == null) { 4176 continue; 4177 } 4178 PermissionsState permissionsState = sb.getPermissionsState(); 4179 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4180 userId, flagMask, flagValues); 4181 } 4182 if (changed) { 4183 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4184 } 4185 } 4186 } 4187 4188 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4189 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4190 != PackageManager.PERMISSION_GRANTED 4191 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4192 != PackageManager.PERMISSION_GRANTED) { 4193 throw new SecurityException(message + " requires " 4194 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4195 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4196 } 4197 } 4198 4199 @Override 4200 public boolean shouldShowRequestPermissionRationale(String permissionName, 4201 String packageName, int userId) { 4202 if (UserHandle.getCallingUserId() != userId) { 4203 mContext.enforceCallingPermission( 4204 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4205 "canShowRequestPermissionRationale for user " + userId); 4206 } 4207 4208 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4209 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4210 return false; 4211 } 4212 4213 if (checkPermission(permissionName, packageName, userId) 4214 == PackageManager.PERMISSION_GRANTED) { 4215 return false; 4216 } 4217 4218 final int flags; 4219 4220 final long identity = Binder.clearCallingIdentity(); 4221 try { 4222 flags = getPermissionFlags(permissionName, 4223 packageName, userId); 4224 } finally { 4225 Binder.restoreCallingIdentity(identity); 4226 } 4227 4228 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4229 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4230 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4231 4232 if ((flags & fixedFlags) != 0) { 4233 return false; 4234 } 4235 4236 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4237 } 4238 4239 @Override 4240 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4241 mContext.enforceCallingOrSelfPermission( 4242 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4243 "addOnPermissionsChangeListener"); 4244 4245 synchronized (mPackages) { 4246 mOnPermissionChangeListeners.addListenerLocked(listener); 4247 } 4248 } 4249 4250 @Override 4251 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4252 synchronized (mPackages) { 4253 mOnPermissionChangeListeners.removeListenerLocked(listener); 4254 } 4255 } 4256 4257 @Override 4258 public boolean isProtectedBroadcast(String actionName) { 4259 synchronized (mPackages) { 4260 if (mProtectedBroadcasts.contains(actionName)) { 4261 return true; 4262 } else if (actionName != null) { 4263 // TODO: remove these terrible hacks 4264 if (actionName.startsWith("android.net.netmon.lingerExpired") 4265 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4266 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4267 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4268 return true; 4269 } 4270 } 4271 } 4272 return false; 4273 } 4274 4275 @Override 4276 public int checkSignatures(String pkg1, String pkg2) { 4277 synchronized (mPackages) { 4278 final PackageParser.Package p1 = mPackages.get(pkg1); 4279 final PackageParser.Package p2 = mPackages.get(pkg2); 4280 if (p1 == null || p1.mExtras == null 4281 || p2 == null || p2.mExtras == null) { 4282 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4283 } 4284 return compareSignatures(p1.mSignatures, p2.mSignatures); 4285 } 4286 } 4287 4288 @Override 4289 public int checkUidSignatures(int uid1, int uid2) { 4290 // Map to base uids. 4291 uid1 = UserHandle.getAppId(uid1); 4292 uid2 = UserHandle.getAppId(uid2); 4293 // reader 4294 synchronized (mPackages) { 4295 Signature[] s1; 4296 Signature[] s2; 4297 Object obj = mSettings.getUserIdLPr(uid1); 4298 if (obj != null) { 4299 if (obj instanceof SharedUserSetting) { 4300 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4301 } else if (obj instanceof PackageSetting) { 4302 s1 = ((PackageSetting)obj).signatures.mSignatures; 4303 } else { 4304 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4305 } 4306 } else { 4307 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4308 } 4309 obj = mSettings.getUserIdLPr(uid2); 4310 if (obj != null) { 4311 if (obj instanceof SharedUserSetting) { 4312 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4313 } else if (obj instanceof PackageSetting) { 4314 s2 = ((PackageSetting)obj).signatures.mSignatures; 4315 } else { 4316 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4317 } 4318 } else { 4319 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4320 } 4321 return compareSignatures(s1, s2); 4322 } 4323 } 4324 4325 private void killUid(int appId, int userId, String reason) { 4326 final long identity = Binder.clearCallingIdentity(); 4327 try { 4328 IActivityManager am = ActivityManagerNative.getDefault(); 4329 if (am != null) { 4330 try { 4331 am.killUid(appId, userId, reason); 4332 } catch (RemoteException e) { 4333 /* ignore - same process */ 4334 } 4335 } 4336 } finally { 4337 Binder.restoreCallingIdentity(identity); 4338 } 4339 } 4340 4341 /** 4342 * Compares two sets of signatures. Returns: 4343 * <br /> 4344 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4345 * <br /> 4346 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4347 * <br /> 4348 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4349 * <br /> 4350 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4351 * <br /> 4352 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4353 */ 4354 static int compareSignatures(Signature[] s1, Signature[] s2) { 4355 if (s1 == null) { 4356 return s2 == null 4357 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4358 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4359 } 4360 4361 if (s2 == null) { 4362 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4363 } 4364 4365 if (s1.length != s2.length) { 4366 return PackageManager.SIGNATURE_NO_MATCH; 4367 } 4368 4369 // Since both signature sets are of size 1, we can compare without HashSets. 4370 if (s1.length == 1) { 4371 return s1[0].equals(s2[0]) ? 4372 PackageManager.SIGNATURE_MATCH : 4373 PackageManager.SIGNATURE_NO_MATCH; 4374 } 4375 4376 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4377 for (Signature sig : s1) { 4378 set1.add(sig); 4379 } 4380 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4381 for (Signature sig : s2) { 4382 set2.add(sig); 4383 } 4384 // Make sure s2 contains all signatures in s1. 4385 if (set1.equals(set2)) { 4386 return PackageManager.SIGNATURE_MATCH; 4387 } 4388 return PackageManager.SIGNATURE_NO_MATCH; 4389 } 4390 4391 /** 4392 * If the database version for this type of package (internal storage or 4393 * external storage) is less than the version where package signatures 4394 * were updated, return true. 4395 */ 4396 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4397 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4398 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4399 } 4400 4401 /** 4402 * Used for backward compatibility to make sure any packages with 4403 * certificate chains get upgraded to the new style. {@code existingSigs} 4404 * will be in the old format (since they were stored on disk from before the 4405 * system upgrade) and {@code scannedSigs} will be in the newer format. 4406 */ 4407 private int compareSignaturesCompat(PackageSignatures existingSigs, 4408 PackageParser.Package scannedPkg) { 4409 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4410 return PackageManager.SIGNATURE_NO_MATCH; 4411 } 4412 4413 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4414 for (Signature sig : existingSigs.mSignatures) { 4415 existingSet.add(sig); 4416 } 4417 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4418 for (Signature sig : scannedPkg.mSignatures) { 4419 try { 4420 Signature[] chainSignatures = sig.getChainSignatures(); 4421 for (Signature chainSig : chainSignatures) { 4422 scannedCompatSet.add(chainSig); 4423 } 4424 } catch (CertificateEncodingException e) { 4425 scannedCompatSet.add(sig); 4426 } 4427 } 4428 /* 4429 * Make sure the expanded scanned set contains all signatures in the 4430 * existing one. 4431 */ 4432 if (scannedCompatSet.equals(existingSet)) { 4433 // Migrate the old signatures to the new scheme. 4434 existingSigs.assignSignatures(scannedPkg.mSignatures); 4435 // The new KeySets will be re-added later in the scanning process. 4436 synchronized (mPackages) { 4437 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4438 } 4439 return PackageManager.SIGNATURE_MATCH; 4440 } 4441 return PackageManager.SIGNATURE_NO_MATCH; 4442 } 4443 4444 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4445 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4446 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4447 } 4448 4449 private int compareSignaturesRecover(PackageSignatures existingSigs, 4450 PackageParser.Package scannedPkg) { 4451 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4452 return PackageManager.SIGNATURE_NO_MATCH; 4453 } 4454 4455 String msg = null; 4456 try { 4457 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4458 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4459 + scannedPkg.packageName); 4460 return PackageManager.SIGNATURE_MATCH; 4461 } 4462 } catch (CertificateException e) { 4463 msg = e.getMessage(); 4464 } 4465 4466 logCriticalInfo(Log.INFO, 4467 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4468 return PackageManager.SIGNATURE_NO_MATCH; 4469 } 4470 4471 @Override 4472 public List<String> getAllPackages() { 4473 synchronized (mPackages) { 4474 return new ArrayList<String>(mPackages.keySet()); 4475 } 4476 } 4477 4478 @Override 4479 public String[] getPackagesForUid(int uid) { 4480 uid = UserHandle.getAppId(uid); 4481 // reader 4482 synchronized (mPackages) { 4483 Object obj = mSettings.getUserIdLPr(uid); 4484 if (obj instanceof SharedUserSetting) { 4485 final SharedUserSetting sus = (SharedUserSetting) obj; 4486 final int N = sus.packages.size(); 4487 final String[] res = new String[N]; 4488 final Iterator<PackageSetting> it = sus.packages.iterator(); 4489 int i = 0; 4490 while (it.hasNext()) { 4491 res[i++] = it.next().name; 4492 } 4493 return res; 4494 } else if (obj instanceof PackageSetting) { 4495 final PackageSetting ps = (PackageSetting) obj; 4496 return new String[] { ps.name }; 4497 } 4498 } 4499 return null; 4500 } 4501 4502 @Override 4503 public String getNameForUid(int uid) { 4504 // reader 4505 synchronized (mPackages) { 4506 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4507 if (obj instanceof SharedUserSetting) { 4508 final SharedUserSetting sus = (SharedUserSetting) obj; 4509 return sus.name + ":" + sus.userId; 4510 } else if (obj instanceof PackageSetting) { 4511 final PackageSetting ps = (PackageSetting) obj; 4512 return ps.name; 4513 } 4514 } 4515 return null; 4516 } 4517 4518 @Override 4519 public int getUidForSharedUser(String sharedUserName) { 4520 if(sharedUserName == null) { 4521 return -1; 4522 } 4523 // reader 4524 synchronized (mPackages) { 4525 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4526 if (suid == null) { 4527 return -1; 4528 } 4529 return suid.userId; 4530 } 4531 } 4532 4533 @Override 4534 public int getFlagsForUid(int uid) { 4535 synchronized (mPackages) { 4536 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4537 if (obj instanceof SharedUserSetting) { 4538 final SharedUserSetting sus = (SharedUserSetting) obj; 4539 return sus.pkgFlags; 4540 } else if (obj instanceof PackageSetting) { 4541 final PackageSetting ps = (PackageSetting) obj; 4542 return ps.pkgFlags; 4543 } 4544 } 4545 return 0; 4546 } 4547 4548 @Override 4549 public int getPrivateFlagsForUid(int uid) { 4550 synchronized (mPackages) { 4551 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4552 if (obj instanceof SharedUserSetting) { 4553 final SharedUserSetting sus = (SharedUserSetting) obj; 4554 return sus.pkgPrivateFlags; 4555 } else if (obj instanceof PackageSetting) { 4556 final PackageSetting ps = (PackageSetting) obj; 4557 return ps.pkgPrivateFlags; 4558 } 4559 } 4560 return 0; 4561 } 4562 4563 @Override 4564 public boolean isUidPrivileged(int uid) { 4565 uid = UserHandle.getAppId(uid); 4566 // reader 4567 synchronized (mPackages) { 4568 Object obj = mSettings.getUserIdLPr(uid); 4569 if (obj instanceof SharedUserSetting) { 4570 final SharedUserSetting sus = (SharedUserSetting) obj; 4571 final Iterator<PackageSetting> it = sus.packages.iterator(); 4572 while (it.hasNext()) { 4573 if (it.next().isPrivileged()) { 4574 return true; 4575 } 4576 } 4577 } else if (obj instanceof PackageSetting) { 4578 final PackageSetting ps = (PackageSetting) obj; 4579 return ps.isPrivileged(); 4580 } 4581 } 4582 return false; 4583 } 4584 4585 @Override 4586 public String[] getAppOpPermissionPackages(String permissionName) { 4587 synchronized (mPackages) { 4588 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4589 if (pkgs == null) { 4590 return null; 4591 } 4592 return pkgs.toArray(new String[pkgs.size()]); 4593 } 4594 } 4595 4596 @Override 4597 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4598 int flags, int userId) { 4599 if (!sUserManager.exists(userId)) return null; 4600 flags = updateFlagsForResolve(flags, userId, intent); 4601 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4602 false /* requireFullPermission */, false /* checkShell */, "resolve intent"); 4603 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4604 userId); 4605 final ResolveInfo bestChoice = 4606 chooseBestActivity(intent, resolvedType, flags, query, userId); 4607 4608 if (isEphemeralAllowed(intent, query, userId)) { 4609 final EphemeralResolveInfo ai = 4610 getEphemeralResolveInfo(intent, resolvedType, userId); 4611 if (ai != null) { 4612 if (DEBUG_EPHEMERAL) { 4613 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4614 } 4615 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4616 bestChoice.ephemeralResolveInfo = ai; 4617 } 4618 } 4619 return bestChoice; 4620 } 4621 4622 @Override 4623 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4624 IntentFilter filter, int match, ComponentName activity) { 4625 final int userId = UserHandle.getCallingUserId(); 4626 if (DEBUG_PREFERRED) { 4627 Log.v(TAG, "setLastChosenActivity intent=" + intent 4628 + " resolvedType=" + resolvedType 4629 + " flags=" + flags 4630 + " filter=" + filter 4631 + " match=" + match 4632 + " activity=" + activity); 4633 filter.dump(new PrintStreamPrinter(System.out), " "); 4634 } 4635 intent.setComponent(null); 4636 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4637 userId); 4638 // Find any earlier preferred or last chosen entries and nuke them 4639 findPreferredActivity(intent, resolvedType, 4640 flags, query, 0, false, true, false, userId); 4641 // Add the new activity as the last chosen for this filter 4642 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4643 "Setting last chosen"); 4644 } 4645 4646 @Override 4647 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4648 final int userId = UserHandle.getCallingUserId(); 4649 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4650 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4651 userId); 4652 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4653 false, false, false, userId); 4654 } 4655 4656 4657 private boolean isEphemeralAllowed( 4658 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4659 // Short circuit and return early if possible. 4660 if (DISABLE_EPHEMERAL_APPS) { 4661 return false; 4662 } 4663 final int callingUser = UserHandle.getCallingUserId(); 4664 if (callingUser != UserHandle.USER_SYSTEM) { 4665 return false; 4666 } 4667 if (mEphemeralResolverConnection == null) { 4668 return false; 4669 } 4670 if (intent.getComponent() != null) { 4671 return false; 4672 } 4673 if (intent.getPackage() != null) { 4674 return false; 4675 } 4676 final boolean isWebUri = hasWebURI(intent); 4677 if (!isWebUri) { 4678 return false; 4679 } 4680 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4681 synchronized (mPackages) { 4682 final int count = resolvedActivites.size(); 4683 for (int n = 0; n < count; n++) { 4684 ResolveInfo info = resolvedActivites.get(n); 4685 String packageName = info.activityInfo.packageName; 4686 PackageSetting ps = mSettings.mPackages.get(packageName); 4687 if (ps != null) { 4688 // Try to get the status from User settings first 4689 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4690 int status = (int) (packedStatus >> 32); 4691 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4692 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4693 if (DEBUG_EPHEMERAL) { 4694 Slog.v(TAG, "DENY ephemeral apps;" 4695 + " pkg: " + packageName + ", status: " + status); 4696 } 4697 return false; 4698 } 4699 } 4700 } 4701 } 4702 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4703 return true; 4704 } 4705 4706 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4707 int userId) { 4708 MessageDigest digest = null; 4709 try { 4710 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4711 } catch (NoSuchAlgorithmException e) { 4712 // If we can't create a digest, ignore ephemeral apps. 4713 return null; 4714 } 4715 4716 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4717 final byte[] digestBytes = digest.digest(hostBytes); 4718 int shaPrefix = 4719 digestBytes[0] << 24 4720 | digestBytes[1] << 16 4721 | digestBytes[2] << 8 4722 | digestBytes[3] << 0; 4723 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4724 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4725 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4726 // No hash prefix match; there are no ephemeral apps for this domain. 4727 return null; 4728 } 4729 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4730 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4731 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4732 continue; 4733 } 4734 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4735 // No filters; this should never happen. 4736 if (filters.isEmpty()) { 4737 continue; 4738 } 4739 // We have a domain match; resolve the filters to see if anything matches. 4740 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4741 for (int j = filters.size() - 1; j >= 0; --j) { 4742 final EphemeralResolveIntentInfo intentInfo = 4743 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4744 ephemeralResolver.addFilter(intentInfo); 4745 } 4746 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4747 intent, resolvedType, false /*defaultOnly*/, userId); 4748 if (!matchedResolveInfoList.isEmpty()) { 4749 return matchedResolveInfoList.get(0); 4750 } 4751 } 4752 // Hash or filter mis-match; no ephemeral apps for this domain. 4753 return null; 4754 } 4755 4756 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4757 int flags, List<ResolveInfo> query, int userId) { 4758 if (query != null) { 4759 final int N = query.size(); 4760 if (N == 1) { 4761 return query.get(0); 4762 } else if (N > 1) { 4763 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4764 // If there is more than one activity with the same priority, 4765 // then let the user decide between them. 4766 ResolveInfo r0 = query.get(0); 4767 ResolveInfo r1 = query.get(1); 4768 if (DEBUG_INTENT_MATCHING || debug) { 4769 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4770 + r1.activityInfo.name + "=" + r1.priority); 4771 } 4772 // If the first activity has a higher priority, or a different 4773 // default, then it is always desirable to pick it. 4774 if (r0.priority != r1.priority 4775 || r0.preferredOrder != r1.preferredOrder 4776 || r0.isDefault != r1.isDefault) { 4777 return query.get(0); 4778 } 4779 // If we have saved a preference for a preferred activity for 4780 // this Intent, use that. 4781 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4782 flags, query, r0.priority, true, false, debug, userId); 4783 if (ri != null) { 4784 return ri; 4785 } 4786 ri = new ResolveInfo(mResolveInfo); 4787 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4788 ri.activityInfo.applicationInfo = new ApplicationInfo( 4789 ri.activityInfo.applicationInfo); 4790 if (userId != 0) { 4791 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4792 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4793 } 4794 // Make sure that the resolver is displayable in car mode 4795 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4796 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4797 return ri; 4798 } 4799 } 4800 return null; 4801 } 4802 4803 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4804 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4805 final int N = query.size(); 4806 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4807 .get(userId); 4808 // Get the list of persistent preferred activities that handle the intent 4809 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4810 List<PersistentPreferredActivity> pprefs = ppir != null 4811 ? ppir.queryIntent(intent, resolvedType, 4812 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4813 : null; 4814 if (pprefs != null && pprefs.size() > 0) { 4815 final int M = pprefs.size(); 4816 for (int i=0; i<M; i++) { 4817 final PersistentPreferredActivity ppa = pprefs.get(i); 4818 if (DEBUG_PREFERRED || debug) { 4819 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4820 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4821 + "\n component=" + ppa.mComponent); 4822 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4823 } 4824 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4825 flags | MATCH_DISABLED_COMPONENTS, userId); 4826 if (DEBUG_PREFERRED || debug) { 4827 Slog.v(TAG, "Found persistent preferred activity:"); 4828 if (ai != null) { 4829 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4830 } else { 4831 Slog.v(TAG, " null"); 4832 } 4833 } 4834 if (ai == null) { 4835 // This previously registered persistent preferred activity 4836 // component is no longer known. Ignore it and do NOT remove it. 4837 continue; 4838 } 4839 for (int j=0; j<N; j++) { 4840 final ResolveInfo ri = query.get(j); 4841 if (!ri.activityInfo.applicationInfo.packageName 4842 .equals(ai.applicationInfo.packageName)) { 4843 continue; 4844 } 4845 if (!ri.activityInfo.name.equals(ai.name)) { 4846 continue; 4847 } 4848 // Found a persistent preference that can handle the intent. 4849 if (DEBUG_PREFERRED || debug) { 4850 Slog.v(TAG, "Returning persistent preferred activity: " + 4851 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4852 } 4853 return ri; 4854 } 4855 } 4856 } 4857 return null; 4858 } 4859 4860 // TODO: handle preferred activities missing while user has amnesia 4861 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4862 List<ResolveInfo> query, int priority, boolean always, 4863 boolean removeMatches, boolean debug, int userId) { 4864 if (!sUserManager.exists(userId)) return null; 4865 flags = updateFlagsForResolve(flags, userId, intent); 4866 // writer 4867 synchronized (mPackages) { 4868 if (intent.getSelector() != null) { 4869 intent = intent.getSelector(); 4870 } 4871 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4872 4873 // Try to find a matching persistent preferred activity. 4874 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4875 debug, userId); 4876 4877 // If a persistent preferred activity matched, use it. 4878 if (pri != null) { 4879 return pri; 4880 } 4881 4882 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4883 // Get the list of preferred activities that handle the intent 4884 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4885 List<PreferredActivity> prefs = pir != null 4886 ? pir.queryIntent(intent, resolvedType, 4887 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4888 : null; 4889 if (prefs != null && prefs.size() > 0) { 4890 boolean changed = false; 4891 try { 4892 // First figure out how good the original match set is. 4893 // We will only allow preferred activities that came 4894 // from the same match quality. 4895 int match = 0; 4896 4897 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4898 4899 final int N = query.size(); 4900 for (int j=0; j<N; j++) { 4901 final ResolveInfo ri = query.get(j); 4902 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4903 + ": 0x" + Integer.toHexString(match)); 4904 if (ri.match > match) { 4905 match = ri.match; 4906 } 4907 } 4908 4909 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4910 + Integer.toHexString(match)); 4911 4912 match &= IntentFilter.MATCH_CATEGORY_MASK; 4913 final int M = prefs.size(); 4914 for (int i=0; i<M; i++) { 4915 final PreferredActivity pa = prefs.get(i); 4916 if (DEBUG_PREFERRED || debug) { 4917 Slog.v(TAG, "Checking PreferredActivity ds=" 4918 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4919 + "\n component=" + pa.mPref.mComponent); 4920 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4921 } 4922 if (pa.mPref.mMatch != match) { 4923 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4924 + Integer.toHexString(pa.mPref.mMatch)); 4925 continue; 4926 } 4927 // If it's not an "always" type preferred activity and that's what we're 4928 // looking for, skip it. 4929 if (always && !pa.mPref.mAlways) { 4930 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4931 continue; 4932 } 4933 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4934 flags | MATCH_DISABLED_COMPONENTS, userId); 4935 if (DEBUG_PREFERRED || debug) { 4936 Slog.v(TAG, "Found preferred activity:"); 4937 if (ai != null) { 4938 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4939 } else { 4940 Slog.v(TAG, " null"); 4941 } 4942 } 4943 if (ai == null) { 4944 // This previously registered preferred activity 4945 // component is no longer known. Most likely an update 4946 // to the app was installed and in the new version this 4947 // component no longer exists. Clean it up by removing 4948 // it from the preferred activities list, and skip it. 4949 Slog.w(TAG, "Removing dangling preferred activity: " 4950 + pa.mPref.mComponent); 4951 pir.removeFilter(pa); 4952 changed = true; 4953 continue; 4954 } 4955 for (int j=0; j<N; j++) { 4956 final ResolveInfo ri = query.get(j); 4957 if (!ri.activityInfo.applicationInfo.packageName 4958 .equals(ai.applicationInfo.packageName)) { 4959 continue; 4960 } 4961 if (!ri.activityInfo.name.equals(ai.name)) { 4962 continue; 4963 } 4964 4965 if (removeMatches) { 4966 pir.removeFilter(pa); 4967 changed = true; 4968 if (DEBUG_PREFERRED) { 4969 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4970 } 4971 break; 4972 } 4973 4974 // Okay we found a previously set preferred or last chosen app. 4975 // If the result set is different from when this 4976 // was created, we need to clear it and re-ask the 4977 // user their preference, if we're looking for an "always" type entry. 4978 if (always && !pa.mPref.sameSet(query)) { 4979 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4980 + intent + " type " + resolvedType); 4981 if (DEBUG_PREFERRED) { 4982 Slog.v(TAG, "Removing preferred activity since set changed " 4983 + pa.mPref.mComponent); 4984 } 4985 pir.removeFilter(pa); 4986 // Re-add the filter as a "last chosen" entry (!always) 4987 PreferredActivity lastChosen = new PreferredActivity( 4988 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4989 pir.addFilter(lastChosen); 4990 changed = true; 4991 return null; 4992 } 4993 4994 // Yay! Either the set matched or we're looking for the last chosen 4995 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4996 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4997 return ri; 4998 } 4999 } 5000 } finally { 5001 if (changed) { 5002 if (DEBUG_PREFERRED) { 5003 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5004 } 5005 scheduleWritePackageRestrictionsLocked(userId); 5006 } 5007 } 5008 } 5009 } 5010 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5011 return null; 5012 } 5013 5014 /* 5015 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5016 */ 5017 @Override 5018 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5019 int targetUserId) { 5020 mContext.enforceCallingOrSelfPermission( 5021 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5022 List<CrossProfileIntentFilter> matches = 5023 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5024 if (matches != null) { 5025 int size = matches.size(); 5026 for (int i = 0; i < size; i++) { 5027 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5028 } 5029 } 5030 if (hasWebURI(intent)) { 5031 // cross-profile app linking works only towards the parent. 5032 final UserInfo parent = getProfileParent(sourceUserId); 5033 synchronized(mPackages) { 5034 int flags = updateFlagsForResolve(0, parent.id, intent); 5035 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5036 intent, resolvedType, flags, sourceUserId, parent.id); 5037 return xpDomainInfo != null; 5038 } 5039 } 5040 return false; 5041 } 5042 5043 private UserInfo getProfileParent(int userId) { 5044 final long identity = Binder.clearCallingIdentity(); 5045 try { 5046 return sUserManager.getProfileParent(userId); 5047 } finally { 5048 Binder.restoreCallingIdentity(identity); 5049 } 5050 } 5051 5052 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5053 String resolvedType, int userId) { 5054 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5055 if (resolver != null) { 5056 return resolver.queryIntent(intent, resolvedType, false, userId); 5057 } 5058 return null; 5059 } 5060 5061 @Override 5062 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5063 String resolvedType, int flags, int userId) { 5064 return new ParceledListSlice<>( 5065 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5066 } 5067 5068 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5069 String resolvedType, int flags, int userId) { 5070 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5071 flags = updateFlagsForResolve(flags, userId, intent); 5072 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5073 false /* requireFullPermission */, false /* checkShell */, 5074 "query intent activities"); 5075 ComponentName comp = intent.getComponent(); 5076 if (comp == null) { 5077 if (intent.getSelector() != null) { 5078 intent = intent.getSelector(); 5079 comp = intent.getComponent(); 5080 } 5081 } 5082 5083 if (comp != null) { 5084 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5085 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5086 if (ai != null) { 5087 final ResolveInfo ri = new ResolveInfo(); 5088 ri.activityInfo = ai; 5089 list.add(ri); 5090 } 5091 return list; 5092 } 5093 5094 // reader 5095 synchronized (mPackages) { 5096 final String pkgName = intent.getPackage(); 5097 if (pkgName == null) { 5098 List<CrossProfileIntentFilter> matchingFilters = 5099 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5100 // Check for results that need to skip the current profile. 5101 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5102 resolvedType, flags, userId); 5103 if (xpResolveInfo != null) { 5104 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5105 result.add(xpResolveInfo); 5106 return filterIfNotSystemUser(result, userId); 5107 } 5108 5109 // Check for results in the current profile. 5110 List<ResolveInfo> result = mActivities.queryIntent( 5111 intent, resolvedType, flags, userId); 5112 result = filterIfNotSystemUser(result, userId); 5113 5114 // Check for cross profile results. 5115 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5116 xpResolveInfo = queryCrossProfileIntents( 5117 matchingFilters, intent, resolvedType, flags, userId, 5118 hasNonNegativePriorityResult); 5119 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5120 boolean isVisibleToUser = filterIfNotSystemUser( 5121 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5122 if (isVisibleToUser) { 5123 result.add(xpResolveInfo); 5124 Collections.sort(result, mResolvePrioritySorter); 5125 } 5126 } 5127 if (hasWebURI(intent)) { 5128 CrossProfileDomainInfo xpDomainInfo = null; 5129 final UserInfo parent = getProfileParent(userId); 5130 if (parent != null) { 5131 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5132 flags, userId, parent.id); 5133 } 5134 if (xpDomainInfo != null) { 5135 if (xpResolveInfo != null) { 5136 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5137 // in the result. 5138 result.remove(xpResolveInfo); 5139 } 5140 if (result.size() == 0) { 5141 result.add(xpDomainInfo.resolveInfo); 5142 return result; 5143 } 5144 } else if (result.size() <= 1) { 5145 return result; 5146 } 5147 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5148 xpDomainInfo, userId); 5149 Collections.sort(result, mResolvePrioritySorter); 5150 } 5151 return result; 5152 } 5153 final PackageParser.Package pkg = mPackages.get(pkgName); 5154 if (pkg != null) { 5155 return filterIfNotSystemUser( 5156 mActivities.queryIntentForPackage( 5157 intent, resolvedType, flags, pkg.activities, userId), 5158 userId); 5159 } 5160 return new ArrayList<ResolveInfo>(); 5161 } 5162 } 5163 5164 private static class CrossProfileDomainInfo { 5165 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5166 ResolveInfo resolveInfo; 5167 /* Best domain verification status of the activities found in the other profile */ 5168 int bestDomainVerificationStatus; 5169 } 5170 5171 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5172 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5173 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5174 sourceUserId)) { 5175 return null; 5176 } 5177 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5178 resolvedType, flags, parentUserId); 5179 5180 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5181 return null; 5182 } 5183 CrossProfileDomainInfo result = null; 5184 int size = resultTargetUser.size(); 5185 for (int i = 0; i < size; i++) { 5186 ResolveInfo riTargetUser = resultTargetUser.get(i); 5187 // Intent filter verification is only for filters that specify a host. So don't return 5188 // those that handle all web uris. 5189 if (riTargetUser.handleAllWebDataURI) { 5190 continue; 5191 } 5192 String packageName = riTargetUser.activityInfo.packageName; 5193 PackageSetting ps = mSettings.mPackages.get(packageName); 5194 if (ps == null) { 5195 continue; 5196 } 5197 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5198 int status = (int)(verificationState >> 32); 5199 if (result == null) { 5200 result = new CrossProfileDomainInfo(); 5201 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5202 sourceUserId, parentUserId); 5203 result.bestDomainVerificationStatus = status; 5204 } else { 5205 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5206 result.bestDomainVerificationStatus); 5207 } 5208 } 5209 // Don't consider matches with status NEVER across profiles. 5210 if (result != null && result.bestDomainVerificationStatus 5211 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5212 return null; 5213 } 5214 return result; 5215 } 5216 5217 /** 5218 * Verification statuses are ordered from the worse to the best, except for 5219 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5220 */ 5221 private int bestDomainVerificationStatus(int status1, int status2) { 5222 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5223 return status2; 5224 } 5225 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5226 return status1; 5227 } 5228 return (int) MathUtils.max(status1, status2); 5229 } 5230 5231 private boolean isUserEnabled(int userId) { 5232 long callingId = Binder.clearCallingIdentity(); 5233 try { 5234 UserInfo userInfo = sUserManager.getUserInfo(userId); 5235 return userInfo != null && userInfo.isEnabled(); 5236 } finally { 5237 Binder.restoreCallingIdentity(callingId); 5238 } 5239 } 5240 5241 /** 5242 * Filter out activities with systemUserOnly flag set, when current user is not System. 5243 * 5244 * @return filtered list 5245 */ 5246 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5247 if (userId == UserHandle.USER_SYSTEM) { 5248 return resolveInfos; 5249 } 5250 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5251 ResolveInfo info = resolveInfos.get(i); 5252 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5253 resolveInfos.remove(i); 5254 } 5255 } 5256 return resolveInfos; 5257 } 5258 5259 /** 5260 * @param resolveInfos list of resolve infos in descending priority order 5261 * @return if the list contains a resolve info with non-negative priority 5262 */ 5263 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5264 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5265 } 5266 5267 private static boolean hasWebURI(Intent intent) { 5268 if (intent.getData() == null) { 5269 return false; 5270 } 5271 final String scheme = intent.getScheme(); 5272 if (TextUtils.isEmpty(scheme)) { 5273 return false; 5274 } 5275 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5276 } 5277 5278 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5279 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5280 int userId) { 5281 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5282 5283 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5284 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5285 candidates.size()); 5286 } 5287 5288 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5289 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5290 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5291 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5292 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5293 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5294 5295 synchronized (mPackages) { 5296 final int count = candidates.size(); 5297 // First, try to use linked apps. Partition the candidates into four lists: 5298 // one for the final results, one for the "do not use ever", one for "undefined status" 5299 // and finally one for "browser app type". 5300 for (int n=0; n<count; n++) { 5301 ResolveInfo info = candidates.get(n); 5302 String packageName = info.activityInfo.packageName; 5303 PackageSetting ps = mSettings.mPackages.get(packageName); 5304 if (ps != null) { 5305 // Add to the special match all list (Browser use case) 5306 if (info.handleAllWebDataURI) { 5307 matchAllList.add(info); 5308 continue; 5309 } 5310 // Try to get the status from User settings first 5311 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5312 int status = (int)(packedStatus >> 32); 5313 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5314 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5315 if (DEBUG_DOMAIN_VERIFICATION) { 5316 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5317 + " : linkgen=" + linkGeneration); 5318 } 5319 // Use link-enabled generation as preferredOrder, i.e. 5320 // prefer newly-enabled over earlier-enabled. 5321 info.preferredOrder = linkGeneration; 5322 alwaysList.add(info); 5323 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5324 if (DEBUG_DOMAIN_VERIFICATION) { 5325 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5326 } 5327 neverList.add(info); 5328 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5329 if (DEBUG_DOMAIN_VERIFICATION) { 5330 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5331 } 5332 alwaysAskList.add(info); 5333 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5334 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5335 if (DEBUG_DOMAIN_VERIFICATION) { 5336 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5337 } 5338 undefinedList.add(info); 5339 } 5340 } 5341 } 5342 5343 // We'll want to include browser possibilities in a few cases 5344 boolean includeBrowser = false; 5345 5346 // First try to add the "always" resolution(s) for the current user, if any 5347 if (alwaysList.size() > 0) { 5348 result.addAll(alwaysList); 5349 } else { 5350 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5351 result.addAll(undefinedList); 5352 // Maybe add one for the other profile. 5353 if (xpDomainInfo != null && ( 5354 xpDomainInfo.bestDomainVerificationStatus 5355 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5356 result.add(xpDomainInfo.resolveInfo); 5357 } 5358 includeBrowser = true; 5359 } 5360 5361 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5362 // If there were 'always' entries their preferred order has been set, so we also 5363 // back that off to make the alternatives equivalent 5364 if (alwaysAskList.size() > 0) { 5365 for (ResolveInfo i : result) { 5366 i.preferredOrder = 0; 5367 } 5368 result.addAll(alwaysAskList); 5369 includeBrowser = true; 5370 } 5371 5372 if (includeBrowser) { 5373 // Also add browsers (all of them or only the default one) 5374 if (DEBUG_DOMAIN_VERIFICATION) { 5375 Slog.v(TAG, " ...including browsers in candidate set"); 5376 } 5377 if ((matchFlags & MATCH_ALL) != 0) { 5378 result.addAll(matchAllList); 5379 } else { 5380 // Browser/generic handling case. If there's a default browser, go straight 5381 // to that (but only if there is no other higher-priority match). 5382 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5383 int maxMatchPrio = 0; 5384 ResolveInfo defaultBrowserMatch = null; 5385 final int numCandidates = matchAllList.size(); 5386 for (int n = 0; n < numCandidates; n++) { 5387 ResolveInfo info = matchAllList.get(n); 5388 // track the highest overall match priority... 5389 if (info.priority > maxMatchPrio) { 5390 maxMatchPrio = info.priority; 5391 } 5392 // ...and the highest-priority default browser match 5393 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5394 if (defaultBrowserMatch == null 5395 || (defaultBrowserMatch.priority < info.priority)) { 5396 if (debug) { 5397 Slog.v(TAG, "Considering default browser match " + info); 5398 } 5399 defaultBrowserMatch = info; 5400 } 5401 } 5402 } 5403 if (defaultBrowserMatch != null 5404 && defaultBrowserMatch.priority >= maxMatchPrio 5405 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5406 { 5407 if (debug) { 5408 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5409 } 5410 result.add(defaultBrowserMatch); 5411 } else { 5412 result.addAll(matchAllList); 5413 } 5414 } 5415 5416 // If there is nothing selected, add all candidates and remove the ones that the user 5417 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5418 if (result.size() == 0) { 5419 result.addAll(candidates); 5420 result.removeAll(neverList); 5421 } 5422 } 5423 } 5424 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5425 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5426 result.size()); 5427 for (ResolveInfo info : result) { 5428 Slog.v(TAG, " + " + info.activityInfo); 5429 } 5430 } 5431 return result; 5432 } 5433 5434 // Returns a packed value as a long: 5435 // 5436 // high 'int'-sized word: link status: undefined/ask/never/always. 5437 // low 'int'-sized word: relative priority among 'always' results. 5438 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5439 long result = ps.getDomainVerificationStatusForUser(userId); 5440 // if none available, get the master status 5441 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5442 if (ps.getIntentFilterVerificationInfo() != null) { 5443 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5444 } 5445 } 5446 return result; 5447 } 5448 5449 private ResolveInfo querySkipCurrentProfileIntents( 5450 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5451 int flags, int sourceUserId) { 5452 if (matchingFilters != null) { 5453 int size = matchingFilters.size(); 5454 for (int i = 0; i < size; i ++) { 5455 CrossProfileIntentFilter filter = matchingFilters.get(i); 5456 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5457 // Checking if there are activities in the target user that can handle the 5458 // intent. 5459 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5460 resolvedType, flags, sourceUserId); 5461 if (resolveInfo != null) { 5462 return resolveInfo; 5463 } 5464 } 5465 } 5466 } 5467 return null; 5468 } 5469 5470 // Return matching ResolveInfo in target user if any. 5471 private ResolveInfo queryCrossProfileIntents( 5472 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5473 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5474 if (matchingFilters != null) { 5475 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5476 // match the same intent. For performance reasons, it is better not to 5477 // run queryIntent twice for the same userId 5478 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5479 int size = matchingFilters.size(); 5480 for (int i = 0; i < size; i++) { 5481 CrossProfileIntentFilter filter = matchingFilters.get(i); 5482 int targetUserId = filter.getTargetUserId(); 5483 boolean skipCurrentProfile = 5484 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5485 boolean skipCurrentProfileIfNoMatchFound = 5486 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5487 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5488 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5489 // Checking if there are activities in the target user that can handle the 5490 // intent. 5491 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5492 resolvedType, flags, sourceUserId); 5493 if (resolveInfo != null) return resolveInfo; 5494 alreadyTriedUserIds.put(targetUserId, true); 5495 } 5496 } 5497 } 5498 return null; 5499 } 5500 5501 /** 5502 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5503 * will forward the intent to the filter's target user. 5504 * Otherwise, returns null. 5505 */ 5506 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5507 String resolvedType, int flags, int sourceUserId) { 5508 int targetUserId = filter.getTargetUserId(); 5509 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5510 resolvedType, flags, targetUserId); 5511 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5512 // If all the matches in the target profile are suspended, return null. 5513 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5514 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5515 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5516 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5517 targetUserId); 5518 } 5519 } 5520 } 5521 return null; 5522 } 5523 5524 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5525 int sourceUserId, int targetUserId) { 5526 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5527 long ident = Binder.clearCallingIdentity(); 5528 boolean targetIsProfile; 5529 try { 5530 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5531 } finally { 5532 Binder.restoreCallingIdentity(ident); 5533 } 5534 String className; 5535 if (targetIsProfile) { 5536 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5537 } else { 5538 className = FORWARD_INTENT_TO_PARENT; 5539 } 5540 ComponentName forwardingActivityComponentName = new ComponentName( 5541 mAndroidApplication.packageName, className); 5542 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5543 sourceUserId); 5544 if (!targetIsProfile) { 5545 forwardingActivityInfo.showUserIcon = targetUserId; 5546 forwardingResolveInfo.noResourceId = true; 5547 } 5548 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5549 forwardingResolveInfo.priority = 0; 5550 forwardingResolveInfo.preferredOrder = 0; 5551 forwardingResolveInfo.match = 0; 5552 forwardingResolveInfo.isDefault = true; 5553 forwardingResolveInfo.filter = filter; 5554 forwardingResolveInfo.targetUserId = targetUserId; 5555 return forwardingResolveInfo; 5556 } 5557 5558 @Override 5559 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5560 Intent[] specifics, String[] specificTypes, Intent intent, 5561 String resolvedType, int flags, int userId) { 5562 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5563 specificTypes, intent, resolvedType, flags, userId)); 5564 } 5565 5566 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5567 Intent[] specifics, String[] specificTypes, Intent intent, 5568 String resolvedType, int flags, int userId) { 5569 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5570 flags = updateFlagsForResolve(flags, userId, intent); 5571 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5572 false /* requireFullPermission */, false /* checkShell */, 5573 "query intent activity options"); 5574 final String resultsAction = intent.getAction(); 5575 5576 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5577 | PackageManager.GET_RESOLVED_FILTER, userId); 5578 5579 if (DEBUG_INTENT_MATCHING) { 5580 Log.v(TAG, "Query " + intent + ": " + results); 5581 } 5582 5583 int specificsPos = 0; 5584 int N; 5585 5586 // todo: note that the algorithm used here is O(N^2). This 5587 // isn't a problem in our current environment, but if we start running 5588 // into situations where we have more than 5 or 10 matches then this 5589 // should probably be changed to something smarter... 5590 5591 // First we go through and resolve each of the specific items 5592 // that were supplied, taking care of removing any corresponding 5593 // duplicate items in the generic resolve list. 5594 if (specifics != null) { 5595 for (int i=0; i<specifics.length; i++) { 5596 final Intent sintent = specifics[i]; 5597 if (sintent == null) { 5598 continue; 5599 } 5600 5601 if (DEBUG_INTENT_MATCHING) { 5602 Log.v(TAG, "Specific #" + i + ": " + sintent); 5603 } 5604 5605 String action = sintent.getAction(); 5606 if (resultsAction != null && resultsAction.equals(action)) { 5607 // If this action was explicitly requested, then don't 5608 // remove things that have it. 5609 action = null; 5610 } 5611 5612 ResolveInfo ri = null; 5613 ActivityInfo ai = null; 5614 5615 ComponentName comp = sintent.getComponent(); 5616 if (comp == null) { 5617 ri = resolveIntent( 5618 sintent, 5619 specificTypes != null ? specificTypes[i] : null, 5620 flags, userId); 5621 if (ri == null) { 5622 continue; 5623 } 5624 if (ri == mResolveInfo) { 5625 // ACK! Must do something better with this. 5626 } 5627 ai = ri.activityInfo; 5628 comp = new ComponentName(ai.applicationInfo.packageName, 5629 ai.name); 5630 } else { 5631 ai = getActivityInfo(comp, flags, userId); 5632 if (ai == null) { 5633 continue; 5634 } 5635 } 5636 5637 // Look for any generic query activities that are duplicates 5638 // of this specific one, and remove them from the results. 5639 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5640 N = results.size(); 5641 int j; 5642 for (j=specificsPos; j<N; j++) { 5643 ResolveInfo sri = results.get(j); 5644 if ((sri.activityInfo.name.equals(comp.getClassName()) 5645 && sri.activityInfo.applicationInfo.packageName.equals( 5646 comp.getPackageName())) 5647 || (action != null && sri.filter.matchAction(action))) { 5648 results.remove(j); 5649 if (DEBUG_INTENT_MATCHING) Log.v( 5650 TAG, "Removing duplicate item from " + j 5651 + " due to specific " + specificsPos); 5652 if (ri == null) { 5653 ri = sri; 5654 } 5655 j--; 5656 N--; 5657 } 5658 } 5659 5660 // Add this specific item to its proper place. 5661 if (ri == null) { 5662 ri = new ResolveInfo(); 5663 ri.activityInfo = ai; 5664 } 5665 results.add(specificsPos, ri); 5666 ri.specificIndex = i; 5667 specificsPos++; 5668 } 5669 } 5670 5671 // Now we go through the remaining generic results and remove any 5672 // duplicate actions that are found here. 5673 N = results.size(); 5674 for (int i=specificsPos; i<N-1; i++) { 5675 final ResolveInfo rii = results.get(i); 5676 if (rii.filter == null) { 5677 continue; 5678 } 5679 5680 // Iterate over all of the actions of this result's intent 5681 // filter... typically this should be just one. 5682 final Iterator<String> it = rii.filter.actionsIterator(); 5683 if (it == null) { 5684 continue; 5685 } 5686 while (it.hasNext()) { 5687 final String action = it.next(); 5688 if (resultsAction != null && resultsAction.equals(action)) { 5689 // If this action was explicitly requested, then don't 5690 // remove things that have it. 5691 continue; 5692 } 5693 for (int j=i+1; j<N; j++) { 5694 final ResolveInfo rij = results.get(j); 5695 if (rij.filter != null && rij.filter.hasAction(action)) { 5696 results.remove(j); 5697 if (DEBUG_INTENT_MATCHING) Log.v( 5698 TAG, "Removing duplicate item from " + j 5699 + " due to action " + action + " at " + i); 5700 j--; 5701 N--; 5702 } 5703 } 5704 } 5705 5706 // If the caller didn't request filter information, drop it now 5707 // so we don't have to marshall/unmarshall it. 5708 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5709 rii.filter = null; 5710 } 5711 } 5712 5713 // Filter out the caller activity if so requested. 5714 if (caller != null) { 5715 N = results.size(); 5716 for (int i=0; i<N; i++) { 5717 ActivityInfo ainfo = results.get(i).activityInfo; 5718 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5719 && caller.getClassName().equals(ainfo.name)) { 5720 results.remove(i); 5721 break; 5722 } 5723 } 5724 } 5725 5726 // If the caller didn't request filter information, 5727 // drop them now so we don't have to 5728 // marshall/unmarshall it. 5729 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5730 N = results.size(); 5731 for (int i=0; i<N; i++) { 5732 results.get(i).filter = null; 5733 } 5734 } 5735 5736 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5737 return results; 5738 } 5739 5740 @Override 5741 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 5742 String resolvedType, int flags, int userId) { 5743 return new ParceledListSlice<>( 5744 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 5745 } 5746 5747 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 5748 String resolvedType, int flags, int userId) { 5749 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5750 flags = updateFlagsForResolve(flags, userId, intent); 5751 ComponentName comp = intent.getComponent(); 5752 if (comp == null) { 5753 if (intent.getSelector() != null) { 5754 intent = intent.getSelector(); 5755 comp = intent.getComponent(); 5756 } 5757 } 5758 if (comp != null) { 5759 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5760 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5761 if (ai != null) { 5762 ResolveInfo ri = new ResolveInfo(); 5763 ri.activityInfo = ai; 5764 list.add(ri); 5765 } 5766 return list; 5767 } 5768 5769 // reader 5770 synchronized (mPackages) { 5771 String pkgName = intent.getPackage(); 5772 if (pkgName == null) { 5773 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5774 } 5775 final PackageParser.Package pkg = mPackages.get(pkgName); 5776 if (pkg != null) { 5777 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5778 userId); 5779 } 5780 return Collections.emptyList(); 5781 } 5782 } 5783 5784 @Override 5785 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5786 if (!sUserManager.exists(userId)) return null; 5787 flags = updateFlagsForResolve(flags, userId, intent); 5788 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 5789 if (query != null) { 5790 if (query.size() >= 1) { 5791 // If there is more than one service with the same priority, 5792 // just arbitrarily pick the first one. 5793 return query.get(0); 5794 } 5795 } 5796 return null; 5797 } 5798 5799 @Override 5800 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 5801 String resolvedType, int flags, int userId) { 5802 return new ParceledListSlice<>( 5803 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 5804 } 5805 5806 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 5807 String resolvedType, int flags, int userId) { 5808 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5809 flags = updateFlagsForResolve(flags, userId, intent); 5810 ComponentName comp = intent.getComponent(); 5811 if (comp == null) { 5812 if (intent.getSelector() != null) { 5813 intent = intent.getSelector(); 5814 comp = intent.getComponent(); 5815 } 5816 } 5817 if (comp != null) { 5818 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5819 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5820 if (si != null) { 5821 final ResolveInfo ri = new ResolveInfo(); 5822 ri.serviceInfo = si; 5823 list.add(ri); 5824 } 5825 return list; 5826 } 5827 5828 // reader 5829 synchronized (mPackages) { 5830 String pkgName = intent.getPackage(); 5831 if (pkgName == null) { 5832 return mServices.queryIntent(intent, resolvedType, flags, userId); 5833 } 5834 final PackageParser.Package pkg = mPackages.get(pkgName); 5835 if (pkg != null) { 5836 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5837 userId); 5838 } 5839 return Collections.emptyList(); 5840 } 5841 } 5842 5843 @Override 5844 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 5845 String resolvedType, int flags, int userId) { 5846 return new ParceledListSlice<>( 5847 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 5848 } 5849 5850 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 5851 Intent intent, String resolvedType, int flags, int userId) { 5852 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5853 flags = updateFlagsForResolve(flags, userId, intent); 5854 ComponentName comp = intent.getComponent(); 5855 if (comp == null) { 5856 if (intent.getSelector() != null) { 5857 intent = intent.getSelector(); 5858 comp = intent.getComponent(); 5859 } 5860 } 5861 if (comp != null) { 5862 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5863 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5864 if (pi != null) { 5865 final ResolveInfo ri = new ResolveInfo(); 5866 ri.providerInfo = pi; 5867 list.add(ri); 5868 } 5869 return list; 5870 } 5871 5872 // reader 5873 synchronized (mPackages) { 5874 String pkgName = intent.getPackage(); 5875 if (pkgName == null) { 5876 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5877 } 5878 final PackageParser.Package pkg = mPackages.get(pkgName); 5879 if (pkg != null) { 5880 return mProviders.queryIntentForPackage( 5881 intent, resolvedType, flags, pkg.providers, userId); 5882 } 5883 return Collections.emptyList(); 5884 } 5885 } 5886 5887 @Override 5888 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5889 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5890 flags = updateFlagsForPackage(flags, userId, null); 5891 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5892 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5893 true /* requireFullPermission */, false /* checkShell */, 5894 "get installed packages"); 5895 5896 // writer 5897 synchronized (mPackages) { 5898 ArrayList<PackageInfo> list; 5899 if (listUninstalled) { 5900 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5901 for (PackageSetting ps : mSettings.mPackages.values()) { 5902 PackageInfo pi; 5903 if (ps.pkg != null) { 5904 pi = generatePackageInfo(ps.pkg, flags, userId); 5905 } else { 5906 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5907 } 5908 if (pi != null) { 5909 list.add(pi); 5910 } 5911 } 5912 } else { 5913 list = new ArrayList<PackageInfo>(mPackages.size()); 5914 for (PackageParser.Package p : mPackages.values()) { 5915 PackageInfo pi = generatePackageInfo(p, flags, userId); 5916 if (pi != null) { 5917 list.add(pi); 5918 } 5919 } 5920 } 5921 5922 return new ParceledListSlice<PackageInfo>(list); 5923 } 5924 } 5925 5926 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5927 String[] permissions, boolean[] tmp, int flags, int userId) { 5928 int numMatch = 0; 5929 final PermissionsState permissionsState = ps.getPermissionsState(); 5930 for (int i=0; i<permissions.length; i++) { 5931 final String permission = permissions[i]; 5932 if (permissionsState.hasPermission(permission, userId)) { 5933 tmp[i] = true; 5934 numMatch++; 5935 } else { 5936 tmp[i] = false; 5937 } 5938 } 5939 if (numMatch == 0) { 5940 return; 5941 } 5942 PackageInfo pi; 5943 if (ps.pkg != null) { 5944 pi = generatePackageInfo(ps.pkg, flags, userId); 5945 } else { 5946 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5947 } 5948 // The above might return null in cases of uninstalled apps or install-state 5949 // skew across users/profiles. 5950 if (pi != null) { 5951 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5952 if (numMatch == permissions.length) { 5953 pi.requestedPermissions = permissions; 5954 } else { 5955 pi.requestedPermissions = new String[numMatch]; 5956 numMatch = 0; 5957 for (int i=0; i<permissions.length; i++) { 5958 if (tmp[i]) { 5959 pi.requestedPermissions[numMatch] = permissions[i]; 5960 numMatch++; 5961 } 5962 } 5963 } 5964 } 5965 list.add(pi); 5966 } 5967 } 5968 5969 @Override 5970 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5971 String[] permissions, int flags, int userId) { 5972 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5973 flags = updateFlagsForPackage(flags, userId, permissions); 5974 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5975 5976 // writer 5977 synchronized (mPackages) { 5978 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5979 boolean[] tmpBools = new boolean[permissions.length]; 5980 if (listUninstalled) { 5981 for (PackageSetting ps : mSettings.mPackages.values()) { 5982 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5983 } 5984 } else { 5985 for (PackageParser.Package pkg : mPackages.values()) { 5986 PackageSetting ps = (PackageSetting)pkg.mExtras; 5987 if (ps != null) { 5988 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5989 userId); 5990 } 5991 } 5992 } 5993 5994 return new ParceledListSlice<PackageInfo>(list); 5995 } 5996 } 5997 5998 @Override 5999 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6000 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6001 flags = updateFlagsForApplication(flags, userId, null); 6002 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6003 6004 // writer 6005 synchronized (mPackages) { 6006 ArrayList<ApplicationInfo> list; 6007 if (listUninstalled) { 6008 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6009 for (PackageSetting ps : mSettings.mPackages.values()) { 6010 ApplicationInfo ai; 6011 if (ps.pkg != null) { 6012 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6013 ps.readUserState(userId), userId); 6014 } else { 6015 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6016 } 6017 if (ai != null) { 6018 list.add(ai); 6019 } 6020 } 6021 } else { 6022 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6023 for (PackageParser.Package p : mPackages.values()) { 6024 if (p.mExtras != null) { 6025 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6026 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6027 if (ai != null) { 6028 list.add(ai); 6029 } 6030 } 6031 } 6032 } 6033 6034 return new ParceledListSlice<ApplicationInfo>(list); 6035 } 6036 } 6037 6038 @Override 6039 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6040 if (DISABLE_EPHEMERAL_APPS) { 6041 return null; 6042 } 6043 6044 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6045 "getEphemeralApplications"); 6046 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6047 true /* requireFullPermission */, false /* checkShell */, 6048 "getEphemeralApplications"); 6049 synchronized (mPackages) { 6050 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6051 .getEphemeralApplicationsLPw(userId); 6052 if (ephemeralApps != null) { 6053 return new ParceledListSlice<>(ephemeralApps); 6054 } 6055 } 6056 return null; 6057 } 6058 6059 @Override 6060 public boolean isEphemeralApplication(String packageName, int userId) { 6061 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6062 true /* requireFullPermission */, false /* checkShell */, 6063 "isEphemeral"); 6064 if (DISABLE_EPHEMERAL_APPS) { 6065 return false; 6066 } 6067 6068 if (!isCallerSameApp(packageName)) { 6069 return false; 6070 } 6071 synchronized (mPackages) { 6072 PackageParser.Package pkg = mPackages.get(packageName); 6073 if (pkg != null) { 6074 return pkg.applicationInfo.isEphemeralApp(); 6075 } 6076 } 6077 return false; 6078 } 6079 6080 @Override 6081 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6082 if (DISABLE_EPHEMERAL_APPS) { 6083 return null; 6084 } 6085 6086 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6087 true /* requireFullPermission */, false /* checkShell */, 6088 "getCookie"); 6089 if (!isCallerSameApp(packageName)) { 6090 return null; 6091 } 6092 synchronized (mPackages) { 6093 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6094 packageName, userId); 6095 } 6096 } 6097 6098 @Override 6099 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6100 if (DISABLE_EPHEMERAL_APPS) { 6101 return true; 6102 } 6103 6104 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6105 true /* requireFullPermission */, true /* checkShell */, 6106 "setCookie"); 6107 if (!isCallerSameApp(packageName)) { 6108 return false; 6109 } 6110 synchronized (mPackages) { 6111 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6112 packageName, cookie, userId); 6113 } 6114 } 6115 6116 @Override 6117 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6118 if (DISABLE_EPHEMERAL_APPS) { 6119 return null; 6120 } 6121 6122 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6123 "getEphemeralApplicationIcon"); 6124 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6125 true /* requireFullPermission */, false /* checkShell */, 6126 "getEphemeralApplicationIcon"); 6127 synchronized (mPackages) { 6128 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6129 packageName, userId); 6130 } 6131 } 6132 6133 private boolean isCallerSameApp(String packageName) { 6134 PackageParser.Package pkg = mPackages.get(packageName); 6135 return pkg != null 6136 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6137 } 6138 6139 @Override 6140 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6141 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6142 } 6143 6144 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6145 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6146 6147 // reader 6148 synchronized (mPackages) { 6149 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6150 final int userId = UserHandle.getCallingUserId(); 6151 while (i.hasNext()) { 6152 final PackageParser.Package p = i.next(); 6153 if (p.applicationInfo == null) continue; 6154 6155 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6156 && !p.applicationInfo.isDirectBootAware(); 6157 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6158 && p.applicationInfo.isDirectBootAware(); 6159 6160 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6161 && (!mSafeMode || isSystemApp(p)) 6162 && (matchesUnaware || matchesAware)) { 6163 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6164 if (ps != null) { 6165 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6166 ps.readUserState(userId), userId); 6167 if (ai != null) { 6168 finalList.add(ai); 6169 } 6170 } 6171 } 6172 } 6173 } 6174 6175 return finalList; 6176 } 6177 6178 @Override 6179 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6180 if (!sUserManager.exists(userId)) return null; 6181 flags = updateFlagsForComponent(flags, userId, name); 6182 // reader 6183 synchronized (mPackages) { 6184 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6185 PackageSetting ps = provider != null 6186 ? mSettings.mPackages.get(provider.owner.packageName) 6187 : null; 6188 return ps != null 6189 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6190 ? PackageParser.generateProviderInfo(provider, flags, 6191 ps.readUserState(userId), userId) 6192 : null; 6193 } 6194 } 6195 6196 /** 6197 * @deprecated 6198 */ 6199 @Deprecated 6200 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6201 // reader 6202 synchronized (mPackages) { 6203 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6204 .entrySet().iterator(); 6205 final int userId = UserHandle.getCallingUserId(); 6206 while (i.hasNext()) { 6207 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6208 PackageParser.Provider p = entry.getValue(); 6209 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6210 6211 if (ps != null && p.syncable 6212 && (!mSafeMode || (p.info.applicationInfo.flags 6213 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6214 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6215 ps.readUserState(userId), userId); 6216 if (info != null) { 6217 outNames.add(entry.getKey()); 6218 outInfo.add(info); 6219 } 6220 } 6221 } 6222 } 6223 } 6224 6225 @Override 6226 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6227 int uid, int flags) { 6228 final int userId = processName != null ? UserHandle.getUserId(uid) 6229 : UserHandle.getCallingUserId(); 6230 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6231 flags = updateFlagsForComponent(flags, userId, processName); 6232 6233 ArrayList<ProviderInfo> finalList = null; 6234 // reader 6235 synchronized (mPackages) { 6236 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6237 while (i.hasNext()) { 6238 final PackageParser.Provider p = i.next(); 6239 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6240 if (ps != null && p.info.authority != null 6241 && (processName == null 6242 || (p.info.processName.equals(processName) 6243 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6244 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6245 if (finalList == null) { 6246 finalList = new ArrayList<ProviderInfo>(3); 6247 } 6248 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6249 ps.readUserState(userId), userId); 6250 if (info != null) { 6251 finalList.add(info); 6252 } 6253 } 6254 } 6255 } 6256 6257 if (finalList != null) { 6258 Collections.sort(finalList, mProviderInitOrderSorter); 6259 return new ParceledListSlice<ProviderInfo>(finalList); 6260 } 6261 6262 return ParceledListSlice.emptyList(); 6263 } 6264 6265 @Override 6266 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6267 // reader 6268 synchronized (mPackages) { 6269 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6270 return PackageParser.generateInstrumentationInfo(i, flags); 6271 } 6272 } 6273 6274 @Override 6275 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6276 String targetPackage, int flags) { 6277 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6278 } 6279 6280 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6281 int flags) { 6282 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6283 6284 // reader 6285 synchronized (mPackages) { 6286 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6287 while (i.hasNext()) { 6288 final PackageParser.Instrumentation p = i.next(); 6289 if (targetPackage == null 6290 || targetPackage.equals(p.info.targetPackage)) { 6291 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6292 flags); 6293 if (ii != null) { 6294 finalList.add(ii); 6295 } 6296 } 6297 } 6298 } 6299 6300 return finalList; 6301 } 6302 6303 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6304 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6305 if (overlays == null) { 6306 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6307 return; 6308 } 6309 for (PackageParser.Package opkg : overlays.values()) { 6310 // Not much to do if idmap fails: we already logged the error 6311 // and we certainly don't want to abort installation of pkg simply 6312 // because an overlay didn't fit properly. For these reasons, 6313 // ignore the return value of createIdmapForPackagePairLI. 6314 createIdmapForPackagePairLI(pkg, opkg); 6315 } 6316 } 6317 6318 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6319 PackageParser.Package opkg) { 6320 if (!opkg.mTrustedOverlay) { 6321 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6322 opkg.baseCodePath + ": overlay not trusted"); 6323 return false; 6324 } 6325 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6326 if (overlaySet == null) { 6327 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6328 opkg.baseCodePath + " but target package has no known overlays"); 6329 return false; 6330 } 6331 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6332 // TODO: generate idmap for split APKs 6333 try { 6334 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6335 } catch (InstallerException e) { 6336 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6337 + opkg.baseCodePath); 6338 return false; 6339 } 6340 PackageParser.Package[] overlayArray = 6341 overlaySet.values().toArray(new PackageParser.Package[0]); 6342 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6343 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6344 return p1.mOverlayPriority - p2.mOverlayPriority; 6345 } 6346 }; 6347 Arrays.sort(overlayArray, cmp); 6348 6349 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6350 int i = 0; 6351 for (PackageParser.Package p : overlayArray) { 6352 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6353 } 6354 return true; 6355 } 6356 6357 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6358 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6359 try { 6360 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6361 } finally { 6362 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6363 } 6364 } 6365 6366 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6367 final File[] files = dir.listFiles(); 6368 if (ArrayUtils.isEmpty(files)) { 6369 Log.d(TAG, "No files in app dir " + dir); 6370 return; 6371 } 6372 6373 if (DEBUG_PACKAGE_SCANNING) { 6374 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6375 + " flags=0x" + Integer.toHexString(parseFlags)); 6376 } 6377 6378 for (File file : files) { 6379 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6380 && !PackageInstallerService.isStageName(file.getName()); 6381 if (!isPackage) { 6382 // Ignore entries which are not packages 6383 continue; 6384 } 6385 try { 6386 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6387 scanFlags, currentTime, null); 6388 } catch (PackageManagerException e) { 6389 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6390 6391 // Delete invalid userdata apps 6392 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6393 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6394 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6395 removeCodePathLI(file); 6396 } 6397 } 6398 } 6399 } 6400 6401 private static File getSettingsProblemFile() { 6402 File dataDir = Environment.getDataDirectory(); 6403 File systemDir = new File(dataDir, "system"); 6404 File fname = new File(systemDir, "uiderrors.txt"); 6405 return fname; 6406 } 6407 6408 static void reportSettingsProblem(int priority, String msg) { 6409 logCriticalInfo(priority, msg); 6410 } 6411 6412 static void logCriticalInfo(int priority, String msg) { 6413 Slog.println(priority, TAG, msg); 6414 EventLogTags.writePmCriticalInfo(msg); 6415 try { 6416 File fname = getSettingsProblemFile(); 6417 FileOutputStream out = new FileOutputStream(fname, true); 6418 PrintWriter pw = new FastPrintWriter(out); 6419 SimpleDateFormat formatter = new SimpleDateFormat(); 6420 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6421 pw.println(dateString + ": " + msg); 6422 pw.close(); 6423 FileUtils.setPermissions( 6424 fname.toString(), 6425 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6426 -1, -1); 6427 } catch (java.io.IOException e) { 6428 } 6429 } 6430 6431 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6432 int parseFlags) throws PackageManagerException { 6433 if (ps != null 6434 && ps.codePath.equals(srcFile) 6435 && ps.timeStamp == srcFile.lastModified() 6436 && !isCompatSignatureUpdateNeeded(pkg) 6437 && !isRecoverSignatureUpdateNeeded(pkg)) { 6438 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6439 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6440 ArraySet<PublicKey> signingKs; 6441 synchronized (mPackages) { 6442 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6443 } 6444 if (ps.signatures.mSignatures != null 6445 && ps.signatures.mSignatures.length != 0 6446 && signingKs != null) { 6447 // Optimization: reuse the existing cached certificates 6448 // if the package appears to be unchanged. 6449 pkg.mSignatures = ps.signatures.mSignatures; 6450 pkg.mSigningKeys = signingKs; 6451 return; 6452 } 6453 6454 Slog.w(TAG, "PackageSetting for " + ps.name 6455 + " is missing signatures. Collecting certs again to recover them."); 6456 } else { 6457 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6458 } 6459 6460 try { 6461 PackageParser.collectCertificates(pkg, parseFlags); 6462 } catch (PackageParserException e) { 6463 throw PackageManagerException.from(e); 6464 } 6465 } 6466 6467 /** 6468 * Traces a package scan. 6469 * @see #scanPackageLI(File, int, int, long, UserHandle) 6470 */ 6471 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6472 long currentTime, UserHandle user) throws PackageManagerException { 6473 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6474 try { 6475 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6476 } finally { 6477 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6478 } 6479 } 6480 6481 /** 6482 * Scans a package and returns the newly parsed package. 6483 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6484 */ 6485 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6486 long currentTime, UserHandle user) throws PackageManagerException { 6487 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6488 parseFlags |= mDefParseFlags; 6489 PackageParser pp = new PackageParser(); 6490 pp.setSeparateProcesses(mSeparateProcesses); 6491 pp.setOnlyCoreApps(mOnlyCore); 6492 pp.setDisplayMetrics(mMetrics); 6493 6494 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6495 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6496 } 6497 6498 final PackageParser.Package pkg; 6499 try { 6500 pkg = pp.parsePackage(scanFile, parseFlags); 6501 } catch (PackageParserException e) { 6502 throw PackageManagerException.from(e); 6503 } 6504 6505 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6506 } 6507 6508 /** 6509 * Scans a package and returns the newly parsed package. 6510 * @throws PackageManagerException on a parse error. 6511 */ 6512 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6513 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6514 throws PackageManagerException { 6515 // If the package has children and this is the first dive in the function 6516 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6517 // packages (parent and children) would be successfully scanned before the 6518 // actual scan since scanning mutates internal state and we want to atomically 6519 // install the package and its children. 6520 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6521 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6522 scanFlags |= SCAN_CHECK_ONLY; 6523 } 6524 } else { 6525 scanFlags &= ~SCAN_CHECK_ONLY; 6526 } 6527 6528 // Scan the parent 6529 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags, 6530 scanFlags, currentTime, user); 6531 6532 // Scan the children 6533 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6534 for (int i = 0; i < childCount; i++) { 6535 PackageParser.Package childPackage = pkg.childPackages.get(i); 6536 scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags, 6537 currentTime, user); 6538 } 6539 6540 6541 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6542 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6543 } 6544 6545 return scannedPkg; 6546 } 6547 6548 /** 6549 * Scans a package and returns the newly parsed package. 6550 * @throws PackageManagerException on a parse error. 6551 */ 6552 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6553 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6554 throws PackageManagerException { 6555 PackageSetting ps = null; 6556 PackageSetting updatedPkg; 6557 // reader 6558 synchronized (mPackages) { 6559 // Look to see if we already know about this package. 6560 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6561 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6562 // This package has been renamed to its original name. Let's 6563 // use that. 6564 ps = mSettings.peekPackageLPr(oldName); 6565 } 6566 // If there was no original package, see one for the real package name. 6567 if (ps == null) { 6568 ps = mSettings.peekPackageLPr(pkg.packageName); 6569 } 6570 // Check to see if this package could be hiding/updating a system 6571 // package. Must look for it either under the original or real 6572 // package name depending on our state. 6573 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6574 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6575 6576 // If this is a package we don't know about on the system partition, we 6577 // may need to remove disabled child packages on the system partition 6578 // or may need to not add child packages if the parent apk is updated 6579 // on the data partition and no longer defines this child package. 6580 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6581 // If this is a parent package for an updated system app and this system 6582 // app got an OTA update which no longer defines some of the child packages 6583 // we have to prune them from the disabled system packages. 6584 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6585 if (disabledPs != null) { 6586 final int scannedChildCount = (pkg.childPackages != null) 6587 ? pkg.childPackages.size() : 0; 6588 final int disabledChildCount = disabledPs.childPackageNames != null 6589 ? disabledPs.childPackageNames.size() : 0; 6590 for (int i = 0; i < disabledChildCount; i++) { 6591 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6592 boolean disabledPackageAvailable = false; 6593 for (int j = 0; j < scannedChildCount; j++) { 6594 PackageParser.Package childPkg = pkg.childPackages.get(j); 6595 if (childPkg.packageName.equals(disabledChildPackageName)) { 6596 disabledPackageAvailable = true; 6597 break; 6598 } 6599 } 6600 if (!disabledPackageAvailable) { 6601 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6602 } 6603 } 6604 } 6605 } 6606 } 6607 6608 boolean updatedPkgBetter = false; 6609 // First check if this is a system package that may involve an update 6610 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6611 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6612 // it needs to drop FLAG_PRIVILEGED. 6613 if (locationIsPrivileged(scanFile)) { 6614 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6615 } else { 6616 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6617 } 6618 6619 if (ps != null && !ps.codePath.equals(scanFile)) { 6620 // The path has changed from what was last scanned... check the 6621 // version of the new path against what we have stored to determine 6622 // what to do. 6623 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6624 if (pkg.mVersionCode <= ps.versionCode) { 6625 // The system package has been updated and the code path does not match 6626 // Ignore entry. Skip it. 6627 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6628 + " ignored: updated version " + ps.versionCode 6629 + " better than this " + pkg.mVersionCode); 6630 if (!updatedPkg.codePath.equals(scanFile)) { 6631 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6632 + ps.name + " changing from " + updatedPkg.codePathString 6633 + " to " + scanFile); 6634 updatedPkg.codePath = scanFile; 6635 updatedPkg.codePathString = scanFile.toString(); 6636 updatedPkg.resourcePath = scanFile; 6637 updatedPkg.resourcePathString = scanFile.toString(); 6638 } 6639 updatedPkg.pkg = pkg; 6640 updatedPkg.versionCode = pkg.mVersionCode; 6641 6642 // Update the disabled system child packages to point to the package too. 6643 final int childCount = updatedPkg.childPackageNames != null 6644 ? updatedPkg.childPackageNames.size() : 0; 6645 for (int i = 0; i < childCount; i++) { 6646 String childPackageName = updatedPkg.childPackageNames.get(i); 6647 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6648 childPackageName); 6649 if (updatedChildPkg != null) { 6650 updatedChildPkg.pkg = pkg; 6651 updatedChildPkg.versionCode = pkg.mVersionCode; 6652 } 6653 } 6654 6655 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6656 + scanFile + " ignored: updated version " + ps.versionCode 6657 + " better than this " + pkg.mVersionCode); 6658 } else { 6659 // The current app on the system partition is better than 6660 // what we have updated to on the data partition; switch 6661 // back to the system partition version. 6662 // At this point, its safely assumed that package installation for 6663 // apps in system partition will go through. If not there won't be a working 6664 // version of the app 6665 // writer 6666 synchronized (mPackages) { 6667 // Just remove the loaded entries from package lists. 6668 mPackages.remove(ps.name); 6669 } 6670 6671 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6672 + " reverting from " + ps.codePathString 6673 + ": new version " + pkg.mVersionCode 6674 + " better than installed " + ps.versionCode); 6675 6676 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6677 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6678 synchronized (mInstallLock) { 6679 args.cleanUpResourcesLI(); 6680 } 6681 synchronized (mPackages) { 6682 mSettings.enableSystemPackageLPw(ps.name); 6683 } 6684 updatedPkgBetter = true; 6685 } 6686 } 6687 } 6688 6689 if (updatedPkg != null) { 6690 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6691 // initially 6692 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6693 6694 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6695 // flag set initially 6696 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6697 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6698 } 6699 } 6700 6701 // Verify certificates against what was last scanned 6702 collectCertificatesLI(ps, pkg, scanFile, parseFlags); 6703 6704 /* 6705 * A new system app appeared, but we already had a non-system one of the 6706 * same name installed earlier. 6707 */ 6708 boolean shouldHideSystemApp = false; 6709 if (updatedPkg == null && ps != null 6710 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6711 /* 6712 * Check to make sure the signatures match first. If they don't, 6713 * wipe the installed application and its data. 6714 */ 6715 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6716 != PackageManager.SIGNATURE_MATCH) { 6717 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6718 + " signatures don't match existing userdata copy; removing"); 6719 deletePackageLI(pkg.packageName, null, true, null, 0, null, false, null); 6720 ps = null; 6721 } else { 6722 /* 6723 * If the newly-added system app is an older version than the 6724 * already installed version, hide it. It will be scanned later 6725 * and re-added like an update. 6726 */ 6727 if (pkg.mVersionCode <= ps.versionCode) { 6728 shouldHideSystemApp = true; 6729 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6730 + " but new version " + pkg.mVersionCode + " better than installed " 6731 + ps.versionCode + "; hiding system"); 6732 } else { 6733 /* 6734 * The newly found system app is a newer version that the 6735 * one previously installed. Simply remove the 6736 * already-installed application and replace it with our own 6737 * while keeping the application data. 6738 */ 6739 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6740 + " reverting from " + ps.codePathString + ": new version " 6741 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6742 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6743 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6744 synchronized (mInstallLock) { 6745 args.cleanUpResourcesLI(); 6746 } 6747 } 6748 } 6749 } 6750 6751 // The apk is forward locked (not public) if its code and resources 6752 // are kept in different files. (except for app in either system or 6753 // vendor path). 6754 // TODO grab this value from PackageSettings 6755 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6756 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6757 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6758 } 6759 } 6760 6761 // TODO: extend to support forward-locked splits 6762 String resourcePath = null; 6763 String baseResourcePath = null; 6764 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6765 if (ps != null && ps.resourcePathString != null) { 6766 resourcePath = ps.resourcePathString; 6767 baseResourcePath = ps.resourcePathString; 6768 } else { 6769 // Should not happen at all. Just log an error. 6770 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6771 } 6772 } else { 6773 resourcePath = pkg.codePath; 6774 baseResourcePath = pkg.baseCodePath; 6775 } 6776 6777 // Set application objects path explicitly. 6778 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 6779 pkg.setApplicationInfoCodePath(pkg.codePath); 6780 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 6781 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 6782 pkg.setApplicationInfoResourcePath(resourcePath); 6783 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 6784 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 6785 6786 // Note that we invoke the following method only if we are about to unpack an application 6787 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6788 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6789 6790 /* 6791 * If the system app should be overridden by a previously installed 6792 * data, hide the system app now and let the /data/app scan pick it up 6793 * again. 6794 */ 6795 if (shouldHideSystemApp) { 6796 synchronized (mPackages) { 6797 mSettings.disableSystemPackageLPw(pkg.packageName, true); 6798 } 6799 } 6800 6801 return scannedPkg; 6802 } 6803 6804 private static String fixProcessName(String defProcessName, 6805 String processName, int uid) { 6806 if (processName == null) { 6807 return defProcessName; 6808 } 6809 return processName; 6810 } 6811 6812 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6813 throws PackageManagerException { 6814 if (pkgSetting.signatures.mSignatures != null) { 6815 // Already existing package. Make sure signatures match 6816 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6817 == PackageManager.SIGNATURE_MATCH; 6818 if (!match) { 6819 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6820 == PackageManager.SIGNATURE_MATCH; 6821 } 6822 if (!match) { 6823 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6824 == PackageManager.SIGNATURE_MATCH; 6825 } 6826 if (!match) { 6827 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6828 + pkg.packageName + " signatures do not match the " 6829 + "previously installed version; ignoring!"); 6830 } 6831 } 6832 6833 // Check for shared user signatures 6834 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6835 // Already existing package. Make sure signatures match 6836 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6837 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6838 if (!match) { 6839 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6840 == PackageManager.SIGNATURE_MATCH; 6841 } 6842 if (!match) { 6843 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6844 == PackageManager.SIGNATURE_MATCH; 6845 } 6846 if (!match) { 6847 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6848 "Package " + pkg.packageName 6849 + " has no signatures that match those in shared user " 6850 + pkgSetting.sharedUser.name + "; ignoring!"); 6851 } 6852 } 6853 } 6854 6855 /** 6856 * Enforces that only the system UID or root's UID can call a method exposed 6857 * via Binder. 6858 * 6859 * @param message used as message if SecurityException is thrown 6860 * @throws SecurityException if the caller is not system or root 6861 */ 6862 private static final void enforceSystemOrRoot(String message) { 6863 final int uid = Binder.getCallingUid(); 6864 if (uid != Process.SYSTEM_UID && uid != 0) { 6865 throw new SecurityException(message); 6866 } 6867 } 6868 6869 @Override 6870 public void performFstrimIfNeeded() { 6871 enforceSystemOrRoot("Only the system can request fstrim"); 6872 6873 // Before everything else, see whether we need to fstrim. 6874 try { 6875 IMountService ms = PackageHelper.getMountService(); 6876 if (ms != null) { 6877 final boolean isUpgrade = isUpgrade(); 6878 boolean doTrim = isUpgrade; 6879 if (doTrim) { 6880 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6881 } else { 6882 final long interval = android.provider.Settings.Global.getLong( 6883 mContext.getContentResolver(), 6884 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6885 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6886 if (interval > 0) { 6887 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6888 if (timeSinceLast > interval) { 6889 doTrim = true; 6890 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6891 + "; running immediately"); 6892 } 6893 } 6894 } 6895 if (doTrim) { 6896 if (!isFirstBoot()) { 6897 try { 6898 ActivityManagerNative.getDefault().showBootMessage( 6899 mContext.getResources().getString( 6900 R.string.android_upgrading_fstrim), true); 6901 } catch (RemoteException e) { 6902 } 6903 } 6904 ms.runMaintenance(); 6905 } 6906 } else { 6907 Slog.e(TAG, "Mount service unavailable!"); 6908 } 6909 } catch (RemoteException e) { 6910 // Can't happen; MountService is local 6911 } 6912 } 6913 6914 @Override 6915 public void extractPackagesIfNeeded() { 6916 enforceSystemOrRoot("Only the system can request package extraction"); 6917 6918 // Extract pacakges only if profile-guided compilation is enabled because 6919 // otherwise BackgroundDexOptService will not dexopt them later. 6920 boolean prunedCache = VMRuntime.didPruneDalvikCache(); 6921 if (!isUpgrade() && !prunedCache) { 6922 return; 6923 } 6924 6925 List<PackageParser.Package> pkgs; 6926 synchronized (mPackages) { 6927 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 6928 } 6929 6930 int curr = 0; 6931 int total = pkgs.size(); 6932 for (PackageParser.Package pkg : pkgs) { 6933 curr++; 6934 6935 if (DEBUG_DEXOPT) { 6936 Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName); 6937 } 6938 6939 if (!isFirstBoot()) { 6940 try { 6941 ActivityManagerNative.getDefault().showBootMessage( 6942 mContext.getResources().getString(R.string.android_upgrading_apk, 6943 curr, total), true); 6944 } catch (RemoteException e) { 6945 } 6946 } 6947 6948 if (PackageDexOptimizer.canOptimizePackage(pkg)) { 6949 // If the cache was pruned, any compiled odex files will likely be out of date 6950 // and would have to be patched (would be SELF_PATCHOAT, which is deprecated). 6951 // Instead, force the extraction in this case. 6952 performDexOpt(pkg.packageName, null /* instructionSet */, 6953 false /* checkProfiles */, REASON_BOOT, prunedCache); 6954 } 6955 } 6956 } 6957 6958 @Override 6959 public void notifyPackageUse(String packageName) { 6960 synchronized (mPackages) { 6961 PackageParser.Package p = mPackages.get(packageName); 6962 if (p == null) { 6963 return; 6964 } 6965 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6966 } 6967 } 6968 6969 // TODO: this is not used nor needed. Delete it. 6970 @Override 6971 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6972 return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */, 6973 getFullCompilerFilter(), false /* force */); 6974 } 6975 6976 @Override 6977 public boolean performDexOpt(String packageName, String instructionSet, 6978 boolean checkProfiles, int compileReason, boolean force) { 6979 return performDexOptTraced(packageName, instructionSet, checkProfiles, 6980 getCompilerFilterForReason(compileReason), force); 6981 } 6982 6983 @Override 6984 public boolean performDexOptMode(String packageName, String instructionSet, 6985 boolean checkProfiles, String targetCompilerFilter, boolean force) { 6986 return performDexOptTraced(packageName, instructionSet, checkProfiles, 6987 targetCompilerFilter, force); 6988 } 6989 6990 private boolean performDexOptTraced(String packageName, String instructionSet, 6991 boolean checkProfiles, String targetCompilerFilter, boolean force) { 6992 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6993 try { 6994 return performDexOptInternal(packageName, instructionSet, checkProfiles, 6995 targetCompilerFilter, force); 6996 } finally { 6997 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6998 } 6999 } 7000 7001 private boolean performDexOptInternal(String packageName, String instructionSet, 7002 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7003 PackageParser.Package p; 7004 final String targetInstructionSet; 7005 synchronized (mPackages) { 7006 p = mPackages.get(packageName); 7007 if (p == null) { 7008 return false; 7009 } 7010 mPackageUsage.write(false); 7011 7012 targetInstructionSet = instructionSet != null ? instructionSet : 7013 getPrimaryInstructionSet(p.applicationInfo); 7014 } 7015 long callingId = Binder.clearCallingIdentity(); 7016 try { 7017 synchronized (mInstallLock) { 7018 final String[] instructionSets = new String[] { targetInstructionSet }; 7019 int result = performDexOptInternalWithDependenciesLI(p, instructionSets, 7020 checkProfiles, targetCompilerFilter, force); 7021 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 7022 } 7023 } finally { 7024 Binder.restoreCallingIdentity(callingId); 7025 } 7026 } 7027 7028 public ArraySet<String> getOptimizablePackages() { 7029 ArraySet<String> pkgs = new ArraySet<String>(); 7030 synchronized (mPackages) { 7031 for (PackageParser.Package p : mPackages.values()) { 7032 if (PackageDexOptimizer.canOptimizePackage(p)) { 7033 pkgs.add(p.packageName); 7034 } 7035 } 7036 } 7037 return pkgs; 7038 } 7039 7040 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7041 String instructionSets[], boolean checkProfiles, String targetCompilerFilter, 7042 boolean force) { 7043 // Select the dex optimizer based on the force parameter. 7044 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7045 // allocate an object here. 7046 PackageDexOptimizer pdo = force 7047 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7048 : mPackageDexOptimizer; 7049 7050 // Optimize all dependencies first. Note: we ignore the return value and march on 7051 // on errors. 7052 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7053 if (!deps.isEmpty()) { 7054 for (PackageParser.Package depPackage : deps) { 7055 // TODO: Analyze and investigate if we (should) profile libraries. 7056 // Currently this will do a full compilation of the library by default. 7057 pdo.performDexOpt(depPackage, instructionSets, false /* checkProfiles */, 7058 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7059 } 7060 } 7061 7062 return pdo.performDexOpt(p, instructionSets, checkProfiles, targetCompilerFilter); 7063 } 7064 7065 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7066 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7067 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7068 Set<String> collectedNames = new HashSet<>(); 7069 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7070 7071 retValue.remove(p); 7072 7073 return retValue; 7074 } else { 7075 return Collections.emptyList(); 7076 } 7077 } 7078 7079 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7080 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7081 if (!collectedNames.contains(p.packageName)) { 7082 collectedNames.add(p.packageName); 7083 collected.add(p); 7084 7085 if (p.usesLibraries != null) { 7086 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7087 } 7088 if (p.usesOptionalLibraries != null) { 7089 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7090 collectedNames); 7091 } 7092 } 7093 } 7094 7095 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7096 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7097 for (String libName : libs) { 7098 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7099 if (libPkg != null) { 7100 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7101 } 7102 } 7103 } 7104 7105 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7106 synchronized (mPackages) { 7107 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7108 if (lib != null && lib.apk != null) { 7109 return mPackages.get(lib.apk); 7110 } 7111 } 7112 return null; 7113 } 7114 7115 public void shutdown() { 7116 mPackageUsage.write(true); 7117 } 7118 7119 @Override 7120 public void forceDexOpt(String packageName) { 7121 enforceSystemOrRoot("forceDexOpt"); 7122 7123 PackageParser.Package pkg; 7124 synchronized (mPackages) { 7125 pkg = mPackages.get(packageName); 7126 if (pkg == null) { 7127 throw new IllegalArgumentException("Unknown package: " + packageName); 7128 } 7129 } 7130 7131 synchronized (mInstallLock) { 7132 final String[] instructionSets = new String[] { 7133 getPrimaryInstructionSet(pkg.applicationInfo) }; 7134 7135 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7136 7137 // Whoever is calling forceDexOpt wants a fully compiled package. 7138 // Don't use profiles since that may cause compilation to be skipped. 7139 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7140 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7141 true /* force */); 7142 7143 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7144 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7145 throw new IllegalStateException("Failed to dexopt: " + res); 7146 } 7147 } 7148 } 7149 7150 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7151 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7152 Slog.w(TAG, "Unable to update from " + oldPkg.name 7153 + " to " + newPkg.packageName 7154 + ": old package not in system partition"); 7155 return false; 7156 } else if (mPackages.get(oldPkg.name) != null) { 7157 Slog.w(TAG, "Unable to update from " + oldPkg.name 7158 + " to " + newPkg.packageName 7159 + ": old package still exists"); 7160 return false; 7161 } 7162 return true; 7163 } 7164 7165 private boolean removeDataDirsLI(String volumeUuid, String packageName) { 7166 // TODO: triage flags as part of 26466827 7167 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7168 7169 boolean res = true; 7170 final int[] users = sUserManager.getUserIds(); 7171 for (int user : users) { 7172 try { 7173 mInstaller.destroyAppData(volumeUuid, packageName, user, flags); 7174 } catch (InstallerException e) { 7175 Slog.w(TAG, "Failed to delete data directory", e); 7176 res = false; 7177 } 7178 } 7179 return res; 7180 } 7181 7182 void removeCodePathLI(File codePath) { 7183 if (codePath.isDirectory()) { 7184 try { 7185 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7186 } catch (InstallerException e) { 7187 Slog.w(TAG, "Failed to remove code path", e); 7188 } 7189 } else { 7190 codePath.delete(); 7191 } 7192 } 7193 7194 void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) { 7195 try { 7196 mInstaller.destroyAppData(volumeUuid, packageName, userId, flags); 7197 } catch (InstallerException e) { 7198 Slog.w(TAG, "Failed to destroy app data", e); 7199 } 7200 } 7201 7202 void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags, 7203 int appId, String seinfo) { 7204 try { 7205 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo); 7206 } catch (InstallerException e) { 7207 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 7208 } 7209 } 7210 7211 private void deleteProfilesLI(String packageName, boolean destroy) { 7212 final PackageParser.Package pkg; 7213 synchronized (mPackages) { 7214 pkg = mPackages.get(packageName); 7215 } 7216 if (pkg == null) { 7217 Slog.w(TAG, "Failed to delete profiles. No package: " + packageName); 7218 return; 7219 } 7220 deleteProfilesLI(pkg, destroy); 7221 } 7222 7223 private void deleteProfilesLI(PackageParser.Package pkg, boolean destroy) { 7224 try { 7225 if (destroy) { 7226 mInstaller.clearAppProfiles(pkg.packageName); 7227 } else { 7228 mInstaller.destroyAppProfiles(pkg.packageName); 7229 } 7230 } catch (InstallerException ex) { 7231 Log.e(TAG, "Could not delete profiles for package " + pkg.packageName); 7232 } 7233 } 7234 7235 private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 7236 final PackageParser.Package pkg; 7237 synchronized (mPackages) { 7238 pkg = mPackages.get(packageName); 7239 } 7240 if (pkg == null) { 7241 Slog.w(TAG, "Failed to delete code cache directory. No package: " + packageName); 7242 return; 7243 } 7244 deleteCodeCacheDirsLI(pkg); 7245 } 7246 7247 private void deleteCodeCacheDirsLI(PackageParser.Package pkg) { 7248 // TODO: triage flags as part of 26466827 7249 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7250 7251 int[] users = sUserManager.getUserIds(); 7252 int res = 0; 7253 for (int user : users) { 7254 // Remove the parent code cache 7255 try { 7256 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, user, 7257 flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7258 } catch (InstallerException e) { 7259 Slog.w(TAG, "Failed to delete code cache directory", e); 7260 } 7261 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7262 for (int i = 0; i < childCount; i++) { 7263 PackageParser.Package childPkg = pkg.childPackages.get(i); 7264 // Remove the child code cache 7265 try { 7266 mInstaller.clearAppData(childPkg.volumeUuid, childPkg.packageName, 7267 user, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7268 } catch (InstallerException e) { 7269 Slog.w(TAG, "Failed to delete code cache directory", e); 7270 } 7271 } 7272 } 7273 } 7274 7275 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7276 long lastUpdateTime) { 7277 // Set parent install/update time 7278 PackageSetting ps = (PackageSetting) pkg.mExtras; 7279 if (ps != null) { 7280 ps.firstInstallTime = firstInstallTime; 7281 ps.lastUpdateTime = lastUpdateTime; 7282 } 7283 // Set children install/update time 7284 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7285 for (int i = 0; i < childCount; i++) { 7286 PackageParser.Package childPkg = pkg.childPackages.get(i); 7287 ps = (PackageSetting) childPkg.mExtras; 7288 if (ps != null) { 7289 ps.firstInstallTime = firstInstallTime; 7290 ps.lastUpdateTime = lastUpdateTime; 7291 } 7292 } 7293 } 7294 7295 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7296 PackageParser.Package changingLib) { 7297 if (file.path != null) { 7298 usesLibraryFiles.add(file.path); 7299 return; 7300 } 7301 PackageParser.Package p = mPackages.get(file.apk); 7302 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7303 // If we are doing this while in the middle of updating a library apk, 7304 // then we need to make sure to use that new apk for determining the 7305 // dependencies here. (We haven't yet finished committing the new apk 7306 // to the package manager state.) 7307 if (p == null || p.packageName.equals(changingLib.packageName)) { 7308 p = changingLib; 7309 } 7310 } 7311 if (p != null) { 7312 usesLibraryFiles.addAll(p.getAllCodePaths()); 7313 } 7314 } 7315 7316 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7317 PackageParser.Package changingLib) throws PackageManagerException { 7318 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7319 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7320 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7321 for (int i=0; i<N; i++) { 7322 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7323 if (file == null) { 7324 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7325 "Package " + pkg.packageName + " requires unavailable shared library " 7326 + pkg.usesLibraries.get(i) + "; failing!"); 7327 } 7328 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7329 } 7330 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7331 for (int i=0; i<N; i++) { 7332 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7333 if (file == null) { 7334 Slog.w(TAG, "Package " + pkg.packageName 7335 + " desires unavailable shared library " 7336 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7337 } else { 7338 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7339 } 7340 } 7341 N = usesLibraryFiles.size(); 7342 if (N > 0) { 7343 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7344 } else { 7345 pkg.usesLibraryFiles = null; 7346 } 7347 } 7348 } 7349 7350 private static boolean hasString(List<String> list, List<String> which) { 7351 if (list == null) { 7352 return false; 7353 } 7354 for (int i=list.size()-1; i>=0; i--) { 7355 for (int j=which.size()-1; j>=0; j--) { 7356 if (which.get(j).equals(list.get(i))) { 7357 return true; 7358 } 7359 } 7360 } 7361 return false; 7362 } 7363 7364 private void updateAllSharedLibrariesLPw() { 7365 for (PackageParser.Package pkg : mPackages.values()) { 7366 try { 7367 updateSharedLibrariesLPw(pkg, null); 7368 } catch (PackageManagerException e) { 7369 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7370 } 7371 } 7372 } 7373 7374 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7375 PackageParser.Package changingPkg) { 7376 ArrayList<PackageParser.Package> res = null; 7377 for (PackageParser.Package pkg : mPackages.values()) { 7378 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7379 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7380 if (res == null) { 7381 res = new ArrayList<PackageParser.Package>(); 7382 } 7383 res.add(pkg); 7384 try { 7385 updateSharedLibrariesLPw(pkg, changingPkg); 7386 } catch (PackageManagerException e) { 7387 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7388 } 7389 } 7390 } 7391 return res; 7392 } 7393 7394 /** 7395 * Derive the value of the {@code cpuAbiOverride} based on the provided 7396 * value and an optional stored value from the package settings. 7397 */ 7398 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7399 String cpuAbiOverride = null; 7400 7401 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7402 cpuAbiOverride = null; 7403 } else if (abiOverride != null) { 7404 cpuAbiOverride = abiOverride; 7405 } else if (settings != null) { 7406 cpuAbiOverride = settings.cpuAbiOverrideString; 7407 } 7408 7409 return cpuAbiOverride; 7410 } 7411 7412 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 7413 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7414 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7415 // If the package has children and this is the first dive in the function 7416 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7417 // whether all packages (parent and children) would be successfully scanned 7418 // before the actual scan since scanning mutates internal state and we want 7419 // to atomically install the package and its children. 7420 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7421 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7422 scanFlags |= SCAN_CHECK_ONLY; 7423 } 7424 } else { 7425 scanFlags &= ~SCAN_CHECK_ONLY; 7426 } 7427 7428 final PackageParser.Package scannedPkg; 7429 try { 7430 // Scan the parent 7431 scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 7432 // Scan the children 7433 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7434 for (int i = 0; i < childCount; i++) { 7435 PackageParser.Package childPkg = pkg.childPackages.get(i); 7436 scanPackageLI(childPkg, parseFlags, 7437 scanFlags, currentTime, user); 7438 } 7439 } finally { 7440 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7441 } 7442 7443 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7444 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 7445 } 7446 7447 return scannedPkg; 7448 } 7449 7450 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 7451 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7452 boolean success = false; 7453 try { 7454 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 7455 currentTime, user); 7456 success = true; 7457 return res; 7458 } finally { 7459 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7460 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 7461 } 7462 } 7463 } 7464 7465 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 7466 int scanFlags, long currentTime, UserHandle user) 7467 throws PackageManagerException { 7468 final File scanFile = new File(pkg.codePath); 7469 if (pkg.applicationInfo.getCodePath() == null || 7470 pkg.applicationInfo.getResourcePath() == null) { 7471 // Bail out. The resource and code paths haven't been set. 7472 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7473 "Code and resource paths haven't been set correctly"); 7474 } 7475 7476 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7477 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7478 } else { 7479 // Only allow system apps to be flagged as core apps. 7480 pkg.coreApp = false; 7481 } 7482 7483 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7484 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7485 } 7486 7487 if (mCustomResolverComponentName != null && 7488 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7489 setUpCustomResolverActivity(pkg); 7490 } 7491 7492 if (pkg.packageName.equals("android")) { 7493 synchronized (mPackages) { 7494 if (mAndroidApplication != null) { 7495 Slog.w(TAG, "*************************************************"); 7496 Slog.w(TAG, "Core android package being redefined. Skipping."); 7497 Slog.w(TAG, " file=" + scanFile); 7498 Slog.w(TAG, "*************************************************"); 7499 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7500 "Core android package being redefined. Skipping."); 7501 } 7502 7503 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7504 // Set up information for our fall-back user intent resolution activity. 7505 mPlatformPackage = pkg; 7506 pkg.mVersionCode = mSdkVersion; 7507 mAndroidApplication = pkg.applicationInfo; 7508 7509 if (!mResolverReplaced) { 7510 mResolveActivity.applicationInfo = mAndroidApplication; 7511 mResolveActivity.name = ResolverActivity.class.getName(); 7512 mResolveActivity.packageName = mAndroidApplication.packageName; 7513 mResolveActivity.processName = "system:ui"; 7514 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7515 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7516 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7517 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7518 mResolveActivity.exported = true; 7519 mResolveActivity.enabled = true; 7520 mResolveInfo.activityInfo = mResolveActivity; 7521 mResolveInfo.priority = 0; 7522 mResolveInfo.preferredOrder = 0; 7523 mResolveInfo.match = 0; 7524 mResolveComponentName = new ComponentName( 7525 mAndroidApplication.packageName, mResolveActivity.name); 7526 } 7527 } 7528 } 7529 } 7530 7531 if (DEBUG_PACKAGE_SCANNING) { 7532 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7533 Log.d(TAG, "Scanning package " + pkg.packageName); 7534 } 7535 7536 synchronized (mPackages) { 7537 if (mPackages.containsKey(pkg.packageName) 7538 || mSharedLibraries.containsKey(pkg.packageName)) { 7539 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7540 "Application package " + pkg.packageName 7541 + " already installed. Skipping duplicate."); 7542 } 7543 7544 // If we're only installing presumed-existing packages, require that the 7545 // scanned APK is both already known and at the path previously established 7546 // for it. Previously unknown packages we pick up normally, but if we have an 7547 // a priori expectation about this package's install presence, enforce it. 7548 // With a singular exception for new system packages. When an OTA contains 7549 // a new system package, we allow the codepath to change from a system location 7550 // to the user-installed location. If we don't allow this change, any newer, 7551 // user-installed version of the application will be ignored. 7552 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7553 if (mExpectingBetter.containsKey(pkg.packageName)) { 7554 logCriticalInfo(Log.WARN, 7555 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7556 } else { 7557 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7558 if (known != null) { 7559 if (DEBUG_PACKAGE_SCANNING) { 7560 Log.d(TAG, "Examining " + pkg.codePath 7561 + " and requiring known paths " + known.codePathString 7562 + " & " + known.resourcePathString); 7563 } 7564 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7565 || !pkg.applicationInfo.getResourcePath().equals( 7566 known.resourcePathString)) { 7567 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7568 "Application package " + pkg.packageName 7569 + " found at " + pkg.applicationInfo.getCodePath() 7570 + " but expected at " + known.codePathString 7571 + "; ignoring."); 7572 } 7573 } 7574 } 7575 } 7576 } 7577 7578 // Initialize package source and resource directories 7579 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7580 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7581 7582 SharedUserSetting suid = null; 7583 PackageSetting pkgSetting = null; 7584 7585 if (!isSystemApp(pkg)) { 7586 // Only system apps can use these features. 7587 pkg.mOriginalPackages = null; 7588 pkg.mRealPackage = null; 7589 pkg.mAdoptPermissions = null; 7590 } 7591 7592 // Getting the package setting may have a side-effect, so if we 7593 // are only checking if scan would succeed, stash a copy of the 7594 // old setting to restore at the end. 7595 PackageSetting nonMutatedPs = null; 7596 7597 // writer 7598 synchronized (mPackages) { 7599 if (pkg.mSharedUserId != null) { 7600 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7601 if (suid == null) { 7602 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7603 "Creating application package " + pkg.packageName 7604 + " for shared user failed"); 7605 } 7606 if (DEBUG_PACKAGE_SCANNING) { 7607 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7608 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7609 + "): packages=" + suid.packages); 7610 } 7611 } 7612 7613 // Check if we are renaming from an original package name. 7614 PackageSetting origPackage = null; 7615 String realName = null; 7616 if (pkg.mOriginalPackages != null) { 7617 // This package may need to be renamed to a previously 7618 // installed name. Let's check on that... 7619 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7620 if (pkg.mOriginalPackages.contains(renamed)) { 7621 // This package had originally been installed as the 7622 // original name, and we have already taken care of 7623 // transitioning to the new one. Just update the new 7624 // one to continue using the old name. 7625 realName = pkg.mRealPackage; 7626 if (!pkg.packageName.equals(renamed)) { 7627 // Callers into this function may have already taken 7628 // care of renaming the package; only do it here if 7629 // it is not already done. 7630 pkg.setPackageName(renamed); 7631 } 7632 7633 } else { 7634 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7635 if ((origPackage = mSettings.peekPackageLPr( 7636 pkg.mOriginalPackages.get(i))) != null) { 7637 // We do have the package already installed under its 7638 // original name... should we use it? 7639 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7640 // New package is not compatible with original. 7641 origPackage = null; 7642 continue; 7643 } else if (origPackage.sharedUser != null) { 7644 // Make sure uid is compatible between packages. 7645 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7646 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7647 + " to " + pkg.packageName + ": old uid " 7648 + origPackage.sharedUser.name 7649 + " differs from " + pkg.mSharedUserId); 7650 origPackage = null; 7651 continue; 7652 } 7653 } else { 7654 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7655 + pkg.packageName + " to old name " + origPackage.name); 7656 } 7657 break; 7658 } 7659 } 7660 } 7661 } 7662 7663 if (mTransferedPackages.contains(pkg.packageName)) { 7664 Slog.w(TAG, "Package " + pkg.packageName 7665 + " was transferred to another, but its .apk remains"); 7666 } 7667 7668 // See comments in nonMutatedPs declaration 7669 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7670 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 7671 if (foundPs != null) { 7672 nonMutatedPs = new PackageSetting(foundPs); 7673 } 7674 } 7675 7676 // Just create the setting, don't add it yet. For already existing packages 7677 // the PkgSetting exists already and doesn't have to be created. 7678 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7679 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7680 pkg.applicationInfo.primaryCpuAbi, 7681 pkg.applicationInfo.secondaryCpuAbi, 7682 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7683 user, false); 7684 if (pkgSetting == null) { 7685 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7686 "Creating application package " + pkg.packageName + " failed"); 7687 } 7688 7689 if (pkgSetting.origPackage != null) { 7690 // If we are first transitioning from an original package, 7691 // fix up the new package's name now. We need to do this after 7692 // looking up the package under its new name, so getPackageLP 7693 // can take care of fiddling things correctly. 7694 pkg.setPackageName(origPackage.name); 7695 7696 // File a report about this. 7697 String msg = "New package " + pkgSetting.realName 7698 + " renamed to replace old package " + pkgSetting.name; 7699 reportSettingsProblem(Log.WARN, msg); 7700 7701 // Make a note of it. 7702 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7703 mTransferedPackages.add(origPackage.name); 7704 } 7705 7706 // No longer need to retain this. 7707 pkgSetting.origPackage = null; 7708 } 7709 7710 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 7711 // Make a note of it. 7712 mTransferedPackages.add(pkg.packageName); 7713 } 7714 7715 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7716 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7717 } 7718 7719 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7720 // Check all shared libraries and map to their actual file path. 7721 // We only do this here for apps not on a system dir, because those 7722 // are the only ones that can fail an install due to this. We 7723 // will take care of the system apps by updating all of their 7724 // library paths after the scan is done. 7725 updateSharedLibrariesLPw(pkg, null); 7726 } 7727 7728 if (mFoundPolicyFile) { 7729 SELinuxMMAC.assignSeinfoValue(pkg); 7730 } 7731 7732 pkg.applicationInfo.uid = pkgSetting.appId; 7733 pkg.mExtras = pkgSetting; 7734 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7735 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7736 // We just determined the app is signed correctly, so bring 7737 // over the latest parsed certs. 7738 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7739 } else { 7740 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7741 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7742 "Package " + pkg.packageName + " upgrade keys do not match the " 7743 + "previously installed version"); 7744 } else { 7745 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7746 String msg = "System package " + pkg.packageName 7747 + " signature changed; retaining data."; 7748 reportSettingsProblem(Log.WARN, msg); 7749 } 7750 } 7751 } else { 7752 try { 7753 verifySignaturesLP(pkgSetting, pkg); 7754 // We just determined the app is signed correctly, so bring 7755 // over the latest parsed certs. 7756 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7757 } catch (PackageManagerException e) { 7758 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7759 throw e; 7760 } 7761 // The signature has changed, but this package is in the system 7762 // image... let's recover! 7763 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7764 // However... if this package is part of a shared user, but it 7765 // doesn't match the signature of the shared user, let's fail. 7766 // What this means is that you can't change the signatures 7767 // associated with an overall shared user, which doesn't seem all 7768 // that unreasonable. 7769 if (pkgSetting.sharedUser != null) { 7770 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7771 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7772 throw new PackageManagerException( 7773 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7774 "Signature mismatch for shared user: " 7775 + pkgSetting.sharedUser); 7776 } 7777 } 7778 // File a report about this. 7779 String msg = "System package " + pkg.packageName 7780 + " signature changed; retaining data."; 7781 reportSettingsProblem(Log.WARN, msg); 7782 } 7783 } 7784 // Verify that this new package doesn't have any content providers 7785 // that conflict with existing packages. Only do this if the 7786 // package isn't already installed, since we don't want to break 7787 // things that are installed. 7788 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7789 final int N = pkg.providers.size(); 7790 int i; 7791 for (i=0; i<N; i++) { 7792 PackageParser.Provider p = pkg.providers.get(i); 7793 if (p.info.authority != null) { 7794 String names[] = p.info.authority.split(";"); 7795 for (int j = 0; j < names.length; j++) { 7796 if (mProvidersByAuthority.containsKey(names[j])) { 7797 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7798 final String otherPackageName = 7799 ((other != null && other.getComponentName() != null) ? 7800 other.getComponentName().getPackageName() : "?"); 7801 throw new PackageManagerException( 7802 INSTALL_FAILED_CONFLICTING_PROVIDER, 7803 "Can't install because provider name " + names[j] 7804 + " (in package " + pkg.applicationInfo.packageName 7805 + ") is already used by " + otherPackageName); 7806 } 7807 } 7808 } 7809 } 7810 } 7811 7812 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 7813 // This package wants to adopt ownership of permissions from 7814 // another package. 7815 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7816 final String origName = pkg.mAdoptPermissions.get(i); 7817 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7818 if (orig != null) { 7819 if (verifyPackageUpdateLPr(orig, pkg)) { 7820 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7821 + pkg.packageName); 7822 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7823 } 7824 } 7825 } 7826 } 7827 } 7828 7829 final String pkgName = pkg.packageName; 7830 7831 final long scanFileTime = scanFile.lastModified(); 7832 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7833 pkg.applicationInfo.processName = fixProcessName( 7834 pkg.applicationInfo.packageName, 7835 pkg.applicationInfo.processName, 7836 pkg.applicationInfo.uid); 7837 7838 if (pkg != mPlatformPackage) { 7839 // Get all of our default paths setup 7840 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7841 } 7842 7843 final String path = scanFile.getPath(); 7844 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7845 7846 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7847 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7848 7849 // Some system apps still use directory structure for native libraries 7850 // in which case we might end up not detecting abi solely based on apk 7851 // structure. Try to detect abi based on directory structure. 7852 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7853 pkg.applicationInfo.primaryCpuAbi == null) { 7854 setBundledAppAbisAndRoots(pkg, pkgSetting); 7855 setNativeLibraryPaths(pkg); 7856 } 7857 7858 } else { 7859 if ((scanFlags & SCAN_MOVE) != 0) { 7860 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7861 // but we already have this packages package info in the PackageSetting. We just 7862 // use that and derive the native library path based on the new codepath. 7863 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7864 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7865 } 7866 7867 // Set native library paths again. For moves, the path will be updated based on the 7868 // ABIs we've determined above. For non-moves, the path will be updated based on the 7869 // ABIs we determined during compilation, but the path will depend on the final 7870 // package path (after the rename away from the stage path). 7871 setNativeLibraryPaths(pkg); 7872 } 7873 7874 // This is a special case for the "system" package, where the ABI is 7875 // dictated by the zygote configuration (and init.rc). We should keep track 7876 // of this ABI so that we can deal with "normal" applications that run under 7877 // the same UID correctly. 7878 if (mPlatformPackage == pkg) { 7879 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7880 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7881 } 7882 7883 // If there's a mismatch between the abi-override in the package setting 7884 // and the abiOverride specified for the install. Warn about this because we 7885 // would've already compiled the app without taking the package setting into 7886 // account. 7887 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7888 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7889 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7890 " for package " + pkg.packageName); 7891 } 7892 } 7893 7894 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7895 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7896 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7897 7898 // Copy the derived override back to the parsed package, so that we can 7899 // update the package settings accordingly. 7900 pkg.cpuAbiOverride = cpuAbiOverride; 7901 7902 if (DEBUG_ABI_SELECTION) { 7903 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7904 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7905 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7906 } 7907 7908 // Push the derived path down into PackageSettings so we know what to 7909 // clean up at uninstall time. 7910 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7911 7912 if (DEBUG_ABI_SELECTION) { 7913 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7914 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7915 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7916 } 7917 7918 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7919 // We don't do this here during boot because we can do it all 7920 // at once after scanning all existing packages. 7921 // 7922 // We also do this *before* we perform dexopt on this package, so that 7923 // we can avoid redundant dexopts, and also to make sure we've got the 7924 // code and package path correct. 7925 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7926 pkg, true /* boot complete */); 7927 } 7928 7929 if (mFactoryTest && pkg.requestedPermissions.contains( 7930 android.Manifest.permission.FACTORY_TEST)) { 7931 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7932 } 7933 7934 ArrayList<PackageParser.Package> clientLibPkgs = null; 7935 7936 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7937 if (nonMutatedPs != null) { 7938 synchronized (mPackages) { 7939 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 7940 } 7941 } 7942 return pkg; 7943 } 7944 7945 // Only privileged apps and updated privileged apps can add child packages. 7946 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 7947 if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) { 7948 throw new PackageManagerException("Only privileged apps and updated " 7949 + "privileged apps can add child packages. Ignoring package " 7950 + pkg.packageName); 7951 } 7952 final int childCount = pkg.childPackages.size(); 7953 for (int i = 0; i < childCount; i++) { 7954 PackageParser.Package childPkg = pkg.childPackages.get(i); 7955 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 7956 childPkg.packageName)) { 7957 throw new PackageManagerException("Cannot override a child package of " 7958 + "another disabled system app. Ignoring package " + pkg.packageName); 7959 } 7960 } 7961 } 7962 7963 // writer 7964 synchronized (mPackages) { 7965 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7966 // Only system apps can add new shared libraries. 7967 if (pkg.libraryNames != null) { 7968 for (int i=0; i<pkg.libraryNames.size(); i++) { 7969 String name = pkg.libraryNames.get(i); 7970 boolean allowed = false; 7971 if (pkg.isUpdatedSystemApp()) { 7972 // New library entries can only be added through the 7973 // system image. This is important to get rid of a lot 7974 // of nasty edge cases: for example if we allowed a non- 7975 // system update of the app to add a library, then uninstalling 7976 // the update would make the library go away, and assumptions 7977 // we made such as through app install filtering would now 7978 // have allowed apps on the device which aren't compatible 7979 // with it. Better to just have the restriction here, be 7980 // conservative, and create many fewer cases that can negatively 7981 // impact the user experience. 7982 final PackageSetting sysPs = mSettings 7983 .getDisabledSystemPkgLPr(pkg.packageName); 7984 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7985 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7986 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7987 allowed = true; 7988 break; 7989 } 7990 } 7991 } 7992 } else { 7993 allowed = true; 7994 } 7995 if (allowed) { 7996 if (!mSharedLibraries.containsKey(name)) { 7997 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7998 } else if (!name.equals(pkg.packageName)) { 7999 Slog.w(TAG, "Package " + pkg.packageName + " library " 8000 + name + " already exists; skipping"); 8001 } 8002 } else { 8003 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8004 + name + " that is not declared on system image; skipping"); 8005 } 8006 } 8007 if ((scanFlags & SCAN_BOOTING) == 0) { 8008 // If we are not booting, we need to update any applications 8009 // that are clients of our shared library. If we are booting, 8010 // this will all be done once the scan is complete. 8011 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8012 } 8013 } 8014 } 8015 } 8016 8017 // Request the ActivityManager to kill the process(only for existing packages) 8018 // so that we do not end up in a confused state while the user is still using the older 8019 // version of the application while the new one gets installed. 8020 final boolean isReplacing = (scanFlags & SCAN_REPLACING) != 0; 8021 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 8022 if (killApp) { 8023 if (isReplacing) { 8024 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 8025 8026 killApplication(pkg.applicationInfo.packageName, 8027 pkg.applicationInfo.uid, "replace pkg"); 8028 8029 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8030 } 8031 } 8032 8033 // Also need to kill any apps that are dependent on the library. 8034 if (clientLibPkgs != null) { 8035 for (int i=0; i<clientLibPkgs.size(); i++) { 8036 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8037 killApplication(clientPkg.applicationInfo.packageName, 8038 clientPkg.applicationInfo.uid, "update lib"); 8039 } 8040 } 8041 8042 // Make sure we're not adding any bogus keyset info 8043 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8044 ksms.assertScannedPackageValid(pkg); 8045 8046 // writer 8047 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8048 8049 boolean createIdmapFailed = false; 8050 synchronized (mPackages) { 8051 // We don't expect installation to fail beyond this point 8052 8053 // Add the new setting to mSettings 8054 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8055 // Add the new setting to mPackages 8056 mPackages.put(pkg.applicationInfo.packageName, pkg); 8057 // Make sure we don't accidentally delete its data. 8058 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8059 while (iter.hasNext()) { 8060 PackageCleanItem item = iter.next(); 8061 if (pkgName.equals(item.packageName)) { 8062 iter.remove(); 8063 } 8064 } 8065 8066 // Take care of first install / last update times. 8067 if (currentTime != 0) { 8068 if (pkgSetting.firstInstallTime == 0) { 8069 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8070 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8071 pkgSetting.lastUpdateTime = currentTime; 8072 } 8073 } else if (pkgSetting.firstInstallTime == 0) { 8074 // We need *something*. Take time time stamp of the file. 8075 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8076 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8077 if (scanFileTime != pkgSetting.timeStamp) { 8078 // A package on the system image has changed; consider this 8079 // to be an update. 8080 pkgSetting.lastUpdateTime = scanFileTime; 8081 } 8082 } 8083 8084 // Add the package's KeySets to the global KeySetManagerService 8085 ksms.addScannedPackageLPw(pkg); 8086 8087 int N = pkg.providers.size(); 8088 StringBuilder r = null; 8089 int i; 8090 for (i=0; i<N; i++) { 8091 PackageParser.Provider p = pkg.providers.get(i); 8092 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8093 p.info.processName, pkg.applicationInfo.uid); 8094 mProviders.addProvider(p); 8095 p.syncable = p.info.isSyncable; 8096 if (p.info.authority != null) { 8097 String names[] = p.info.authority.split(";"); 8098 p.info.authority = null; 8099 for (int j = 0; j < names.length; j++) { 8100 if (j == 1 && p.syncable) { 8101 // We only want the first authority for a provider to possibly be 8102 // syncable, so if we already added this provider using a different 8103 // authority clear the syncable flag. We copy the provider before 8104 // changing it because the mProviders object contains a reference 8105 // to a provider that we don't want to change. 8106 // Only do this for the second authority since the resulting provider 8107 // object can be the same for all future authorities for this provider. 8108 p = new PackageParser.Provider(p); 8109 p.syncable = false; 8110 } 8111 if (!mProvidersByAuthority.containsKey(names[j])) { 8112 mProvidersByAuthority.put(names[j], p); 8113 if (p.info.authority == null) { 8114 p.info.authority = names[j]; 8115 } else { 8116 p.info.authority = p.info.authority + ";" + names[j]; 8117 } 8118 if (DEBUG_PACKAGE_SCANNING) { 8119 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 8120 Log.d(TAG, "Registered content provider: " + names[j] 8121 + ", className = " + p.info.name + ", isSyncable = " 8122 + p.info.isSyncable); 8123 } 8124 } else { 8125 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8126 Slog.w(TAG, "Skipping provider name " + names[j] + 8127 " (in package " + pkg.applicationInfo.packageName + 8128 "): name already used by " 8129 + ((other != null && other.getComponentName() != null) 8130 ? other.getComponentName().getPackageName() : "?")); 8131 } 8132 } 8133 } 8134 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8135 if (r == null) { 8136 r = new StringBuilder(256); 8137 } else { 8138 r.append(' '); 8139 } 8140 r.append(p.info.name); 8141 } 8142 } 8143 if (r != null) { 8144 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8145 } 8146 8147 N = pkg.services.size(); 8148 r = null; 8149 for (i=0; i<N; i++) { 8150 PackageParser.Service s = pkg.services.get(i); 8151 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8152 s.info.processName, pkg.applicationInfo.uid); 8153 mServices.addService(s); 8154 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8155 if (r == null) { 8156 r = new StringBuilder(256); 8157 } else { 8158 r.append(' '); 8159 } 8160 r.append(s.info.name); 8161 } 8162 } 8163 if (r != null) { 8164 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8165 } 8166 8167 N = pkg.receivers.size(); 8168 r = null; 8169 for (i=0; i<N; i++) { 8170 PackageParser.Activity a = pkg.receivers.get(i); 8171 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8172 a.info.processName, pkg.applicationInfo.uid); 8173 mReceivers.addActivity(a, "receiver"); 8174 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8175 if (r == null) { 8176 r = new StringBuilder(256); 8177 } else { 8178 r.append(' '); 8179 } 8180 r.append(a.info.name); 8181 } 8182 } 8183 if (r != null) { 8184 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8185 } 8186 8187 N = pkg.activities.size(); 8188 r = null; 8189 for (i=0; i<N; i++) { 8190 PackageParser.Activity a = pkg.activities.get(i); 8191 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8192 a.info.processName, pkg.applicationInfo.uid); 8193 mActivities.addActivity(a, "activity"); 8194 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8195 if (r == null) { 8196 r = new StringBuilder(256); 8197 } else { 8198 r.append(' '); 8199 } 8200 r.append(a.info.name); 8201 } 8202 } 8203 if (r != null) { 8204 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8205 } 8206 8207 N = pkg.permissionGroups.size(); 8208 r = null; 8209 for (i=0; i<N; i++) { 8210 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8211 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8212 if (cur == null) { 8213 mPermissionGroups.put(pg.info.name, pg); 8214 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8215 if (r == null) { 8216 r = new StringBuilder(256); 8217 } else { 8218 r.append(' '); 8219 } 8220 r.append(pg.info.name); 8221 } 8222 } else { 8223 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8224 + pg.info.packageName + " ignored: original from " 8225 + cur.info.packageName); 8226 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8227 if (r == null) { 8228 r = new StringBuilder(256); 8229 } else { 8230 r.append(' '); 8231 } 8232 r.append("DUP:"); 8233 r.append(pg.info.name); 8234 } 8235 } 8236 } 8237 if (r != null) { 8238 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8239 } 8240 8241 N = pkg.permissions.size(); 8242 r = null; 8243 for (i=0; i<N; i++) { 8244 PackageParser.Permission p = pkg.permissions.get(i); 8245 8246 // Assume by default that we did not install this permission into the system. 8247 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8248 8249 // Now that permission groups have a special meaning, we ignore permission 8250 // groups for legacy apps to prevent unexpected behavior. In particular, 8251 // permissions for one app being granted to someone just becase they happen 8252 // to be in a group defined by another app (before this had no implications). 8253 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8254 p.group = mPermissionGroups.get(p.info.group); 8255 // Warn for a permission in an unknown group. 8256 if (p.info.group != null && p.group == null) { 8257 Slog.w(TAG, "Permission " + p.info.name + " from package " 8258 + p.info.packageName + " in an unknown group " + p.info.group); 8259 } 8260 } 8261 8262 ArrayMap<String, BasePermission> permissionMap = 8263 p.tree ? mSettings.mPermissionTrees 8264 : mSettings.mPermissions; 8265 BasePermission bp = permissionMap.get(p.info.name); 8266 8267 // Allow system apps to redefine non-system permissions 8268 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8269 final boolean currentOwnerIsSystem = (bp.perm != null 8270 && isSystemApp(bp.perm.owner)); 8271 if (isSystemApp(p.owner)) { 8272 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8273 // It's a built-in permission and no owner, take ownership now 8274 bp.packageSetting = pkgSetting; 8275 bp.perm = p; 8276 bp.uid = pkg.applicationInfo.uid; 8277 bp.sourcePackage = p.info.packageName; 8278 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8279 } else if (!currentOwnerIsSystem) { 8280 String msg = "New decl " + p.owner + " of permission " 8281 + p.info.name + " is system; overriding " + bp.sourcePackage; 8282 reportSettingsProblem(Log.WARN, msg); 8283 bp = null; 8284 } 8285 } 8286 } 8287 8288 if (bp == null) { 8289 bp = new BasePermission(p.info.name, p.info.packageName, 8290 BasePermission.TYPE_NORMAL); 8291 permissionMap.put(p.info.name, bp); 8292 } 8293 8294 if (bp.perm == null) { 8295 if (bp.sourcePackage == null 8296 || bp.sourcePackage.equals(p.info.packageName)) { 8297 BasePermission tree = findPermissionTreeLP(p.info.name); 8298 if (tree == null 8299 || tree.sourcePackage.equals(p.info.packageName)) { 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 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8306 if (r == null) { 8307 r = new StringBuilder(256); 8308 } else { 8309 r.append(' '); 8310 } 8311 r.append(p.info.name); 8312 } 8313 } else { 8314 Slog.w(TAG, "Permission " + p.info.name + " from package " 8315 + p.info.packageName + " ignored: base tree " 8316 + tree.name + " is from package " 8317 + tree.sourcePackage); 8318 } 8319 } else { 8320 Slog.w(TAG, "Permission " + p.info.name + " from package " 8321 + p.info.packageName + " ignored: original from " 8322 + bp.sourcePackage); 8323 } 8324 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8325 if (r == null) { 8326 r = new StringBuilder(256); 8327 } else { 8328 r.append(' '); 8329 } 8330 r.append("DUP:"); 8331 r.append(p.info.name); 8332 } 8333 if (bp.perm == p) { 8334 bp.protectionLevel = p.info.protectionLevel; 8335 } 8336 } 8337 8338 if (r != null) { 8339 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8340 } 8341 8342 N = pkg.instrumentation.size(); 8343 r = null; 8344 for (i=0; i<N; i++) { 8345 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8346 a.info.packageName = pkg.applicationInfo.packageName; 8347 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8348 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8349 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8350 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8351 a.info.dataDir = pkg.applicationInfo.dataDir; 8352 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8353 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8354 8355 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8356 // need other information about the application, like the ABI and what not ? 8357 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8358 mInstrumentation.put(a.getComponentName(), a); 8359 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8360 if (r == null) { 8361 r = new StringBuilder(256); 8362 } else { 8363 r.append(' '); 8364 } 8365 r.append(a.info.name); 8366 } 8367 } 8368 if (r != null) { 8369 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8370 } 8371 8372 if (pkg.protectedBroadcasts != null) { 8373 N = pkg.protectedBroadcasts.size(); 8374 for (i=0; i<N; i++) { 8375 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8376 } 8377 } 8378 8379 pkgSetting.setTimeStamp(scanFileTime); 8380 8381 // Create idmap files for pairs of (packages, overlay packages). 8382 // Note: "android", ie framework-res.apk, is handled by native layers. 8383 if (pkg.mOverlayTarget != null) { 8384 // This is an overlay package. 8385 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8386 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8387 mOverlays.put(pkg.mOverlayTarget, 8388 new ArrayMap<String, PackageParser.Package>()); 8389 } 8390 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8391 map.put(pkg.packageName, pkg); 8392 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8393 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8394 createIdmapFailed = true; 8395 } 8396 } 8397 } else if (mOverlays.containsKey(pkg.packageName) && 8398 !pkg.packageName.equals("android")) { 8399 // This is a regular package, with one or more known overlay packages. 8400 createIdmapsForPackageLI(pkg); 8401 } 8402 } 8403 8404 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8405 8406 if (createIdmapFailed) { 8407 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8408 "scanPackageLI failed to createIdmap"); 8409 } 8410 return pkg; 8411 } 8412 8413 /** 8414 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8415 * is derived purely on the basis of the contents of {@code scanFile} and 8416 * {@code cpuAbiOverride}. 8417 * 8418 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8419 */ 8420 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8421 String cpuAbiOverride, boolean extractLibs) 8422 throws PackageManagerException { 8423 // TODO: We can probably be smarter about this stuff. For installed apps, 8424 // we can calculate this information at install time once and for all. For 8425 // system apps, we can probably assume that this information doesn't change 8426 // after the first boot scan. As things stand, we do lots of unnecessary work. 8427 8428 // Give ourselves some initial paths; we'll come back for another 8429 // pass once we've determined ABI below. 8430 setNativeLibraryPaths(pkg); 8431 8432 // We would never need to extract libs for forward-locked and external packages, 8433 // since the container service will do it for us. We shouldn't attempt to 8434 // extract libs from system app when it was not updated. 8435 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8436 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8437 extractLibs = false; 8438 } 8439 8440 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8441 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8442 8443 NativeLibraryHelper.Handle handle = null; 8444 try { 8445 handle = NativeLibraryHelper.Handle.create(pkg); 8446 // TODO(multiArch): This can be null for apps that didn't go through the 8447 // usual installation process. We can calculate it again, like we 8448 // do during install time. 8449 // 8450 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8451 // unnecessary. 8452 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8453 8454 // Null out the abis so that they can be recalculated. 8455 pkg.applicationInfo.primaryCpuAbi = null; 8456 pkg.applicationInfo.secondaryCpuAbi = null; 8457 if (isMultiArch(pkg.applicationInfo)) { 8458 // Warn if we've set an abiOverride for multi-lib packages.. 8459 // By definition, we need to copy both 32 and 64 bit libraries for 8460 // such packages. 8461 if (pkg.cpuAbiOverride != null 8462 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8463 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8464 } 8465 8466 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8467 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8468 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8469 if (extractLibs) { 8470 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8471 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8472 useIsaSpecificSubdirs); 8473 } else { 8474 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8475 } 8476 } 8477 8478 maybeThrowExceptionForMultiArchCopy( 8479 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8480 8481 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8482 if (extractLibs) { 8483 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8484 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8485 useIsaSpecificSubdirs); 8486 } else { 8487 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8488 } 8489 } 8490 8491 maybeThrowExceptionForMultiArchCopy( 8492 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8493 8494 if (abi64 >= 0) { 8495 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8496 } 8497 8498 if (abi32 >= 0) { 8499 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8500 if (abi64 >= 0) { 8501 if (cpuAbiOverride == null && pkg.use32bitAbi) { 8502 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8503 pkg.applicationInfo.primaryCpuAbi = abi; 8504 } else { 8505 pkg.applicationInfo.secondaryCpuAbi = abi; 8506 } 8507 } else { 8508 pkg.applicationInfo.primaryCpuAbi = abi; 8509 } 8510 } 8511 8512 } else { 8513 String[] abiList = (cpuAbiOverride != null) ? 8514 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8515 8516 // Enable gross and lame hacks for apps that are built with old 8517 // SDK tools. We must scan their APKs for renderscript bitcode and 8518 // not launch them if it's present. Don't bother checking on devices 8519 // that don't have 64 bit support. 8520 boolean needsRenderScriptOverride = false; 8521 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8522 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8523 abiList = Build.SUPPORTED_32_BIT_ABIS; 8524 needsRenderScriptOverride = true; 8525 } 8526 8527 final int copyRet; 8528 if (extractLibs) { 8529 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8530 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8531 } else { 8532 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8533 } 8534 8535 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8536 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8537 "Error unpackaging native libs for app, errorCode=" + copyRet); 8538 } 8539 8540 if (copyRet >= 0) { 8541 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8542 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8543 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8544 } else if (needsRenderScriptOverride) { 8545 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8546 } 8547 } 8548 } catch (IOException ioe) { 8549 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8550 } finally { 8551 IoUtils.closeQuietly(handle); 8552 } 8553 8554 // Now that we've calculated the ABIs and determined if it's an internal app, 8555 // we will go ahead and populate the nativeLibraryPath. 8556 setNativeLibraryPaths(pkg); 8557 } 8558 8559 /** 8560 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8561 * i.e, so that all packages can be run inside a single process if required. 8562 * 8563 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8564 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8565 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8566 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8567 * updating a package that belongs to a shared user. 8568 * 8569 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8570 * adds unnecessary complexity. 8571 */ 8572 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8573 PackageParser.Package scannedPackage, boolean bootComplete) { 8574 String requiredInstructionSet = null; 8575 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8576 requiredInstructionSet = VMRuntime.getInstructionSet( 8577 scannedPackage.applicationInfo.primaryCpuAbi); 8578 } 8579 8580 PackageSetting requirer = null; 8581 for (PackageSetting ps : packagesForUser) { 8582 // If packagesForUser contains scannedPackage, we skip it. This will happen 8583 // when scannedPackage is an update of an existing package. Without this check, 8584 // we will never be able to change the ABI of any package belonging to a shared 8585 // user, even if it's compatible with other packages. 8586 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8587 if (ps.primaryCpuAbiString == null) { 8588 continue; 8589 } 8590 8591 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8592 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8593 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8594 // this but there's not much we can do. 8595 String errorMessage = "Instruction set mismatch, " 8596 + ((requirer == null) ? "[caller]" : requirer) 8597 + " requires " + requiredInstructionSet + " whereas " + ps 8598 + " requires " + instructionSet; 8599 Slog.w(TAG, errorMessage); 8600 } 8601 8602 if (requiredInstructionSet == null) { 8603 requiredInstructionSet = instructionSet; 8604 requirer = ps; 8605 } 8606 } 8607 } 8608 8609 if (requiredInstructionSet != null) { 8610 String adjustedAbi; 8611 if (requirer != null) { 8612 // requirer != null implies that either scannedPackage was null or that scannedPackage 8613 // did not require an ABI, in which case we have to adjust scannedPackage to match 8614 // the ABI of the set (which is the same as requirer's ABI) 8615 adjustedAbi = requirer.primaryCpuAbiString; 8616 if (scannedPackage != null) { 8617 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8618 } 8619 } else { 8620 // requirer == null implies that we're updating all ABIs in the set to 8621 // match scannedPackage. 8622 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8623 } 8624 8625 for (PackageSetting ps : packagesForUser) { 8626 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8627 if (ps.primaryCpuAbiString != null) { 8628 continue; 8629 } 8630 8631 ps.primaryCpuAbiString = adjustedAbi; 8632 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8633 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8634 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8635 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8636 + " (requirer=" 8637 + (requirer == null ? "null" : requirer.pkg.packageName) 8638 + ", scannedPackage=" 8639 + (scannedPackage != null ? scannedPackage.packageName : "null") 8640 + ")"); 8641 try { 8642 mInstaller.rmdex(ps.codePathString, 8643 getDexCodeInstructionSet(getPreferredInstructionSet())); 8644 } catch (InstallerException ignored) { 8645 } 8646 } 8647 } 8648 } 8649 } 8650 } 8651 8652 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8653 synchronized (mPackages) { 8654 mResolverReplaced = true; 8655 // Set up information for custom user intent resolution activity. 8656 mResolveActivity.applicationInfo = pkg.applicationInfo; 8657 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8658 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8659 mResolveActivity.processName = pkg.applicationInfo.packageName; 8660 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8661 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8662 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8663 mResolveActivity.theme = 0; 8664 mResolveActivity.exported = true; 8665 mResolveActivity.enabled = true; 8666 mResolveInfo.activityInfo = mResolveActivity; 8667 mResolveInfo.priority = 0; 8668 mResolveInfo.preferredOrder = 0; 8669 mResolveInfo.match = 0; 8670 mResolveComponentName = mCustomResolverComponentName; 8671 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8672 mResolveComponentName); 8673 } 8674 } 8675 8676 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8677 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8678 8679 // Set up information for ephemeral installer activity 8680 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8681 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8682 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8683 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8684 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8685 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8686 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8687 mEphemeralInstallerActivity.theme = 0; 8688 mEphemeralInstallerActivity.exported = true; 8689 mEphemeralInstallerActivity.enabled = true; 8690 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8691 mEphemeralInstallerInfo.priority = 0; 8692 mEphemeralInstallerInfo.preferredOrder = 0; 8693 mEphemeralInstallerInfo.match = 0; 8694 8695 if (DEBUG_EPHEMERAL) { 8696 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8697 } 8698 } 8699 8700 private static String calculateBundledApkRoot(final String codePathString) { 8701 final File codePath = new File(codePathString); 8702 final File codeRoot; 8703 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8704 codeRoot = Environment.getRootDirectory(); 8705 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8706 codeRoot = Environment.getOemDirectory(); 8707 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8708 codeRoot = Environment.getVendorDirectory(); 8709 } else { 8710 // Unrecognized code path; take its top real segment as the apk root: 8711 // e.g. /something/app/blah.apk => /something 8712 try { 8713 File f = codePath.getCanonicalFile(); 8714 File parent = f.getParentFile(); // non-null because codePath is a file 8715 File tmp; 8716 while ((tmp = parent.getParentFile()) != null) { 8717 f = parent; 8718 parent = tmp; 8719 } 8720 codeRoot = f; 8721 Slog.w(TAG, "Unrecognized code path " 8722 + codePath + " - using " + codeRoot); 8723 } catch (IOException e) { 8724 // Can't canonicalize the code path -- shenanigans? 8725 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8726 return Environment.getRootDirectory().getPath(); 8727 } 8728 } 8729 return codeRoot.getPath(); 8730 } 8731 8732 /** 8733 * Derive and set the location of native libraries for the given package, 8734 * which varies depending on where and how the package was installed. 8735 */ 8736 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8737 final ApplicationInfo info = pkg.applicationInfo; 8738 final String codePath = pkg.codePath; 8739 final File codeFile = new File(codePath); 8740 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8741 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8742 8743 info.nativeLibraryRootDir = null; 8744 info.nativeLibraryRootRequiresIsa = false; 8745 info.nativeLibraryDir = null; 8746 info.secondaryNativeLibraryDir = null; 8747 8748 if (isApkFile(codeFile)) { 8749 // Monolithic install 8750 if (bundledApp) { 8751 // If "/system/lib64/apkname" exists, assume that is the per-package 8752 // native library directory to use; otherwise use "/system/lib/apkname". 8753 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8754 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8755 getPrimaryInstructionSet(info)); 8756 8757 // This is a bundled system app so choose the path based on the ABI. 8758 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8759 // is just the default path. 8760 final String apkName = deriveCodePathName(codePath); 8761 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8762 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8763 apkName).getAbsolutePath(); 8764 8765 if (info.secondaryCpuAbi != null) { 8766 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8767 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8768 secondaryLibDir, apkName).getAbsolutePath(); 8769 } 8770 } else if (asecApp) { 8771 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8772 .getAbsolutePath(); 8773 } else { 8774 final String apkName = deriveCodePathName(codePath); 8775 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8776 .getAbsolutePath(); 8777 } 8778 8779 info.nativeLibraryRootRequiresIsa = false; 8780 info.nativeLibraryDir = info.nativeLibraryRootDir; 8781 } else { 8782 // Cluster install 8783 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8784 info.nativeLibraryRootRequiresIsa = true; 8785 8786 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8787 getPrimaryInstructionSet(info)).getAbsolutePath(); 8788 8789 if (info.secondaryCpuAbi != null) { 8790 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8791 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8792 } 8793 } 8794 } 8795 8796 /** 8797 * Calculate the abis and roots for a bundled app. These can uniquely 8798 * be determined from the contents of the system partition, i.e whether 8799 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8800 * of this information, and instead assume that the system was built 8801 * sensibly. 8802 */ 8803 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8804 PackageSetting pkgSetting) { 8805 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8806 8807 // If "/system/lib64/apkname" exists, assume that is the per-package 8808 // native library directory to use; otherwise use "/system/lib/apkname". 8809 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8810 setBundledAppAbi(pkg, apkRoot, apkName); 8811 // pkgSetting might be null during rescan following uninstall of updates 8812 // to a bundled app, so accommodate that possibility. The settings in 8813 // that case will be established later from the parsed package. 8814 // 8815 // If the settings aren't null, sync them up with what we've just derived. 8816 // note that apkRoot isn't stored in the package settings. 8817 if (pkgSetting != null) { 8818 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8819 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8820 } 8821 } 8822 8823 /** 8824 * Deduces the ABI of a bundled app and sets the relevant fields on the 8825 * parsed pkg object. 8826 * 8827 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8828 * under which system libraries are installed. 8829 * @param apkName the name of the installed package. 8830 */ 8831 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8832 final File codeFile = new File(pkg.codePath); 8833 8834 final boolean has64BitLibs; 8835 final boolean has32BitLibs; 8836 if (isApkFile(codeFile)) { 8837 // Monolithic install 8838 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8839 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8840 } else { 8841 // Cluster install 8842 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8843 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8844 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8845 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8846 has64BitLibs = (new File(rootDir, isa)).exists(); 8847 } else { 8848 has64BitLibs = false; 8849 } 8850 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8851 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8852 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8853 has32BitLibs = (new File(rootDir, isa)).exists(); 8854 } else { 8855 has32BitLibs = false; 8856 } 8857 } 8858 8859 if (has64BitLibs && !has32BitLibs) { 8860 // The package has 64 bit libs, but not 32 bit libs. Its primary 8861 // ABI should be 64 bit. We can safely assume here that the bundled 8862 // native libraries correspond to the most preferred ABI in the list. 8863 8864 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8865 pkg.applicationInfo.secondaryCpuAbi = null; 8866 } else if (has32BitLibs && !has64BitLibs) { 8867 // The package has 32 bit libs but not 64 bit libs. Its primary 8868 // ABI should be 32 bit. 8869 8870 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8871 pkg.applicationInfo.secondaryCpuAbi = null; 8872 } else if (has32BitLibs && has64BitLibs) { 8873 // The application has both 64 and 32 bit bundled libraries. We check 8874 // here that the app declares multiArch support, and warn if it doesn't. 8875 // 8876 // We will be lenient here and record both ABIs. The primary will be the 8877 // ABI that's higher on the list, i.e, a device that's configured to prefer 8878 // 64 bit apps will see a 64 bit primary ABI, 8879 8880 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8881 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 8882 } 8883 8884 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8885 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8886 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8887 } else { 8888 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8889 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8890 } 8891 } else { 8892 pkg.applicationInfo.primaryCpuAbi = null; 8893 pkg.applicationInfo.secondaryCpuAbi = null; 8894 } 8895 } 8896 8897 private void killPackage(PackageParser.Package pkg, String reason) { 8898 // Kill the parent package 8899 killApplication(pkg.packageName, pkg.applicationInfo.uid, reason); 8900 // Kill the child packages 8901 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8902 for (int i = 0; i < childCount; i++) { 8903 PackageParser.Package childPkg = pkg.childPackages.get(i); 8904 killApplication(childPkg.packageName, childPkg.applicationInfo.uid, reason); 8905 } 8906 } 8907 8908 private void killApplication(String pkgName, int appId, String reason) { 8909 // Request the ActivityManager to kill the process(only for existing packages) 8910 // so that we do not end up in a confused state while the user is still using the older 8911 // version of the application while the new one gets installed. 8912 IActivityManager am = ActivityManagerNative.getDefault(); 8913 if (am != null) { 8914 try { 8915 am.killApplicationWithAppId(pkgName, appId, reason); 8916 } catch (RemoteException e) { 8917 } 8918 } 8919 } 8920 8921 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 8922 // Remove the parent package setting 8923 PackageSetting ps = (PackageSetting) pkg.mExtras; 8924 if (ps != null) { 8925 removePackageLI(ps, chatty); 8926 } 8927 // Remove the child package setting 8928 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8929 for (int i = 0; i < childCount; i++) { 8930 PackageParser.Package childPkg = pkg.childPackages.get(i); 8931 ps = (PackageSetting) childPkg.mExtras; 8932 if (ps != null) { 8933 removePackageLI(ps, chatty); 8934 } 8935 } 8936 } 8937 8938 void removePackageLI(PackageSetting ps, boolean chatty) { 8939 if (DEBUG_INSTALL) { 8940 if (chatty) 8941 Log.d(TAG, "Removing package " + ps.name); 8942 } 8943 8944 // writer 8945 synchronized (mPackages) { 8946 mPackages.remove(ps.name); 8947 final PackageParser.Package pkg = ps.pkg; 8948 if (pkg != null) { 8949 cleanPackageDataStructuresLILPw(pkg, chatty); 8950 } 8951 } 8952 } 8953 8954 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8955 if (DEBUG_INSTALL) { 8956 if (chatty) 8957 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8958 } 8959 8960 // writer 8961 synchronized (mPackages) { 8962 // Remove the parent package 8963 mPackages.remove(pkg.applicationInfo.packageName); 8964 cleanPackageDataStructuresLILPw(pkg, chatty); 8965 8966 // Remove the child packages 8967 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8968 for (int i = 0; i < childCount; i++) { 8969 PackageParser.Package childPkg = pkg.childPackages.get(i); 8970 mPackages.remove(childPkg.applicationInfo.packageName); 8971 cleanPackageDataStructuresLILPw(childPkg, chatty); 8972 } 8973 } 8974 } 8975 8976 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8977 int N = pkg.providers.size(); 8978 StringBuilder r = null; 8979 int i; 8980 for (i=0; i<N; i++) { 8981 PackageParser.Provider p = pkg.providers.get(i); 8982 mProviders.removeProvider(p); 8983 if (p.info.authority == null) { 8984 8985 /* There was another ContentProvider with this authority when 8986 * this app was installed so this authority is null, 8987 * Ignore it as we don't have to unregister the provider. 8988 */ 8989 continue; 8990 } 8991 String names[] = p.info.authority.split(";"); 8992 for (int j = 0; j < names.length; j++) { 8993 if (mProvidersByAuthority.get(names[j]) == p) { 8994 mProvidersByAuthority.remove(names[j]); 8995 if (DEBUG_REMOVE) { 8996 if (chatty) 8997 Log.d(TAG, "Unregistered content provider: " + names[j] 8998 + ", className = " + p.info.name + ", isSyncable = " 8999 + p.info.isSyncable); 9000 } 9001 } 9002 } 9003 if (DEBUG_REMOVE && chatty) { 9004 if (r == null) { 9005 r = new StringBuilder(256); 9006 } else { 9007 r.append(' '); 9008 } 9009 r.append(p.info.name); 9010 } 9011 } 9012 if (r != null) { 9013 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9014 } 9015 9016 N = pkg.services.size(); 9017 r = null; 9018 for (i=0; i<N; i++) { 9019 PackageParser.Service s = pkg.services.get(i); 9020 mServices.removeService(s); 9021 if (chatty) { 9022 if (r == null) { 9023 r = new StringBuilder(256); 9024 } else { 9025 r.append(' '); 9026 } 9027 r.append(s.info.name); 9028 } 9029 } 9030 if (r != null) { 9031 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9032 } 9033 9034 N = pkg.receivers.size(); 9035 r = null; 9036 for (i=0; i<N; i++) { 9037 PackageParser.Activity a = pkg.receivers.get(i); 9038 mReceivers.removeActivity(a, "receiver"); 9039 if (DEBUG_REMOVE && chatty) { 9040 if (r == null) { 9041 r = new StringBuilder(256); 9042 } else { 9043 r.append(' '); 9044 } 9045 r.append(a.info.name); 9046 } 9047 } 9048 if (r != null) { 9049 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9050 } 9051 9052 N = pkg.activities.size(); 9053 r = null; 9054 for (i=0; i<N; i++) { 9055 PackageParser.Activity a = pkg.activities.get(i); 9056 mActivities.removeActivity(a, "activity"); 9057 if (DEBUG_REMOVE && chatty) { 9058 if (r == null) { 9059 r = new StringBuilder(256); 9060 } else { 9061 r.append(' '); 9062 } 9063 r.append(a.info.name); 9064 } 9065 } 9066 if (r != null) { 9067 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9068 } 9069 9070 N = pkg.permissions.size(); 9071 r = null; 9072 for (i=0; i<N; i++) { 9073 PackageParser.Permission p = pkg.permissions.get(i); 9074 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9075 if (bp == null) { 9076 bp = mSettings.mPermissionTrees.get(p.info.name); 9077 } 9078 if (bp != null && bp.perm == p) { 9079 bp.perm = null; 9080 if (DEBUG_REMOVE && chatty) { 9081 if (r == null) { 9082 r = new StringBuilder(256); 9083 } else { 9084 r.append(' '); 9085 } 9086 r.append(p.info.name); 9087 } 9088 } 9089 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9090 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9091 if (appOpPkgs != null) { 9092 appOpPkgs.remove(pkg.packageName); 9093 } 9094 } 9095 } 9096 if (r != null) { 9097 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9098 } 9099 9100 N = pkg.requestedPermissions.size(); 9101 r = null; 9102 for (i=0; i<N; i++) { 9103 String perm = pkg.requestedPermissions.get(i); 9104 BasePermission bp = mSettings.mPermissions.get(perm); 9105 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9106 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9107 if (appOpPkgs != null) { 9108 appOpPkgs.remove(pkg.packageName); 9109 if (appOpPkgs.isEmpty()) { 9110 mAppOpPermissionPackages.remove(perm); 9111 } 9112 } 9113 } 9114 } 9115 if (r != null) { 9116 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9117 } 9118 9119 N = pkg.instrumentation.size(); 9120 r = null; 9121 for (i=0; i<N; i++) { 9122 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9123 mInstrumentation.remove(a.getComponentName()); 9124 if (DEBUG_REMOVE && chatty) { 9125 if (r == null) { 9126 r = new StringBuilder(256); 9127 } else { 9128 r.append(' '); 9129 } 9130 r.append(a.info.name); 9131 } 9132 } 9133 if (r != null) { 9134 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9135 } 9136 9137 r = null; 9138 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9139 // Only system apps can hold shared libraries. 9140 if (pkg.libraryNames != null) { 9141 for (i=0; i<pkg.libraryNames.size(); i++) { 9142 String name = pkg.libraryNames.get(i); 9143 SharedLibraryEntry cur = mSharedLibraries.get(name); 9144 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9145 mSharedLibraries.remove(name); 9146 if (DEBUG_REMOVE && chatty) { 9147 if (r == null) { 9148 r = new StringBuilder(256); 9149 } else { 9150 r.append(' '); 9151 } 9152 r.append(name); 9153 } 9154 } 9155 } 9156 } 9157 } 9158 if (r != null) { 9159 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9160 } 9161 } 9162 9163 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9164 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9165 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9166 return true; 9167 } 9168 } 9169 return false; 9170 } 9171 9172 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9173 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9174 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9175 9176 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9177 // Update the parent permissions 9178 updatePermissionsLPw(pkg.packageName, pkg, flags); 9179 // Update the child permissions 9180 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9181 for (int i = 0; i < childCount; i++) { 9182 PackageParser.Package childPkg = pkg.childPackages.get(i); 9183 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9184 } 9185 } 9186 9187 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9188 int flags) { 9189 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9190 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9191 } 9192 9193 private void updatePermissionsLPw(String changingPkg, 9194 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9195 // Make sure there are no dangling permission trees. 9196 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9197 while (it.hasNext()) { 9198 final BasePermission bp = it.next(); 9199 if (bp.packageSetting == null) { 9200 // We may not yet have parsed the package, so just see if 9201 // we still know about its settings. 9202 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9203 } 9204 if (bp.packageSetting == null) { 9205 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9206 + " from package " + bp.sourcePackage); 9207 it.remove(); 9208 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9209 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9210 Slog.i(TAG, "Removing old permission tree: " + bp.name 9211 + " from package " + bp.sourcePackage); 9212 flags |= UPDATE_PERMISSIONS_ALL; 9213 it.remove(); 9214 } 9215 } 9216 } 9217 9218 // Make sure all dynamic permissions have been assigned to a package, 9219 // and make sure there are no dangling permissions. 9220 it = mSettings.mPermissions.values().iterator(); 9221 while (it.hasNext()) { 9222 final BasePermission bp = it.next(); 9223 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9224 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9225 + bp.name + " pkg=" + bp.sourcePackage 9226 + " info=" + bp.pendingInfo); 9227 if (bp.packageSetting == null && bp.pendingInfo != null) { 9228 final BasePermission tree = findPermissionTreeLP(bp.name); 9229 if (tree != null && tree.perm != null) { 9230 bp.packageSetting = tree.packageSetting; 9231 bp.perm = new PackageParser.Permission(tree.perm.owner, 9232 new PermissionInfo(bp.pendingInfo)); 9233 bp.perm.info.packageName = tree.perm.info.packageName; 9234 bp.perm.info.name = bp.name; 9235 bp.uid = tree.uid; 9236 } 9237 } 9238 } 9239 if (bp.packageSetting == null) { 9240 // We may not yet have parsed the package, so just see if 9241 // we still know about its settings. 9242 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9243 } 9244 if (bp.packageSetting == null) { 9245 Slog.w(TAG, "Removing dangling permission: " + bp.name 9246 + " from package " + bp.sourcePackage); 9247 it.remove(); 9248 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9249 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9250 Slog.i(TAG, "Removing old permission: " + bp.name 9251 + " from package " + bp.sourcePackage); 9252 flags |= UPDATE_PERMISSIONS_ALL; 9253 it.remove(); 9254 } 9255 } 9256 } 9257 9258 // Now update the permissions for all packages, in particular 9259 // replace the granted permissions of the system packages. 9260 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9261 for (PackageParser.Package pkg : mPackages.values()) { 9262 if (pkg != pkgInfo) { 9263 // Only replace for packages on requested volume 9264 final String volumeUuid = getVolumeUuidForPackage(pkg); 9265 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9266 && Objects.equals(replaceVolumeUuid, volumeUuid); 9267 grantPermissionsLPw(pkg, replace, changingPkg); 9268 } 9269 } 9270 } 9271 9272 if (pkgInfo != null) { 9273 // Only replace for packages on requested volume 9274 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9275 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9276 && Objects.equals(replaceVolumeUuid, volumeUuid); 9277 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9278 } 9279 } 9280 9281 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9282 String packageOfInterest) { 9283 // IMPORTANT: There are two types of permissions: install and runtime. 9284 // Install time permissions are granted when the app is installed to 9285 // all device users and users added in the future. Runtime permissions 9286 // are granted at runtime explicitly to specific users. Normal and signature 9287 // protected permissions are install time permissions. Dangerous permissions 9288 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9289 // otherwise they are runtime permissions. This function does not manage 9290 // runtime permissions except for the case an app targeting Lollipop MR1 9291 // being upgraded to target a newer SDK, in which case dangerous permissions 9292 // are transformed from install time to runtime ones. 9293 9294 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9295 if (ps == null) { 9296 return; 9297 } 9298 9299 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9300 9301 PermissionsState permissionsState = ps.getPermissionsState(); 9302 PermissionsState origPermissions = permissionsState; 9303 9304 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9305 9306 boolean runtimePermissionsRevoked = false; 9307 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9308 9309 boolean changedInstallPermission = false; 9310 9311 if (replace) { 9312 ps.installPermissionsFixed = false; 9313 if (!ps.isSharedUser()) { 9314 origPermissions = new PermissionsState(permissionsState); 9315 permissionsState.reset(); 9316 } else { 9317 // We need to know only about runtime permission changes since the 9318 // calling code always writes the install permissions state but 9319 // the runtime ones are written only if changed. The only cases of 9320 // changed runtime permissions here are promotion of an install to 9321 // runtime and revocation of a runtime from a shared user. 9322 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9323 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9324 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9325 runtimePermissionsRevoked = true; 9326 } 9327 } 9328 } 9329 9330 permissionsState.setGlobalGids(mGlobalGids); 9331 9332 final int N = pkg.requestedPermissions.size(); 9333 for (int i=0; i<N; i++) { 9334 final String name = pkg.requestedPermissions.get(i); 9335 final BasePermission bp = mSettings.mPermissions.get(name); 9336 9337 if (DEBUG_INSTALL) { 9338 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9339 } 9340 9341 if (bp == null || bp.packageSetting == null) { 9342 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9343 Slog.w(TAG, "Unknown permission " + name 9344 + " in package " + pkg.packageName); 9345 } 9346 continue; 9347 } 9348 9349 final String perm = bp.name; 9350 boolean allowedSig = false; 9351 int grant = GRANT_DENIED; 9352 9353 // Keep track of app op permissions. 9354 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9355 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9356 if (pkgs == null) { 9357 pkgs = new ArraySet<>(); 9358 mAppOpPermissionPackages.put(bp.name, pkgs); 9359 } 9360 pkgs.add(pkg.packageName); 9361 } 9362 9363 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9364 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9365 >= Build.VERSION_CODES.M; 9366 switch (level) { 9367 case PermissionInfo.PROTECTION_NORMAL: { 9368 // For all apps normal permissions are install time ones. 9369 grant = GRANT_INSTALL; 9370 } break; 9371 9372 case PermissionInfo.PROTECTION_DANGEROUS: { 9373 // If a permission review is required for legacy apps we represent 9374 // their permissions as always granted runtime ones since we need 9375 // to keep the review required permission flag per user while an 9376 // install permission's state is shared across all users. 9377 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9378 // For legacy apps dangerous permissions are install time ones. 9379 grant = GRANT_INSTALL; 9380 } else if (origPermissions.hasInstallPermission(bp.name)) { 9381 // For legacy apps that became modern, install becomes runtime. 9382 grant = GRANT_UPGRADE; 9383 } else if (mPromoteSystemApps 9384 && isSystemApp(ps) 9385 && mExistingSystemPackages.contains(ps.name)) { 9386 // For legacy system apps, install becomes runtime. 9387 // We cannot check hasInstallPermission() for system apps since those 9388 // permissions were granted implicitly and not persisted pre-M. 9389 grant = GRANT_UPGRADE; 9390 } else { 9391 // For modern apps keep runtime permissions unchanged. 9392 grant = GRANT_RUNTIME; 9393 } 9394 } break; 9395 9396 case PermissionInfo.PROTECTION_SIGNATURE: { 9397 // For all apps signature permissions are install time ones. 9398 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9399 if (allowedSig) { 9400 grant = GRANT_INSTALL; 9401 } 9402 } break; 9403 } 9404 9405 if (DEBUG_INSTALL) { 9406 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9407 } 9408 9409 if (grant != GRANT_DENIED) { 9410 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9411 // If this is an existing, non-system package, then 9412 // we can't add any new permissions to it. 9413 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9414 // Except... if this is a permission that was added 9415 // to the platform (note: need to only do this when 9416 // updating the platform). 9417 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9418 grant = GRANT_DENIED; 9419 } 9420 } 9421 } 9422 9423 switch (grant) { 9424 case GRANT_INSTALL: { 9425 // Revoke this as runtime permission to handle the case of 9426 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 9427 for (int userId : UserManagerService.getInstance().getUserIds()) { 9428 if (origPermissions.getRuntimePermissionState( 9429 bp.name, userId) != null) { 9430 // Revoke the runtime permission and clear the flags. 9431 origPermissions.revokeRuntimePermission(bp, userId); 9432 origPermissions.updatePermissionFlags(bp, userId, 9433 PackageManager.MASK_PERMISSION_FLAGS, 0); 9434 // If we revoked a permission permission, we have to write. 9435 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9436 changedRuntimePermissionUserIds, userId); 9437 } 9438 } 9439 // Grant an install permission. 9440 if (permissionsState.grantInstallPermission(bp) != 9441 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9442 changedInstallPermission = true; 9443 } 9444 } break; 9445 9446 case GRANT_RUNTIME: { 9447 // Grant previously granted runtime permissions. 9448 for (int userId : UserManagerService.getInstance().getUserIds()) { 9449 PermissionState permissionState = origPermissions 9450 .getRuntimePermissionState(bp.name, userId); 9451 int flags = permissionState != null 9452 ? permissionState.getFlags() : 0; 9453 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9454 if (permissionsState.grantRuntimePermission(bp, userId) == 9455 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9456 // If we cannot put the permission as it was, we have to write. 9457 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9458 changedRuntimePermissionUserIds, userId); 9459 } 9460 // If the app supports runtime permissions no need for a review. 9461 if (Build.PERMISSIONS_REVIEW_REQUIRED 9462 && appSupportsRuntimePermissions 9463 && (flags & PackageManager 9464 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9465 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9466 // Since we changed the flags, we have to write. 9467 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9468 changedRuntimePermissionUserIds, userId); 9469 } 9470 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9471 && !appSupportsRuntimePermissions) { 9472 // For legacy apps that need a permission review, every new 9473 // runtime permission is granted but it is pending a review. 9474 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9475 permissionsState.grantRuntimePermission(bp, userId); 9476 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9477 // We changed the permission and flags, hence have to write. 9478 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9479 changedRuntimePermissionUserIds, userId); 9480 } 9481 } 9482 // Propagate the permission flags. 9483 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9484 } 9485 } break; 9486 9487 case GRANT_UPGRADE: { 9488 // Grant runtime permissions for a previously held install permission. 9489 PermissionState permissionState = origPermissions 9490 .getInstallPermissionState(bp.name); 9491 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9492 9493 if (origPermissions.revokeInstallPermission(bp) 9494 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9495 // We will be transferring the permission flags, so clear them. 9496 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9497 PackageManager.MASK_PERMISSION_FLAGS, 0); 9498 changedInstallPermission = true; 9499 } 9500 9501 // If the permission is not to be promoted to runtime we ignore it and 9502 // also its other flags as they are not applicable to install permissions. 9503 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9504 for (int userId : currentUserIds) { 9505 if (permissionsState.grantRuntimePermission(bp, userId) != 9506 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9507 // Transfer the permission flags. 9508 permissionsState.updatePermissionFlags(bp, userId, 9509 flags, flags); 9510 // If we granted the permission, we have to write. 9511 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9512 changedRuntimePermissionUserIds, userId); 9513 } 9514 } 9515 } 9516 } break; 9517 9518 default: { 9519 if (packageOfInterest == null 9520 || packageOfInterest.equals(pkg.packageName)) { 9521 Slog.w(TAG, "Not granting permission " + perm 9522 + " to package " + pkg.packageName 9523 + " because it was previously installed without"); 9524 } 9525 } break; 9526 } 9527 } else { 9528 if (permissionsState.revokeInstallPermission(bp) != 9529 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9530 // Also drop the permission flags. 9531 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9532 PackageManager.MASK_PERMISSION_FLAGS, 0); 9533 changedInstallPermission = true; 9534 Slog.i(TAG, "Un-granting permission " + perm 9535 + " from package " + pkg.packageName 9536 + " (protectionLevel=" + bp.protectionLevel 9537 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9538 + ")"); 9539 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9540 // Don't print warning for app op permissions, since it is fine for them 9541 // not to be granted, there is a UI for the user to decide. 9542 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9543 Slog.w(TAG, "Not granting permission " + perm 9544 + " to package " + pkg.packageName 9545 + " (protectionLevel=" + bp.protectionLevel 9546 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9547 + ")"); 9548 } 9549 } 9550 } 9551 } 9552 9553 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9554 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9555 // This is the first that we have heard about this package, so the 9556 // permissions we have now selected are fixed until explicitly 9557 // changed. 9558 ps.installPermissionsFixed = true; 9559 } 9560 9561 // Persist the runtime permissions state for users with changes. If permissions 9562 // were revoked because no app in the shared user declares them we have to 9563 // write synchronously to avoid losing runtime permissions state. 9564 for (int userId : changedRuntimePermissionUserIds) { 9565 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9566 } 9567 9568 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9569 } 9570 9571 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9572 boolean allowed = false; 9573 final int NP = PackageParser.NEW_PERMISSIONS.length; 9574 for (int ip=0; ip<NP; ip++) { 9575 final PackageParser.NewPermissionInfo npi 9576 = PackageParser.NEW_PERMISSIONS[ip]; 9577 if (npi.name.equals(perm) 9578 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9579 allowed = true; 9580 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9581 + pkg.packageName); 9582 break; 9583 } 9584 } 9585 return allowed; 9586 } 9587 9588 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9589 BasePermission bp, PermissionsState origPermissions) { 9590 boolean allowed; 9591 allowed = (compareSignatures( 9592 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9593 == PackageManager.SIGNATURE_MATCH) 9594 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9595 == PackageManager.SIGNATURE_MATCH); 9596 if (!allowed && (bp.protectionLevel 9597 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9598 if (isSystemApp(pkg)) { 9599 // For updated system applications, a system permission 9600 // is granted only if it had been defined by the original application. 9601 if (pkg.isUpdatedSystemApp()) { 9602 final PackageSetting sysPs = mSettings 9603 .getDisabledSystemPkgLPr(pkg.packageName); 9604 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9605 // If the original was granted this permission, we take 9606 // that grant decision as read and propagate it to the 9607 // update. 9608 if (sysPs.isPrivileged()) { 9609 allowed = true; 9610 } 9611 } else { 9612 // The system apk may have been updated with an older 9613 // version of the one on the data partition, but which 9614 // granted a new system permission that it didn't have 9615 // before. In this case we do want to allow the app to 9616 // now get the new permission if the ancestral apk is 9617 // privileged to get it. 9618 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9619 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9620 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9621 allowed = true; 9622 break; 9623 } 9624 } 9625 } 9626 // Also if a privileged parent package on the system image or any of 9627 // its children requested a privileged permission, the updated child 9628 // packages can also get the permission. 9629 if (pkg.parentPackage != null) { 9630 final PackageSetting disabledSysParentPs = mSettings 9631 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 9632 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 9633 && disabledSysParentPs.isPrivileged()) { 9634 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 9635 allowed = true; 9636 } else if (disabledSysParentPs.pkg.childPackages != null) { 9637 final int count = disabledSysParentPs.pkg.childPackages.size(); 9638 for (int i = 0; i < count; i++) { 9639 PackageParser.Package disabledSysChildPkg = 9640 disabledSysParentPs.pkg.childPackages.get(i); 9641 if (isPackageRequestingPermission(disabledSysChildPkg, 9642 perm)) { 9643 allowed = true; 9644 break; 9645 } 9646 } 9647 } 9648 } 9649 } 9650 } 9651 } else { 9652 allowed = isPrivilegedApp(pkg); 9653 } 9654 } 9655 } 9656 if (!allowed) { 9657 if (!allowed && (bp.protectionLevel 9658 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9659 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9660 // If this was a previously normal/dangerous permission that got moved 9661 // to a system permission as part of the runtime permission redesign, then 9662 // we still want to blindly grant it to old apps. 9663 allowed = true; 9664 } 9665 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9666 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9667 // If this permission is to be granted to the system installer and 9668 // this app is an installer, then it gets the permission. 9669 allowed = true; 9670 } 9671 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9672 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9673 // If this permission is to be granted to the system verifier and 9674 // this app is a verifier, then it gets the permission. 9675 allowed = true; 9676 } 9677 if (!allowed && (bp.protectionLevel 9678 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9679 && isSystemApp(pkg)) { 9680 // Any pre-installed system app is allowed to get this permission. 9681 allowed = true; 9682 } 9683 if (!allowed && (bp.protectionLevel 9684 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9685 // For development permissions, a development permission 9686 // is granted only if it was already granted. 9687 allowed = origPermissions.hasInstallPermission(perm); 9688 } 9689 } 9690 return allowed; 9691 } 9692 9693 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 9694 final int permCount = pkg.requestedPermissions.size(); 9695 for (int j = 0; j < permCount; j++) { 9696 String requestedPermission = pkg.requestedPermissions.get(j); 9697 if (permission.equals(requestedPermission)) { 9698 return true; 9699 } 9700 } 9701 return false; 9702 } 9703 9704 final class ActivityIntentResolver 9705 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9706 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9707 boolean defaultOnly, int userId) { 9708 if (!sUserManager.exists(userId)) return null; 9709 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9710 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9711 } 9712 9713 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9714 int userId) { 9715 if (!sUserManager.exists(userId)) return null; 9716 mFlags = flags; 9717 return super.queryIntent(intent, resolvedType, 9718 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9719 } 9720 9721 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9722 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9723 if (!sUserManager.exists(userId)) return null; 9724 if (packageActivities == null) { 9725 return null; 9726 } 9727 mFlags = flags; 9728 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9729 final int N = packageActivities.size(); 9730 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9731 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9732 9733 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9734 for (int i = 0; i < N; ++i) { 9735 intentFilters = packageActivities.get(i).intents; 9736 if (intentFilters != null && intentFilters.size() > 0) { 9737 PackageParser.ActivityIntentInfo[] array = 9738 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9739 intentFilters.toArray(array); 9740 listCut.add(array); 9741 } 9742 } 9743 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9744 } 9745 9746 public final void addActivity(PackageParser.Activity a, String type) { 9747 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 9748 mActivities.put(a.getComponentName(), a); 9749 if (DEBUG_SHOW_INFO) 9750 Log.v( 9751 TAG, " " + type + " " + 9752 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 9753 if (DEBUG_SHOW_INFO) 9754 Log.v(TAG, " Class=" + a.info.name); 9755 final int NI = a.intents.size(); 9756 for (int j=0; j<NI; j++) { 9757 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9758 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 9759 intent.setPriority(0); 9760 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 9761 + a.className + " with priority > 0, forcing to 0"); 9762 } 9763 if (DEBUG_SHOW_INFO) { 9764 Log.v(TAG, " IntentFilter:"); 9765 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9766 } 9767 if (!intent.debugCheck()) { 9768 Log.w(TAG, "==> For Activity " + a.info.name); 9769 } 9770 addFilter(intent); 9771 } 9772 } 9773 9774 public final void removeActivity(PackageParser.Activity a, String type) { 9775 mActivities.remove(a.getComponentName()); 9776 if (DEBUG_SHOW_INFO) { 9777 Log.v(TAG, " " + type + " " 9778 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 9779 : a.info.name) + ":"); 9780 Log.v(TAG, " Class=" + a.info.name); 9781 } 9782 final int NI = a.intents.size(); 9783 for (int j=0; j<NI; j++) { 9784 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9785 if (DEBUG_SHOW_INFO) { 9786 Log.v(TAG, " IntentFilter:"); 9787 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9788 } 9789 removeFilter(intent); 9790 } 9791 } 9792 9793 @Override 9794 protected boolean allowFilterResult( 9795 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 9796 ActivityInfo filterAi = filter.activity.info; 9797 for (int i=dest.size()-1; i>=0; i--) { 9798 ActivityInfo destAi = dest.get(i).activityInfo; 9799 if (destAi.name == filterAi.name 9800 && destAi.packageName == filterAi.packageName) { 9801 return false; 9802 } 9803 } 9804 return true; 9805 } 9806 9807 @Override 9808 protected ActivityIntentInfo[] newArray(int size) { 9809 return new ActivityIntentInfo[size]; 9810 } 9811 9812 @Override 9813 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 9814 if (!sUserManager.exists(userId)) return true; 9815 PackageParser.Package p = filter.activity.owner; 9816 if (p != null) { 9817 PackageSetting ps = (PackageSetting)p.mExtras; 9818 if (ps != null) { 9819 // System apps are never considered stopped for purposes of 9820 // filtering, because there may be no way for the user to 9821 // actually re-launch them. 9822 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 9823 && ps.getStopped(userId); 9824 } 9825 } 9826 return false; 9827 } 9828 9829 @Override 9830 protected boolean isPackageForFilter(String packageName, 9831 PackageParser.ActivityIntentInfo info) { 9832 return packageName.equals(info.activity.owner.packageName); 9833 } 9834 9835 @Override 9836 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 9837 int match, int userId) { 9838 if (!sUserManager.exists(userId)) return null; 9839 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 9840 return null; 9841 } 9842 final PackageParser.Activity activity = info.activity; 9843 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 9844 if (ps == null) { 9845 return null; 9846 } 9847 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 9848 ps.readUserState(userId), userId); 9849 if (ai == null) { 9850 return null; 9851 } 9852 final ResolveInfo res = new ResolveInfo(); 9853 res.activityInfo = ai; 9854 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9855 res.filter = info; 9856 } 9857 if (info != null) { 9858 res.handleAllWebDataURI = info.handleAllWebDataURI(); 9859 } 9860 res.priority = info.getPriority(); 9861 res.preferredOrder = activity.owner.mPreferredOrder; 9862 //System.out.println("Result: " + res.activityInfo.className + 9863 // " = " + res.priority); 9864 res.match = match; 9865 res.isDefault = info.hasDefault; 9866 res.labelRes = info.labelRes; 9867 res.nonLocalizedLabel = info.nonLocalizedLabel; 9868 if (userNeedsBadging(userId)) { 9869 res.noResourceId = true; 9870 } else { 9871 res.icon = info.icon; 9872 } 9873 res.iconResourceId = info.icon; 9874 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9875 return res; 9876 } 9877 9878 @Override 9879 protected void sortResults(List<ResolveInfo> results) { 9880 Collections.sort(results, mResolvePrioritySorter); 9881 } 9882 9883 @Override 9884 protected void dumpFilter(PrintWriter out, String prefix, 9885 PackageParser.ActivityIntentInfo filter) { 9886 out.print(prefix); out.print( 9887 Integer.toHexString(System.identityHashCode(filter.activity))); 9888 out.print(' '); 9889 filter.activity.printComponentShortName(out); 9890 out.print(" filter "); 9891 out.println(Integer.toHexString(System.identityHashCode(filter))); 9892 } 9893 9894 @Override 9895 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9896 return filter.activity; 9897 } 9898 9899 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9900 PackageParser.Activity activity = (PackageParser.Activity)label; 9901 out.print(prefix); out.print( 9902 Integer.toHexString(System.identityHashCode(activity))); 9903 out.print(' '); 9904 activity.printComponentShortName(out); 9905 if (count > 1) { 9906 out.print(" ("); out.print(count); out.print(" filters)"); 9907 } 9908 out.println(); 9909 } 9910 9911// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9912// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9913// final List<ResolveInfo> retList = Lists.newArrayList(); 9914// while (i.hasNext()) { 9915// final ResolveInfo resolveInfo = i.next(); 9916// if (isEnabledLP(resolveInfo.activityInfo)) { 9917// retList.add(resolveInfo); 9918// } 9919// } 9920// return retList; 9921// } 9922 9923 // Keys are String (activity class name), values are Activity. 9924 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9925 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9926 private int mFlags; 9927 } 9928 9929 private final class ServiceIntentResolver 9930 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9931 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9932 boolean defaultOnly, int userId) { 9933 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9934 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9935 } 9936 9937 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9938 int userId) { 9939 if (!sUserManager.exists(userId)) return null; 9940 mFlags = flags; 9941 return super.queryIntent(intent, resolvedType, 9942 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9943 } 9944 9945 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9946 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9947 if (!sUserManager.exists(userId)) return null; 9948 if (packageServices == null) { 9949 return null; 9950 } 9951 mFlags = flags; 9952 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9953 final int N = packageServices.size(); 9954 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9955 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9956 9957 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9958 for (int i = 0; i < N; ++i) { 9959 intentFilters = packageServices.get(i).intents; 9960 if (intentFilters != null && intentFilters.size() > 0) { 9961 PackageParser.ServiceIntentInfo[] array = 9962 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9963 intentFilters.toArray(array); 9964 listCut.add(array); 9965 } 9966 } 9967 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9968 } 9969 9970 public final void addService(PackageParser.Service s) { 9971 mServices.put(s.getComponentName(), s); 9972 if (DEBUG_SHOW_INFO) { 9973 Log.v(TAG, " " 9974 + (s.info.nonLocalizedLabel != null 9975 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9976 Log.v(TAG, " Class=" + s.info.name); 9977 } 9978 final int NI = s.intents.size(); 9979 int j; 9980 for (j=0; j<NI; j++) { 9981 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9982 if (DEBUG_SHOW_INFO) { 9983 Log.v(TAG, " IntentFilter:"); 9984 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9985 } 9986 if (!intent.debugCheck()) { 9987 Log.w(TAG, "==> For Service " + s.info.name); 9988 } 9989 addFilter(intent); 9990 } 9991 } 9992 9993 public final void removeService(PackageParser.Service s) { 9994 mServices.remove(s.getComponentName()); 9995 if (DEBUG_SHOW_INFO) { 9996 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9997 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9998 Log.v(TAG, " Class=" + s.info.name); 9999 } 10000 final int NI = s.intents.size(); 10001 int j; 10002 for (j=0; j<NI; j++) { 10003 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10004 if (DEBUG_SHOW_INFO) { 10005 Log.v(TAG, " IntentFilter:"); 10006 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10007 } 10008 removeFilter(intent); 10009 } 10010 } 10011 10012 @Override 10013 protected boolean allowFilterResult( 10014 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10015 ServiceInfo filterSi = filter.service.info; 10016 for (int i=dest.size()-1; i>=0; i--) { 10017 ServiceInfo destAi = dest.get(i).serviceInfo; 10018 if (destAi.name == filterSi.name 10019 && destAi.packageName == filterSi.packageName) { 10020 return false; 10021 } 10022 } 10023 return true; 10024 } 10025 10026 @Override 10027 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10028 return new PackageParser.ServiceIntentInfo[size]; 10029 } 10030 10031 @Override 10032 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10033 if (!sUserManager.exists(userId)) return true; 10034 PackageParser.Package p = filter.service.owner; 10035 if (p != null) { 10036 PackageSetting ps = (PackageSetting)p.mExtras; 10037 if (ps != null) { 10038 // System apps are never considered stopped for purposes of 10039 // filtering, because there may be no way for the user to 10040 // actually re-launch them. 10041 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10042 && ps.getStopped(userId); 10043 } 10044 } 10045 return false; 10046 } 10047 10048 @Override 10049 protected boolean isPackageForFilter(String packageName, 10050 PackageParser.ServiceIntentInfo info) { 10051 return packageName.equals(info.service.owner.packageName); 10052 } 10053 10054 @Override 10055 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10056 int match, int userId) { 10057 if (!sUserManager.exists(userId)) return null; 10058 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10059 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10060 return null; 10061 } 10062 final PackageParser.Service service = info.service; 10063 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10064 if (ps == null) { 10065 return null; 10066 } 10067 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10068 ps.readUserState(userId), userId); 10069 if (si == null) { 10070 return null; 10071 } 10072 final ResolveInfo res = new ResolveInfo(); 10073 res.serviceInfo = si; 10074 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10075 res.filter = filter; 10076 } 10077 res.priority = info.getPriority(); 10078 res.preferredOrder = service.owner.mPreferredOrder; 10079 res.match = match; 10080 res.isDefault = info.hasDefault; 10081 res.labelRes = info.labelRes; 10082 res.nonLocalizedLabel = info.nonLocalizedLabel; 10083 res.icon = info.icon; 10084 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10085 return res; 10086 } 10087 10088 @Override 10089 protected void sortResults(List<ResolveInfo> results) { 10090 Collections.sort(results, mResolvePrioritySorter); 10091 } 10092 10093 @Override 10094 protected void dumpFilter(PrintWriter out, String prefix, 10095 PackageParser.ServiceIntentInfo filter) { 10096 out.print(prefix); out.print( 10097 Integer.toHexString(System.identityHashCode(filter.service))); 10098 out.print(' '); 10099 filter.service.printComponentShortName(out); 10100 out.print(" filter "); 10101 out.println(Integer.toHexString(System.identityHashCode(filter))); 10102 } 10103 10104 @Override 10105 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10106 return filter.service; 10107 } 10108 10109 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10110 PackageParser.Service service = (PackageParser.Service)label; 10111 out.print(prefix); out.print( 10112 Integer.toHexString(System.identityHashCode(service))); 10113 out.print(' '); 10114 service.printComponentShortName(out); 10115 if (count > 1) { 10116 out.print(" ("); out.print(count); out.print(" filters)"); 10117 } 10118 out.println(); 10119 } 10120 10121// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10122// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10123// final List<ResolveInfo> retList = Lists.newArrayList(); 10124// while (i.hasNext()) { 10125// final ResolveInfo resolveInfo = (ResolveInfo) i; 10126// if (isEnabledLP(resolveInfo.serviceInfo)) { 10127// retList.add(resolveInfo); 10128// } 10129// } 10130// return retList; 10131// } 10132 10133 // Keys are String (activity class name), values are Activity. 10134 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10135 = new ArrayMap<ComponentName, PackageParser.Service>(); 10136 private int mFlags; 10137 }; 10138 10139 private final class ProviderIntentResolver 10140 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10141 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10142 boolean defaultOnly, int userId) { 10143 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10144 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10145 } 10146 10147 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10148 int userId) { 10149 if (!sUserManager.exists(userId)) 10150 return null; 10151 mFlags = flags; 10152 return super.queryIntent(intent, resolvedType, 10153 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10154 } 10155 10156 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10157 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10158 if (!sUserManager.exists(userId)) 10159 return null; 10160 if (packageProviders == null) { 10161 return null; 10162 } 10163 mFlags = flags; 10164 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10165 final int N = packageProviders.size(); 10166 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10167 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10168 10169 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10170 for (int i = 0; i < N; ++i) { 10171 intentFilters = packageProviders.get(i).intents; 10172 if (intentFilters != null && intentFilters.size() > 0) { 10173 PackageParser.ProviderIntentInfo[] array = 10174 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10175 intentFilters.toArray(array); 10176 listCut.add(array); 10177 } 10178 } 10179 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10180 } 10181 10182 public final void addProvider(PackageParser.Provider p) { 10183 if (mProviders.containsKey(p.getComponentName())) { 10184 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10185 return; 10186 } 10187 10188 mProviders.put(p.getComponentName(), p); 10189 if (DEBUG_SHOW_INFO) { 10190 Log.v(TAG, " " 10191 + (p.info.nonLocalizedLabel != null 10192 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10193 Log.v(TAG, " Class=" + p.info.name); 10194 } 10195 final int NI = p.intents.size(); 10196 int j; 10197 for (j = 0; j < NI; j++) { 10198 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10199 if (DEBUG_SHOW_INFO) { 10200 Log.v(TAG, " IntentFilter:"); 10201 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10202 } 10203 if (!intent.debugCheck()) { 10204 Log.w(TAG, "==> For Provider " + p.info.name); 10205 } 10206 addFilter(intent); 10207 } 10208 } 10209 10210 public final void removeProvider(PackageParser.Provider p) { 10211 mProviders.remove(p.getComponentName()); 10212 if (DEBUG_SHOW_INFO) { 10213 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10214 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10215 Log.v(TAG, " Class=" + p.info.name); 10216 } 10217 final int NI = p.intents.size(); 10218 int j; 10219 for (j = 0; j < NI; j++) { 10220 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10221 if (DEBUG_SHOW_INFO) { 10222 Log.v(TAG, " IntentFilter:"); 10223 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10224 } 10225 removeFilter(intent); 10226 } 10227 } 10228 10229 @Override 10230 protected boolean allowFilterResult( 10231 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10232 ProviderInfo filterPi = filter.provider.info; 10233 for (int i = dest.size() - 1; i >= 0; i--) { 10234 ProviderInfo destPi = dest.get(i).providerInfo; 10235 if (destPi.name == filterPi.name 10236 && destPi.packageName == filterPi.packageName) { 10237 return false; 10238 } 10239 } 10240 return true; 10241 } 10242 10243 @Override 10244 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10245 return new PackageParser.ProviderIntentInfo[size]; 10246 } 10247 10248 @Override 10249 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10250 if (!sUserManager.exists(userId)) 10251 return true; 10252 PackageParser.Package p = filter.provider.owner; 10253 if (p != null) { 10254 PackageSetting ps = (PackageSetting) p.mExtras; 10255 if (ps != null) { 10256 // System apps are never considered stopped for purposes of 10257 // filtering, because there may be no way for the user to 10258 // actually re-launch them. 10259 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10260 && ps.getStopped(userId); 10261 } 10262 } 10263 return false; 10264 } 10265 10266 @Override 10267 protected boolean isPackageForFilter(String packageName, 10268 PackageParser.ProviderIntentInfo info) { 10269 return packageName.equals(info.provider.owner.packageName); 10270 } 10271 10272 @Override 10273 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10274 int match, int userId) { 10275 if (!sUserManager.exists(userId)) 10276 return null; 10277 final PackageParser.ProviderIntentInfo info = filter; 10278 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10279 return null; 10280 } 10281 final PackageParser.Provider provider = info.provider; 10282 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10283 if (ps == null) { 10284 return null; 10285 } 10286 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10287 ps.readUserState(userId), userId); 10288 if (pi == null) { 10289 return null; 10290 } 10291 final ResolveInfo res = new ResolveInfo(); 10292 res.providerInfo = pi; 10293 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10294 res.filter = filter; 10295 } 10296 res.priority = info.getPriority(); 10297 res.preferredOrder = provider.owner.mPreferredOrder; 10298 res.match = match; 10299 res.isDefault = info.hasDefault; 10300 res.labelRes = info.labelRes; 10301 res.nonLocalizedLabel = info.nonLocalizedLabel; 10302 res.icon = info.icon; 10303 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10304 return res; 10305 } 10306 10307 @Override 10308 protected void sortResults(List<ResolveInfo> results) { 10309 Collections.sort(results, mResolvePrioritySorter); 10310 } 10311 10312 @Override 10313 protected void dumpFilter(PrintWriter out, String prefix, 10314 PackageParser.ProviderIntentInfo filter) { 10315 out.print(prefix); 10316 out.print( 10317 Integer.toHexString(System.identityHashCode(filter.provider))); 10318 out.print(' '); 10319 filter.provider.printComponentShortName(out); 10320 out.print(" filter "); 10321 out.println(Integer.toHexString(System.identityHashCode(filter))); 10322 } 10323 10324 @Override 10325 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 10326 return filter.provider; 10327 } 10328 10329 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10330 PackageParser.Provider provider = (PackageParser.Provider)label; 10331 out.print(prefix); out.print( 10332 Integer.toHexString(System.identityHashCode(provider))); 10333 out.print(' '); 10334 provider.printComponentShortName(out); 10335 if (count > 1) { 10336 out.print(" ("); out.print(count); out.print(" filters)"); 10337 } 10338 out.println(); 10339 } 10340 10341 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 10342 = new ArrayMap<ComponentName, PackageParser.Provider>(); 10343 private int mFlags; 10344 } 10345 10346 private static final class EphemeralIntentResolver 10347 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 10348 @Override 10349 protected EphemeralResolveIntentInfo[] newArray(int size) { 10350 return new EphemeralResolveIntentInfo[size]; 10351 } 10352 10353 @Override 10354 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 10355 return true; 10356 } 10357 10358 @Override 10359 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 10360 int userId) { 10361 if (!sUserManager.exists(userId)) { 10362 return null; 10363 } 10364 return info.getEphemeralResolveInfo(); 10365 } 10366 } 10367 10368 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 10369 new Comparator<ResolveInfo>() { 10370 public int compare(ResolveInfo r1, ResolveInfo r2) { 10371 int v1 = r1.priority; 10372 int v2 = r2.priority; 10373 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 10374 if (v1 != v2) { 10375 return (v1 > v2) ? -1 : 1; 10376 } 10377 v1 = r1.preferredOrder; 10378 v2 = r2.preferredOrder; 10379 if (v1 != v2) { 10380 return (v1 > v2) ? -1 : 1; 10381 } 10382 if (r1.isDefault != r2.isDefault) { 10383 return r1.isDefault ? -1 : 1; 10384 } 10385 v1 = r1.match; 10386 v2 = r2.match; 10387 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 10388 if (v1 != v2) { 10389 return (v1 > v2) ? -1 : 1; 10390 } 10391 if (r1.system != r2.system) { 10392 return r1.system ? -1 : 1; 10393 } 10394 if (r1.activityInfo != null) { 10395 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 10396 } 10397 if (r1.serviceInfo != null) { 10398 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 10399 } 10400 if (r1.providerInfo != null) { 10401 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 10402 } 10403 return 0; 10404 } 10405 }; 10406 10407 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 10408 new Comparator<ProviderInfo>() { 10409 public int compare(ProviderInfo p1, ProviderInfo p2) { 10410 final int v1 = p1.initOrder; 10411 final int v2 = p2.initOrder; 10412 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 10413 } 10414 }; 10415 10416 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 10417 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 10418 final int[] userIds) { 10419 mHandler.post(new Runnable() { 10420 @Override 10421 public void run() { 10422 try { 10423 final IActivityManager am = ActivityManagerNative.getDefault(); 10424 if (am == null) return; 10425 final int[] resolvedUserIds; 10426 if (userIds == null) { 10427 resolvedUserIds = am.getRunningUserIds(); 10428 } else { 10429 resolvedUserIds = userIds; 10430 } 10431 for (int id : resolvedUserIds) { 10432 final Intent intent = new Intent(action, 10433 pkg != null ? Uri.fromParts("package", pkg, null) : null); 10434 if (extras != null) { 10435 intent.putExtras(extras); 10436 } 10437 if (targetPkg != null) { 10438 intent.setPackage(targetPkg); 10439 } 10440 // Modify the UID when posting to other users 10441 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 10442 if (uid > 0 && UserHandle.getUserId(uid) != id) { 10443 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 10444 intent.putExtra(Intent.EXTRA_UID, uid); 10445 } 10446 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 10447 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 10448 if (DEBUG_BROADCASTS) { 10449 RuntimeException here = new RuntimeException("here"); 10450 here.fillInStackTrace(); 10451 Slog.d(TAG, "Sending to user " + id + ": " 10452 + intent.toShortString(false, true, false, false) 10453 + " " + intent.getExtras(), here); 10454 } 10455 am.broadcastIntent(null, intent, null, finishedReceiver, 10456 0, null, null, null, android.app.AppOpsManager.OP_NONE, 10457 null, finishedReceiver != null, false, id); 10458 } 10459 } catch (RemoteException ex) { 10460 } 10461 } 10462 }); 10463 } 10464 10465 /** 10466 * Check if the external storage media is available. This is true if there 10467 * is a mounted external storage medium or if the external storage is 10468 * emulated. 10469 */ 10470 private boolean isExternalMediaAvailable() { 10471 return mMediaMounted || Environment.isExternalStorageEmulated(); 10472 } 10473 10474 @Override 10475 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 10476 // writer 10477 synchronized (mPackages) { 10478 if (!isExternalMediaAvailable()) { 10479 // If the external storage is no longer mounted at this point, 10480 // the caller may not have been able to delete all of this 10481 // packages files and can not delete any more. Bail. 10482 return null; 10483 } 10484 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 10485 if (lastPackage != null) { 10486 pkgs.remove(lastPackage); 10487 } 10488 if (pkgs.size() > 0) { 10489 return pkgs.get(0); 10490 } 10491 } 10492 return null; 10493 } 10494 10495 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 10496 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 10497 userId, andCode ? 1 : 0, packageName); 10498 if (mSystemReady) { 10499 msg.sendToTarget(); 10500 } else { 10501 if (mPostSystemReadyMessages == null) { 10502 mPostSystemReadyMessages = new ArrayList<>(); 10503 } 10504 mPostSystemReadyMessages.add(msg); 10505 } 10506 } 10507 10508 void startCleaningPackages() { 10509 // reader 10510 if (!isExternalMediaAvailable()) { 10511 return; 10512 } 10513 synchronized (mPackages) { 10514 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 10515 return; 10516 } 10517 } 10518 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 10519 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 10520 IActivityManager am = ActivityManagerNative.getDefault(); 10521 if (am != null) { 10522 try { 10523 am.startService(null, intent, null, mContext.getOpPackageName(), 10524 UserHandle.USER_SYSTEM); 10525 } catch (RemoteException e) { 10526 } 10527 } 10528 } 10529 10530 @Override 10531 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 10532 int installFlags, String installerPackageName, int userId) { 10533 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 10534 10535 final int callingUid = Binder.getCallingUid(); 10536 enforceCrossUserPermission(callingUid, userId, 10537 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 10538 10539 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10540 try { 10541 if (observer != null) { 10542 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 10543 } 10544 } catch (RemoteException re) { 10545 } 10546 return; 10547 } 10548 10549 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 10550 installFlags |= PackageManager.INSTALL_FROM_ADB; 10551 10552 } else { 10553 // Caller holds INSTALL_PACKAGES permission, so we're less strict 10554 // about installerPackageName. 10555 10556 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 10557 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 10558 } 10559 10560 UserHandle user; 10561 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 10562 user = UserHandle.ALL; 10563 } else { 10564 user = new UserHandle(userId); 10565 } 10566 10567 // Only system components can circumvent runtime permissions when installing. 10568 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 10569 && mContext.checkCallingOrSelfPermission(Manifest.permission 10570 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 10571 throw new SecurityException("You need the " 10572 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 10573 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 10574 } 10575 10576 final File originFile = new File(originPath); 10577 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 10578 10579 final Message msg = mHandler.obtainMessage(INIT_COPY); 10580 final VerificationInfo verificationInfo = new VerificationInfo( 10581 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 10582 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 10583 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 10584 null /*packageAbiOverride*/, null /*grantedPermissions*/); 10585 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 10586 msg.obj = params; 10587 10588 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 10589 System.identityHashCode(msg.obj)); 10590 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10591 System.identityHashCode(msg.obj)); 10592 10593 mHandler.sendMessage(msg); 10594 } 10595 10596 void installStage(String packageName, File stagedDir, String stagedCid, 10597 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 10598 String installerPackageName, int installerUid, UserHandle user) { 10599 if (DEBUG_EPHEMERAL) { 10600 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10601 Slog.d(TAG, "Ephemeral install of " + packageName); 10602 } 10603 } 10604 final VerificationInfo verificationInfo = new VerificationInfo( 10605 sessionParams.originatingUri, sessionParams.referrerUri, 10606 sessionParams.originatingUid, installerUid); 10607 10608 final OriginInfo origin; 10609 if (stagedDir != null) { 10610 origin = OriginInfo.fromStagedFile(stagedDir); 10611 } else { 10612 origin = OriginInfo.fromStagedContainer(stagedCid); 10613 } 10614 10615 final Message msg = mHandler.obtainMessage(INIT_COPY); 10616 final InstallParams params = new InstallParams(origin, null, observer, 10617 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 10618 verificationInfo, user, sessionParams.abiOverride, 10619 sessionParams.grantedRuntimePermissions); 10620 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 10621 msg.obj = params; 10622 10623 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 10624 System.identityHashCode(msg.obj)); 10625 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10626 System.identityHashCode(msg.obj)); 10627 10628 mHandler.sendMessage(msg); 10629 } 10630 10631 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 10632 int userId) { 10633 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 10634 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 10635 } 10636 10637 private void sendPackageAddedForUser(String packageName, boolean isSystem, 10638 int appId, int userId) { 10639 Bundle extras = new Bundle(1); 10640 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 10641 10642 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 10643 packageName, extras, 0, null, null, new int[] {userId}); 10644 try { 10645 IActivityManager am = ActivityManagerNative.getDefault(); 10646 if (isSystem && am.isUserRunning(userId, 0)) { 10647 // The just-installed/enabled app is bundled on the system, so presumed 10648 // to be able to run automatically without needing an explicit launch. 10649 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 10650 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 10651 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 10652 .setPackage(packageName); 10653 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 10654 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 10655 } 10656 } catch (RemoteException e) { 10657 // shouldn't happen 10658 Slog.w(TAG, "Unable to bootstrap installed package", e); 10659 } 10660 } 10661 10662 @Override 10663 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 10664 int userId) { 10665 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10666 PackageSetting pkgSetting; 10667 final int uid = Binder.getCallingUid(); 10668 enforceCrossUserPermission(uid, userId, 10669 true /* requireFullPermission */, true /* checkShell */, 10670 "setApplicationHiddenSetting for user " + userId); 10671 10672 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 10673 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 10674 return false; 10675 } 10676 10677 long callingId = Binder.clearCallingIdentity(); 10678 try { 10679 boolean sendAdded = false; 10680 boolean sendRemoved = false; 10681 // writer 10682 synchronized (mPackages) { 10683 pkgSetting = mSettings.mPackages.get(packageName); 10684 if (pkgSetting == null) { 10685 return false; 10686 } 10687 if (pkgSetting.getHidden(userId) != hidden) { 10688 pkgSetting.setHidden(hidden, userId); 10689 mSettings.writePackageRestrictionsLPr(userId); 10690 if (hidden) { 10691 sendRemoved = true; 10692 } else { 10693 sendAdded = true; 10694 } 10695 } 10696 } 10697 if (sendAdded) { 10698 sendPackageAddedForUser(packageName, pkgSetting, userId); 10699 return true; 10700 } 10701 if (sendRemoved) { 10702 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 10703 "hiding pkg"); 10704 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 10705 return true; 10706 } 10707 } finally { 10708 Binder.restoreCallingIdentity(callingId); 10709 } 10710 return false; 10711 } 10712 10713 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 10714 int userId) { 10715 final PackageRemovedInfo info = new PackageRemovedInfo(); 10716 info.removedPackage = packageName; 10717 info.removedUsers = new int[] {userId}; 10718 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 10719 info.sendPackageRemovedBroadcasts(true /*killApp*/); 10720 } 10721 10722 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 10723 if (pkgList.length > 0) { 10724 Bundle extras = new Bundle(1); 10725 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 10726 10727 sendPackageBroadcast( 10728 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 10729 : Intent.ACTION_PACKAGES_UNSUSPENDED, 10730 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 10731 new int[] {userId}); 10732 } 10733 } 10734 10735 /** 10736 * Returns true if application is not found or there was an error. Otherwise it returns 10737 * the hidden state of the package for the given user. 10738 */ 10739 @Override 10740 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 10741 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10742 enforceCrossUserPermission(Binder.getCallingUid(), userId, 10743 true /* requireFullPermission */, false /* checkShell */, 10744 "getApplicationHidden for user " + userId); 10745 PackageSetting pkgSetting; 10746 long callingId = Binder.clearCallingIdentity(); 10747 try { 10748 // writer 10749 synchronized (mPackages) { 10750 pkgSetting = mSettings.mPackages.get(packageName); 10751 if (pkgSetting == null) { 10752 return true; 10753 } 10754 return pkgSetting.getHidden(userId); 10755 } 10756 } finally { 10757 Binder.restoreCallingIdentity(callingId); 10758 } 10759 } 10760 10761 /** 10762 * @hide 10763 */ 10764 @Override 10765 public int installExistingPackageAsUser(String packageName, int userId) { 10766 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 10767 null); 10768 PackageSetting pkgSetting; 10769 final int uid = Binder.getCallingUid(); 10770 enforceCrossUserPermission(uid, userId, 10771 true /* requireFullPermission */, true /* checkShell */, 10772 "installExistingPackage for user " + userId); 10773 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10774 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 10775 } 10776 10777 long callingId = Binder.clearCallingIdentity(); 10778 try { 10779 boolean installed = false; 10780 10781 // writer 10782 synchronized (mPackages) { 10783 pkgSetting = mSettings.mPackages.get(packageName); 10784 if (pkgSetting == null) { 10785 return PackageManager.INSTALL_FAILED_INVALID_URI; 10786 } 10787 if (!pkgSetting.getInstalled(userId)) { 10788 pkgSetting.setInstalled(true, userId); 10789 pkgSetting.setHidden(false, userId); 10790 mSettings.writePackageRestrictionsLPr(userId); 10791 installed = true; 10792 } 10793 } 10794 10795 if (installed) { 10796 if (pkgSetting.pkg != null) { 10797 prepareAppDataAfterInstall(pkgSetting.pkg); 10798 } 10799 sendPackageAddedForUser(packageName, pkgSetting, userId); 10800 } 10801 } finally { 10802 Binder.restoreCallingIdentity(callingId); 10803 } 10804 10805 return PackageManager.INSTALL_SUCCEEDED; 10806 } 10807 10808 boolean isUserRestricted(int userId, String restrictionKey) { 10809 Bundle restrictions = sUserManager.getUserRestrictions(userId); 10810 if (restrictions.getBoolean(restrictionKey, false)) { 10811 Log.w(TAG, "User is restricted: " + restrictionKey); 10812 return true; 10813 } 10814 return false; 10815 } 10816 10817 @Override 10818 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 10819 int userId) { 10820 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10821 enforceCrossUserPermission(Binder.getCallingUid(), userId, 10822 true /* requireFullPermission */, true /* checkShell */, 10823 "setPackagesSuspended for user " + userId); 10824 10825 if (ArrayUtils.isEmpty(packageNames)) { 10826 return packageNames; 10827 } 10828 10829 // List of package names for whom the suspended state has changed. 10830 List<String> changedPackages = new ArrayList<>(packageNames.length); 10831 // List of package names for whom the suspended state is not set as requested in this 10832 // method. 10833 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 10834 for (int i = 0; i < packageNames.length; i++) { 10835 String packageName = packageNames[i]; 10836 long callingId = Binder.clearCallingIdentity(); 10837 try { 10838 boolean changed = false; 10839 final int appId; 10840 synchronized (mPackages) { 10841 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10842 if (pkgSetting == null) { 10843 Slog.w(TAG, "Could not find package setting for package \"" + packageName 10844 + "\". Skipping suspending/un-suspending."); 10845 unactionedPackages.add(packageName); 10846 continue; 10847 } 10848 appId = pkgSetting.appId; 10849 if (pkgSetting.getSuspended(userId) != suspended) { 10850 if (!canSuspendPackageForUserLocked(packageName, userId)) { 10851 unactionedPackages.add(packageName); 10852 continue; 10853 } 10854 pkgSetting.setSuspended(suspended, userId); 10855 mSettings.writePackageRestrictionsLPr(userId); 10856 changed = true; 10857 changedPackages.add(packageName); 10858 } 10859 } 10860 10861 if (changed && suspended) { 10862 killApplication(packageName, UserHandle.getUid(userId, appId), 10863 "suspending package"); 10864 } 10865 } finally { 10866 Binder.restoreCallingIdentity(callingId); 10867 } 10868 } 10869 10870 if (!changedPackages.isEmpty()) { 10871 sendPackagesSuspendedForUser(changedPackages.toArray( 10872 new String[changedPackages.size()]), userId, suspended); 10873 } 10874 10875 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 10876 } 10877 10878 @Override 10879 public boolean isPackageSuspendedForUser(String packageName, int userId) { 10880 enforceCrossUserPermission(Binder.getCallingUid(), userId, 10881 true /* requireFullPermission */, false /* checkShell */, 10882 "isPackageSuspendedForUser for user " + userId); 10883 synchronized (mPackages) { 10884 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10885 return pkgSetting != null && pkgSetting.getSuspended(userId); 10886 } 10887 } 10888 10889 /** 10890 * TODO: cache and disallow blocking the active dialer. 10891 * 10892 * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions 10893 */ 10894 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 10895 if (isPackageDeviceAdmin(packageName, userId)) { 10896 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 10897 + "\": has an active device admin"); 10898 return false; 10899 } 10900 10901 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 10902 if (packageName.equals(activeLauncherPackageName)) { 10903 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 10904 + "\": contains the active launcher"); 10905 return false; 10906 } 10907 10908 if (packageName.equals(mRequiredInstallerPackage)) { 10909 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 10910 + "\": required for package installation"); 10911 return false; 10912 } 10913 10914 if (packageName.equals(mRequiredVerifierPackage)) { 10915 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 10916 + "\": required for package verification"); 10917 return false; 10918 } 10919 10920 final PackageParser.Package pkg = mPackages.get(packageName); 10921 if (pkg != null && isPrivilegedApp(pkg)) { 10922 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 10923 + "\": is a privileged app"); 10924 return false; 10925 } 10926 10927 return true; 10928 } 10929 10930 private String getActiveLauncherPackageName(int userId) { 10931 Intent intent = new Intent(Intent.ACTION_MAIN); 10932 intent.addCategory(Intent.CATEGORY_HOME); 10933 ResolveInfo resolveInfo = resolveIntent( 10934 intent, 10935 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 10936 PackageManager.MATCH_DEFAULT_ONLY, 10937 userId); 10938 10939 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 10940 } 10941 10942 @Override 10943 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 10944 mContext.enforceCallingOrSelfPermission( 10945 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10946 "Only package verification agents can verify applications"); 10947 10948 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10949 final PackageVerificationResponse response = new PackageVerificationResponse( 10950 verificationCode, Binder.getCallingUid()); 10951 msg.arg1 = id; 10952 msg.obj = response; 10953 mHandler.sendMessage(msg); 10954 } 10955 10956 @Override 10957 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 10958 long millisecondsToDelay) { 10959 mContext.enforceCallingOrSelfPermission( 10960 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10961 "Only package verification agents can extend verification timeouts"); 10962 10963 final PackageVerificationState state = mPendingVerification.get(id); 10964 final PackageVerificationResponse response = new PackageVerificationResponse( 10965 verificationCodeAtTimeout, Binder.getCallingUid()); 10966 10967 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 10968 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 10969 } 10970 if (millisecondsToDelay < 0) { 10971 millisecondsToDelay = 0; 10972 } 10973 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 10974 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 10975 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 10976 } 10977 10978 if ((state != null) && !state.timeoutExtended()) { 10979 state.extendTimeout(); 10980 10981 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10982 msg.arg1 = id; 10983 msg.obj = response; 10984 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 10985 } 10986 } 10987 10988 private void broadcastPackageVerified(int verificationId, Uri packageUri, 10989 int verificationCode, UserHandle user) { 10990 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 10991 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 10992 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10993 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10994 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 10995 10996 mContext.sendBroadcastAsUser(intent, user, 10997 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 10998 } 10999 11000 private ComponentName matchComponentForVerifier(String packageName, 11001 List<ResolveInfo> receivers) { 11002 ActivityInfo targetReceiver = null; 11003 11004 final int NR = receivers.size(); 11005 for (int i = 0; i < NR; i++) { 11006 final ResolveInfo info = receivers.get(i); 11007 if (info.activityInfo == null) { 11008 continue; 11009 } 11010 11011 if (packageName.equals(info.activityInfo.packageName)) { 11012 targetReceiver = info.activityInfo; 11013 break; 11014 } 11015 } 11016 11017 if (targetReceiver == null) { 11018 return null; 11019 } 11020 11021 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11022 } 11023 11024 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11025 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11026 if (pkgInfo.verifiers.length == 0) { 11027 return null; 11028 } 11029 11030 final int N = pkgInfo.verifiers.length; 11031 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11032 for (int i = 0; i < N; i++) { 11033 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11034 11035 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11036 receivers); 11037 if (comp == null) { 11038 continue; 11039 } 11040 11041 final int verifierUid = getUidForVerifier(verifierInfo); 11042 if (verifierUid == -1) { 11043 continue; 11044 } 11045 11046 if (DEBUG_VERIFY) { 11047 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11048 + " with the correct signature"); 11049 } 11050 sufficientVerifiers.add(comp); 11051 verificationState.addSufficientVerifier(verifierUid); 11052 } 11053 11054 return sufficientVerifiers; 11055 } 11056 11057 private int getUidForVerifier(VerifierInfo verifierInfo) { 11058 synchronized (mPackages) { 11059 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11060 if (pkg == null) { 11061 return -1; 11062 } else if (pkg.mSignatures.length != 1) { 11063 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11064 + " has more than one signature; ignoring"); 11065 return -1; 11066 } 11067 11068 /* 11069 * If the public key of the package's signature does not match 11070 * our expected public key, then this is a different package and 11071 * we should skip. 11072 */ 11073 11074 final byte[] expectedPublicKey; 11075 try { 11076 final Signature verifierSig = pkg.mSignatures[0]; 11077 final PublicKey publicKey = verifierSig.getPublicKey(); 11078 expectedPublicKey = publicKey.getEncoded(); 11079 } catch (CertificateException e) { 11080 return -1; 11081 } 11082 11083 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11084 11085 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11086 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11087 + " does not have the expected public key; ignoring"); 11088 return -1; 11089 } 11090 11091 return pkg.applicationInfo.uid; 11092 } 11093 } 11094 11095 @Override 11096 public void finishPackageInstall(int token) { 11097 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11098 11099 if (DEBUG_INSTALL) { 11100 Slog.v(TAG, "BM finishing package install for " + token); 11101 } 11102 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11103 11104 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11105 mHandler.sendMessage(msg); 11106 } 11107 11108 /** 11109 * Get the verification agent timeout. 11110 * 11111 * @return verification timeout in milliseconds 11112 */ 11113 private long getVerificationTimeout() { 11114 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11115 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11116 DEFAULT_VERIFICATION_TIMEOUT); 11117 } 11118 11119 /** 11120 * Get the default verification agent response code. 11121 * 11122 * @return default verification response code 11123 */ 11124 private int getDefaultVerificationResponse() { 11125 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11126 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11127 DEFAULT_VERIFICATION_RESPONSE); 11128 } 11129 11130 /** 11131 * Check whether or not package verification has been enabled. 11132 * 11133 * @return true if verification should be performed 11134 */ 11135 private boolean isVerificationEnabled(int userId, int installFlags) { 11136 if (!DEFAULT_VERIFY_ENABLE) { 11137 return false; 11138 } 11139 // Ephemeral apps don't get the full verification treatment 11140 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11141 if (DEBUG_EPHEMERAL) { 11142 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11143 } 11144 return false; 11145 } 11146 11147 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11148 11149 // Check if installing from ADB 11150 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11151 // Do not run verification in a test harness environment 11152 if (ActivityManager.isRunningInTestHarness()) { 11153 return false; 11154 } 11155 if (ensureVerifyAppsEnabled) { 11156 return true; 11157 } 11158 // Check if the developer does not want package verification for ADB installs 11159 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11160 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11161 return false; 11162 } 11163 } 11164 11165 if (ensureVerifyAppsEnabled) { 11166 return true; 11167 } 11168 11169 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11170 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11171 } 11172 11173 @Override 11174 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11175 throws RemoteException { 11176 mContext.enforceCallingOrSelfPermission( 11177 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11178 "Only intentfilter verification agents can verify applications"); 11179 11180 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11181 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11182 Binder.getCallingUid(), verificationCode, failedDomains); 11183 msg.arg1 = id; 11184 msg.obj = response; 11185 mHandler.sendMessage(msg); 11186 } 11187 11188 @Override 11189 public int getIntentVerificationStatus(String packageName, int userId) { 11190 synchronized (mPackages) { 11191 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11192 } 11193 } 11194 11195 @Override 11196 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11197 mContext.enforceCallingOrSelfPermission( 11198 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11199 11200 boolean result = false; 11201 synchronized (mPackages) { 11202 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11203 } 11204 if (result) { 11205 scheduleWritePackageRestrictionsLocked(userId); 11206 } 11207 return result; 11208 } 11209 11210 @Override 11211 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11212 String packageName) { 11213 synchronized (mPackages) { 11214 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11215 } 11216 } 11217 11218 @Override 11219 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11220 if (TextUtils.isEmpty(packageName)) { 11221 return ParceledListSlice.emptyList(); 11222 } 11223 synchronized (mPackages) { 11224 PackageParser.Package pkg = mPackages.get(packageName); 11225 if (pkg == null || pkg.activities == null) { 11226 return ParceledListSlice.emptyList(); 11227 } 11228 final int count = pkg.activities.size(); 11229 ArrayList<IntentFilter> result = new ArrayList<>(); 11230 for (int n=0; n<count; n++) { 11231 PackageParser.Activity activity = pkg.activities.get(n); 11232 if (activity.intents != null && activity.intents.size() > 0) { 11233 result.addAll(activity.intents); 11234 } 11235 } 11236 return new ParceledListSlice<>(result); 11237 } 11238 } 11239 11240 @Override 11241 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11242 mContext.enforceCallingOrSelfPermission( 11243 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11244 11245 synchronized (mPackages) { 11246 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11247 if (packageName != null) { 11248 result |= updateIntentVerificationStatus(packageName, 11249 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11250 userId); 11251 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11252 packageName, userId); 11253 } 11254 return result; 11255 } 11256 } 11257 11258 @Override 11259 public String getDefaultBrowserPackageName(int userId) { 11260 synchronized (mPackages) { 11261 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11262 } 11263 } 11264 11265 /** 11266 * Get the "allow unknown sources" setting. 11267 * 11268 * @return the current "allow unknown sources" setting 11269 */ 11270 private int getUnknownSourcesSettings() { 11271 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11272 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 11273 -1); 11274 } 11275 11276 @Override 11277 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11278 final int uid = Binder.getCallingUid(); 11279 // writer 11280 synchronized (mPackages) { 11281 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11282 if (targetPackageSetting == null) { 11283 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11284 } 11285 11286 PackageSetting installerPackageSetting; 11287 if (installerPackageName != null) { 11288 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11289 if (installerPackageSetting == null) { 11290 throw new IllegalArgumentException("Unknown installer package: " 11291 + installerPackageName); 11292 } 11293 } else { 11294 installerPackageSetting = null; 11295 } 11296 11297 Signature[] callerSignature; 11298 Object obj = mSettings.getUserIdLPr(uid); 11299 if (obj != null) { 11300 if (obj instanceof SharedUserSetting) { 11301 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11302 } else if (obj instanceof PackageSetting) { 11303 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11304 } else { 11305 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11306 } 11307 } else { 11308 throw new SecurityException("Unknown calling UID: " + uid); 11309 } 11310 11311 // Verify: can't set installerPackageName to a package that is 11312 // not signed with the same cert as the caller. 11313 if (installerPackageSetting != null) { 11314 if (compareSignatures(callerSignature, 11315 installerPackageSetting.signatures.mSignatures) 11316 != PackageManager.SIGNATURE_MATCH) { 11317 throw new SecurityException( 11318 "Caller does not have same cert as new installer package " 11319 + installerPackageName); 11320 } 11321 } 11322 11323 // Verify: if target already has an installer package, it must 11324 // be signed with the same cert as the caller. 11325 if (targetPackageSetting.installerPackageName != null) { 11326 PackageSetting setting = mSettings.mPackages.get( 11327 targetPackageSetting.installerPackageName); 11328 // If the currently set package isn't valid, then it's always 11329 // okay to change it. 11330 if (setting != null) { 11331 if (compareSignatures(callerSignature, 11332 setting.signatures.mSignatures) 11333 != PackageManager.SIGNATURE_MATCH) { 11334 throw new SecurityException( 11335 "Caller does not have same cert as old installer package " 11336 + targetPackageSetting.installerPackageName); 11337 } 11338 } 11339 } 11340 11341 // Okay! 11342 targetPackageSetting.installerPackageName = installerPackageName; 11343 scheduleWriteSettingsLocked(); 11344 } 11345 } 11346 11347 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 11348 // Queue up an async operation since the package installation may take a little while. 11349 mHandler.post(new Runnable() { 11350 public void run() { 11351 mHandler.removeCallbacks(this); 11352 // Result object to be returned 11353 PackageInstalledInfo res = new PackageInstalledInfo(); 11354 res.setReturnCode(currentStatus); 11355 res.uid = -1; 11356 res.pkg = null; 11357 res.removedInfo = null; 11358 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11359 args.doPreInstall(res.returnCode); 11360 synchronized (mInstallLock) { 11361 installPackageTracedLI(args, res); 11362 } 11363 args.doPostInstall(res.returnCode, res.uid); 11364 } 11365 11366 // A restore should be performed at this point if (a) the install 11367 // succeeded, (b) the operation is not an update, and (c) the new 11368 // package has not opted out of backup participation. 11369 final boolean update = res.removedInfo != null 11370 && res.removedInfo.removedPackage != null; 11371 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 11372 boolean doRestore = !update 11373 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 11374 11375 // Set up the post-install work request bookkeeping. This will be used 11376 // and cleaned up by the post-install event handling regardless of whether 11377 // there's a restore pass performed. Token values are >= 1. 11378 int token; 11379 if (mNextInstallToken < 0) mNextInstallToken = 1; 11380 token = mNextInstallToken++; 11381 11382 PostInstallData data = new PostInstallData(args, res); 11383 mRunningInstalls.put(token, data); 11384 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 11385 11386 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 11387 // Pass responsibility to the Backup Manager. It will perform a 11388 // restore if appropriate, then pass responsibility back to the 11389 // Package Manager to run the post-install observer callbacks 11390 // and broadcasts. 11391 IBackupManager bm = IBackupManager.Stub.asInterface( 11392 ServiceManager.getService(Context.BACKUP_SERVICE)); 11393 if (bm != null) { 11394 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 11395 + " to BM for possible restore"); 11396 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11397 try { 11398 // TODO: http://b/22388012 11399 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 11400 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 11401 } else { 11402 doRestore = false; 11403 } 11404 } catch (RemoteException e) { 11405 // can't happen; the backup manager is local 11406 } catch (Exception e) { 11407 Slog.e(TAG, "Exception trying to enqueue restore", e); 11408 doRestore = false; 11409 } 11410 } else { 11411 Slog.e(TAG, "Backup Manager not found!"); 11412 doRestore = false; 11413 } 11414 } 11415 11416 if (!doRestore) { 11417 // No restore possible, or the Backup Manager was mysteriously not 11418 // available -- just fire the post-install work request directly. 11419 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 11420 11421 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 11422 11423 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11424 mHandler.sendMessage(msg); 11425 } 11426 } 11427 }); 11428 } 11429 11430 private abstract class HandlerParams { 11431 private static final int MAX_RETRIES = 4; 11432 11433 /** 11434 * Number of times startCopy() has been attempted and had a non-fatal 11435 * error. 11436 */ 11437 private int mRetries = 0; 11438 11439 /** User handle for the user requesting the information or installation. */ 11440 private final UserHandle mUser; 11441 String traceMethod; 11442 int traceCookie; 11443 11444 HandlerParams(UserHandle user) { 11445 mUser = user; 11446 } 11447 11448 UserHandle getUser() { 11449 return mUser; 11450 } 11451 11452 HandlerParams setTraceMethod(String traceMethod) { 11453 this.traceMethod = traceMethod; 11454 return this; 11455 } 11456 11457 HandlerParams setTraceCookie(int traceCookie) { 11458 this.traceCookie = traceCookie; 11459 return this; 11460 } 11461 11462 final boolean startCopy() { 11463 boolean res; 11464 try { 11465 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 11466 11467 if (++mRetries > MAX_RETRIES) { 11468 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 11469 mHandler.sendEmptyMessage(MCS_GIVE_UP); 11470 handleServiceError(); 11471 return false; 11472 } else { 11473 handleStartCopy(); 11474 res = true; 11475 } 11476 } catch (RemoteException e) { 11477 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 11478 mHandler.sendEmptyMessage(MCS_RECONNECT); 11479 res = false; 11480 } 11481 handleReturnCode(); 11482 return res; 11483 } 11484 11485 final void serviceError() { 11486 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 11487 handleServiceError(); 11488 handleReturnCode(); 11489 } 11490 11491 abstract void handleStartCopy() throws RemoteException; 11492 abstract void handleServiceError(); 11493 abstract void handleReturnCode(); 11494 } 11495 11496 class MeasureParams extends HandlerParams { 11497 private final PackageStats mStats; 11498 private boolean mSuccess; 11499 11500 private final IPackageStatsObserver mObserver; 11501 11502 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 11503 super(new UserHandle(stats.userHandle)); 11504 mObserver = observer; 11505 mStats = stats; 11506 } 11507 11508 @Override 11509 public String toString() { 11510 return "MeasureParams{" 11511 + Integer.toHexString(System.identityHashCode(this)) 11512 + " " + mStats.packageName + "}"; 11513 } 11514 11515 @Override 11516 void handleStartCopy() throws RemoteException { 11517 synchronized (mInstallLock) { 11518 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 11519 } 11520 11521 if (mSuccess) { 11522 final boolean mounted; 11523 if (Environment.isExternalStorageEmulated()) { 11524 mounted = true; 11525 } else { 11526 final String status = Environment.getExternalStorageState(); 11527 mounted = (Environment.MEDIA_MOUNTED.equals(status) 11528 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 11529 } 11530 11531 if (mounted) { 11532 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 11533 11534 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 11535 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 11536 11537 mStats.externalDataSize = calculateDirectorySize(mContainerService, 11538 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 11539 11540 // Always subtract cache size, since it's a subdirectory 11541 mStats.externalDataSize -= mStats.externalCacheSize; 11542 11543 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 11544 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 11545 11546 mStats.externalObbSize = calculateDirectorySize(mContainerService, 11547 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 11548 } 11549 } 11550 } 11551 11552 @Override 11553 void handleReturnCode() { 11554 if (mObserver != null) { 11555 try { 11556 mObserver.onGetStatsCompleted(mStats, mSuccess); 11557 } catch (RemoteException e) { 11558 Slog.i(TAG, "Observer no longer exists."); 11559 } 11560 } 11561 } 11562 11563 @Override 11564 void handleServiceError() { 11565 Slog.e(TAG, "Could not measure application " + mStats.packageName 11566 + " external storage"); 11567 } 11568 } 11569 11570 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 11571 throws RemoteException { 11572 long result = 0; 11573 for (File path : paths) { 11574 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 11575 } 11576 return result; 11577 } 11578 11579 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 11580 for (File path : paths) { 11581 try { 11582 mcs.clearDirectory(path.getAbsolutePath()); 11583 } catch (RemoteException e) { 11584 } 11585 } 11586 } 11587 11588 static class OriginInfo { 11589 /** 11590 * Location where install is coming from, before it has been 11591 * copied/renamed into place. This could be a single monolithic APK 11592 * file, or a cluster directory. This location may be untrusted. 11593 */ 11594 final File file; 11595 final String cid; 11596 11597 /** 11598 * Flag indicating that {@link #file} or {@link #cid} has already been 11599 * staged, meaning downstream users don't need to defensively copy the 11600 * contents. 11601 */ 11602 final boolean staged; 11603 11604 /** 11605 * Flag indicating that {@link #file} or {@link #cid} is an already 11606 * installed app that is being moved. 11607 */ 11608 final boolean existing; 11609 11610 final String resolvedPath; 11611 final File resolvedFile; 11612 11613 static OriginInfo fromNothing() { 11614 return new OriginInfo(null, null, false, false); 11615 } 11616 11617 static OriginInfo fromUntrustedFile(File file) { 11618 return new OriginInfo(file, null, false, false); 11619 } 11620 11621 static OriginInfo fromExistingFile(File file) { 11622 return new OriginInfo(file, null, false, true); 11623 } 11624 11625 static OriginInfo fromStagedFile(File file) { 11626 return new OriginInfo(file, null, true, false); 11627 } 11628 11629 static OriginInfo fromStagedContainer(String cid) { 11630 return new OriginInfo(null, cid, true, false); 11631 } 11632 11633 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 11634 this.file = file; 11635 this.cid = cid; 11636 this.staged = staged; 11637 this.existing = existing; 11638 11639 if (cid != null) { 11640 resolvedPath = PackageHelper.getSdDir(cid); 11641 resolvedFile = new File(resolvedPath); 11642 } else if (file != null) { 11643 resolvedPath = file.getAbsolutePath(); 11644 resolvedFile = file; 11645 } else { 11646 resolvedPath = null; 11647 resolvedFile = null; 11648 } 11649 } 11650 } 11651 11652 static class MoveInfo { 11653 final int moveId; 11654 final String fromUuid; 11655 final String toUuid; 11656 final String packageName; 11657 final String dataAppName; 11658 final int appId; 11659 final String seinfo; 11660 final int targetSdkVersion; 11661 11662 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 11663 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 11664 this.moveId = moveId; 11665 this.fromUuid = fromUuid; 11666 this.toUuid = toUuid; 11667 this.packageName = packageName; 11668 this.dataAppName = dataAppName; 11669 this.appId = appId; 11670 this.seinfo = seinfo; 11671 this.targetSdkVersion = targetSdkVersion; 11672 } 11673 } 11674 11675 static class VerificationInfo { 11676 /** A constant used to indicate that a uid value is not present. */ 11677 public static final int NO_UID = -1; 11678 11679 /** URI referencing where the package was downloaded from. */ 11680 final Uri originatingUri; 11681 11682 /** HTTP referrer URI associated with the originatingURI. */ 11683 final Uri referrer; 11684 11685 /** UID of the application that the install request originated from. */ 11686 final int originatingUid; 11687 11688 /** UID of application requesting the install */ 11689 final int installerUid; 11690 11691 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 11692 this.originatingUri = originatingUri; 11693 this.referrer = referrer; 11694 this.originatingUid = originatingUid; 11695 this.installerUid = installerUid; 11696 } 11697 } 11698 11699 class InstallParams extends HandlerParams { 11700 final OriginInfo origin; 11701 final MoveInfo move; 11702 final IPackageInstallObserver2 observer; 11703 int installFlags; 11704 final String installerPackageName; 11705 final String volumeUuid; 11706 private InstallArgs mArgs; 11707 private int mRet; 11708 final String packageAbiOverride; 11709 final String[] grantedRuntimePermissions; 11710 final VerificationInfo verificationInfo; 11711 11712 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11713 int installFlags, String installerPackageName, String volumeUuid, 11714 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 11715 String[] grantedPermissions) { 11716 super(user); 11717 this.origin = origin; 11718 this.move = move; 11719 this.observer = observer; 11720 this.installFlags = installFlags; 11721 this.installerPackageName = installerPackageName; 11722 this.volumeUuid = volumeUuid; 11723 this.verificationInfo = verificationInfo; 11724 this.packageAbiOverride = packageAbiOverride; 11725 this.grantedRuntimePermissions = grantedPermissions; 11726 } 11727 11728 @Override 11729 public String toString() { 11730 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 11731 + " file=" + origin.file + " cid=" + origin.cid + "}"; 11732 } 11733 11734 private int installLocationPolicy(PackageInfoLite pkgLite) { 11735 String packageName = pkgLite.packageName; 11736 int installLocation = pkgLite.installLocation; 11737 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11738 // reader 11739 synchronized (mPackages) { 11740 // Currently installed package which the new package is attempting to replace or 11741 // null if no such package is installed. 11742 PackageParser.Package installedPkg = mPackages.get(packageName); 11743 // Package which currently owns the data which the new package will own if installed. 11744 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 11745 // will be null whereas dataOwnerPkg will contain information about the package 11746 // which was uninstalled while keeping its data. 11747 PackageParser.Package dataOwnerPkg = installedPkg; 11748 if (dataOwnerPkg == null) { 11749 PackageSetting ps = mSettings.mPackages.get(packageName); 11750 if (ps != null) { 11751 dataOwnerPkg = ps.pkg; 11752 } 11753 } 11754 11755 if (dataOwnerPkg != null) { 11756 // If installed, the package will get access to data left on the device by its 11757 // predecessor. As a security measure, this is permited only if this is not a 11758 // version downgrade or if the predecessor package is marked as debuggable and 11759 // a downgrade is explicitly requested. 11760 if (((dataOwnerPkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) 11761 || ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0)) { 11762 try { 11763 checkDowngrade(dataOwnerPkg, pkgLite); 11764 } catch (PackageManagerException e) { 11765 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 11766 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 11767 } 11768 } 11769 } 11770 11771 if (installedPkg != null) { 11772 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11773 // Check for updated system application. 11774 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11775 if (onSd) { 11776 Slog.w(TAG, "Cannot install update to system app on sdcard"); 11777 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 11778 } 11779 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11780 } else { 11781 if (onSd) { 11782 // Install flag overrides everything. 11783 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11784 } 11785 // If current upgrade specifies particular preference 11786 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 11787 // Application explicitly specified internal. 11788 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11789 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 11790 // App explictly prefers external. Let policy decide 11791 } else { 11792 // Prefer previous location 11793 if (isExternal(installedPkg)) { 11794 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11795 } 11796 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11797 } 11798 } 11799 } else { 11800 // Invalid install. Return error code 11801 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 11802 } 11803 } 11804 } 11805 // All the special cases have been taken care of. 11806 // Return result based on recommended install location. 11807 if (onSd) { 11808 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11809 } 11810 return pkgLite.recommendedInstallLocation; 11811 } 11812 11813 /* 11814 * Invoke remote method to get package information and install 11815 * location values. Override install location based on default 11816 * policy if needed and then create install arguments based 11817 * on the install location. 11818 */ 11819 public void handleStartCopy() throws RemoteException { 11820 int ret = PackageManager.INSTALL_SUCCEEDED; 11821 11822 // If we're already staged, we've firmly committed to an install location 11823 if (origin.staged) { 11824 if (origin.file != null) { 11825 installFlags |= PackageManager.INSTALL_INTERNAL; 11826 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11827 } else if (origin.cid != null) { 11828 installFlags |= PackageManager.INSTALL_EXTERNAL; 11829 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11830 } else { 11831 throw new IllegalStateException("Invalid stage location"); 11832 } 11833 } 11834 11835 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11836 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 11837 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11838 PackageInfoLite pkgLite = null; 11839 11840 if (onInt && onSd) { 11841 // Check if both bits are set. 11842 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 11843 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11844 } else if (onSd && ephemeral) { 11845 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 11846 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11847 } else { 11848 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 11849 packageAbiOverride); 11850 11851 if (DEBUG_EPHEMERAL && ephemeral) { 11852 Slog.v(TAG, "pkgLite for install: " + pkgLite); 11853 } 11854 11855 /* 11856 * If we have too little free space, try to free cache 11857 * before giving up. 11858 */ 11859 if (!origin.staged && pkgLite.recommendedInstallLocation 11860 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11861 // TODO: focus freeing disk space on the target device 11862 final StorageManager storage = StorageManager.from(mContext); 11863 final long lowThreshold = storage.getStorageLowBytes( 11864 Environment.getDataDirectory()); 11865 11866 final long sizeBytes = mContainerService.calculateInstalledSize( 11867 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 11868 11869 try { 11870 mInstaller.freeCache(null, sizeBytes + lowThreshold); 11871 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 11872 installFlags, packageAbiOverride); 11873 } catch (InstallerException e) { 11874 Slog.w(TAG, "Failed to free cache", e); 11875 } 11876 11877 /* 11878 * The cache free must have deleted the file we 11879 * downloaded to install. 11880 * 11881 * TODO: fix the "freeCache" call to not delete 11882 * the file we care about. 11883 */ 11884 if (pkgLite.recommendedInstallLocation 11885 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11886 pkgLite.recommendedInstallLocation 11887 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 11888 } 11889 } 11890 } 11891 11892 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11893 int loc = pkgLite.recommendedInstallLocation; 11894 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 11895 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11896 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 11897 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 11898 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11899 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11900 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 11901 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 11902 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11903 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 11904 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 11905 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 11906 } else { 11907 // Override with defaults if needed. 11908 loc = installLocationPolicy(pkgLite); 11909 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 11910 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 11911 } else if (!onSd && !onInt) { 11912 // Override install location with flags 11913 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 11914 // Set the flag to install on external media. 11915 installFlags |= PackageManager.INSTALL_EXTERNAL; 11916 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11917 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 11918 if (DEBUG_EPHEMERAL) { 11919 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 11920 } 11921 installFlags |= PackageManager.INSTALL_EPHEMERAL; 11922 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 11923 |PackageManager.INSTALL_INTERNAL); 11924 } else { 11925 // Make sure the flag for installing on external 11926 // media is unset 11927 installFlags |= PackageManager.INSTALL_INTERNAL; 11928 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11929 } 11930 } 11931 } 11932 } 11933 11934 final InstallArgs args = createInstallArgs(this); 11935 mArgs = args; 11936 11937 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11938 // TODO: http://b/22976637 11939 // Apps installed for "all" users use the device owner to verify the app 11940 UserHandle verifierUser = getUser(); 11941 if (verifierUser == UserHandle.ALL) { 11942 verifierUser = UserHandle.SYSTEM; 11943 } 11944 11945 /* 11946 * Determine if we have any installed package verifiers. If we 11947 * do, then we'll defer to them to verify the packages. 11948 */ 11949 final int requiredUid = mRequiredVerifierPackage == null ? -1 11950 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 11951 verifierUser.getIdentifier()); 11952 if (!origin.existing && requiredUid != -1 11953 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 11954 final Intent verification = new Intent( 11955 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 11956 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 11957 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 11958 PACKAGE_MIME_TYPE); 11959 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11960 11961 // Query all live verifiers based on current user state 11962 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 11963 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 11964 11965 if (DEBUG_VERIFY) { 11966 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 11967 + verification.toString() + " with " + pkgLite.verifiers.length 11968 + " optional verifiers"); 11969 } 11970 11971 final int verificationId = mPendingVerificationToken++; 11972 11973 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11974 11975 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 11976 installerPackageName); 11977 11978 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 11979 installFlags); 11980 11981 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 11982 pkgLite.packageName); 11983 11984 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 11985 pkgLite.versionCode); 11986 11987 if (verificationInfo != null) { 11988 if (verificationInfo.originatingUri != null) { 11989 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 11990 verificationInfo.originatingUri); 11991 } 11992 if (verificationInfo.referrer != null) { 11993 verification.putExtra(Intent.EXTRA_REFERRER, 11994 verificationInfo.referrer); 11995 } 11996 if (verificationInfo.originatingUid >= 0) { 11997 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 11998 verificationInfo.originatingUid); 11999 } 12000 if (verificationInfo.installerUid >= 0) { 12001 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12002 verificationInfo.installerUid); 12003 } 12004 } 12005 12006 final PackageVerificationState verificationState = new PackageVerificationState( 12007 requiredUid, args); 12008 12009 mPendingVerification.append(verificationId, verificationState); 12010 12011 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12012 receivers, verificationState); 12013 12014 /* 12015 * If any sufficient verifiers were listed in the package 12016 * manifest, attempt to ask them. 12017 */ 12018 if (sufficientVerifiers != null) { 12019 final int N = sufficientVerifiers.size(); 12020 if (N == 0) { 12021 Slog.i(TAG, "Additional verifiers required, but none installed."); 12022 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12023 } else { 12024 for (int i = 0; i < N; i++) { 12025 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12026 12027 final Intent sufficientIntent = new Intent(verification); 12028 sufficientIntent.setComponent(verifierComponent); 12029 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12030 } 12031 } 12032 } 12033 12034 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12035 mRequiredVerifierPackage, receivers); 12036 if (ret == PackageManager.INSTALL_SUCCEEDED 12037 && mRequiredVerifierPackage != null) { 12038 Trace.asyncTraceBegin( 12039 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12040 /* 12041 * Send the intent to the required verification agent, 12042 * but only start the verification timeout after the 12043 * target BroadcastReceivers have run. 12044 */ 12045 verification.setComponent(requiredVerifierComponent); 12046 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12047 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12048 new BroadcastReceiver() { 12049 @Override 12050 public void onReceive(Context context, Intent intent) { 12051 final Message msg = mHandler 12052 .obtainMessage(CHECK_PENDING_VERIFICATION); 12053 msg.arg1 = verificationId; 12054 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12055 } 12056 }, null, 0, null, null); 12057 12058 /* 12059 * We don't want the copy to proceed until verification 12060 * succeeds, so null out this field. 12061 */ 12062 mArgs = null; 12063 } 12064 } else { 12065 /* 12066 * No package verification is enabled, so immediately start 12067 * the remote call to initiate copy using temporary file. 12068 */ 12069 ret = args.copyApk(mContainerService, true); 12070 } 12071 } 12072 12073 mRet = ret; 12074 } 12075 12076 @Override 12077 void handleReturnCode() { 12078 // If mArgs is null, then MCS couldn't be reached. When it 12079 // reconnects, it will try again to install. At that point, this 12080 // will succeed. 12081 if (mArgs != null) { 12082 processPendingInstall(mArgs, mRet); 12083 } 12084 } 12085 12086 @Override 12087 void handleServiceError() { 12088 mArgs = createInstallArgs(this); 12089 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12090 } 12091 12092 public boolean isForwardLocked() { 12093 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12094 } 12095 } 12096 12097 /** 12098 * Used during creation of InstallArgs 12099 * 12100 * @param installFlags package installation flags 12101 * @return true if should be installed on external storage 12102 */ 12103 private static boolean installOnExternalAsec(int installFlags) { 12104 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12105 return false; 12106 } 12107 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12108 return true; 12109 } 12110 return false; 12111 } 12112 12113 /** 12114 * Used during creation of InstallArgs 12115 * 12116 * @param installFlags package installation flags 12117 * @return true if should be installed as forward locked 12118 */ 12119 private static boolean installForwardLocked(int installFlags) { 12120 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12121 } 12122 12123 private InstallArgs createInstallArgs(InstallParams params) { 12124 if (params.move != null) { 12125 return new MoveInstallArgs(params); 12126 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12127 return new AsecInstallArgs(params); 12128 } else { 12129 return new FileInstallArgs(params); 12130 } 12131 } 12132 12133 /** 12134 * Create args that describe an existing installed package. Typically used 12135 * when cleaning up old installs, or used as a move source. 12136 */ 12137 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12138 String resourcePath, String[] instructionSets) { 12139 final boolean isInAsec; 12140 if (installOnExternalAsec(installFlags)) { 12141 /* Apps on SD card are always in ASEC containers. */ 12142 isInAsec = true; 12143 } else if (installForwardLocked(installFlags) 12144 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12145 /* 12146 * Forward-locked apps are only in ASEC containers if they're the 12147 * new style 12148 */ 12149 isInAsec = true; 12150 } else { 12151 isInAsec = false; 12152 } 12153 12154 if (isInAsec) { 12155 return new AsecInstallArgs(codePath, instructionSets, 12156 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12157 } else { 12158 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12159 } 12160 } 12161 12162 static abstract class InstallArgs { 12163 /** @see InstallParams#origin */ 12164 final OriginInfo origin; 12165 /** @see InstallParams#move */ 12166 final MoveInfo move; 12167 12168 final IPackageInstallObserver2 observer; 12169 // Always refers to PackageManager flags only 12170 final int installFlags; 12171 final String installerPackageName; 12172 final String volumeUuid; 12173 final UserHandle user; 12174 final String abiOverride; 12175 final String[] installGrantPermissions; 12176 /** If non-null, drop an async trace when the install completes */ 12177 final String traceMethod; 12178 final int traceCookie; 12179 12180 // The list of instruction sets supported by this app. This is currently 12181 // only used during the rmdex() phase to clean up resources. We can get rid of this 12182 // if we move dex files under the common app path. 12183 /* nullable */ String[] instructionSets; 12184 12185 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12186 int installFlags, String installerPackageName, String volumeUuid, 12187 UserHandle user, String[] instructionSets, 12188 String abiOverride, String[] installGrantPermissions, 12189 String traceMethod, int traceCookie) { 12190 this.origin = origin; 12191 this.move = move; 12192 this.installFlags = installFlags; 12193 this.observer = observer; 12194 this.installerPackageName = installerPackageName; 12195 this.volumeUuid = volumeUuid; 12196 this.user = user; 12197 this.instructionSets = instructionSets; 12198 this.abiOverride = abiOverride; 12199 this.installGrantPermissions = installGrantPermissions; 12200 this.traceMethod = traceMethod; 12201 this.traceCookie = traceCookie; 12202 } 12203 12204 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12205 abstract int doPreInstall(int status); 12206 12207 /** 12208 * Rename package into final resting place. All paths on the given 12209 * scanned package should be updated to reflect the rename. 12210 */ 12211 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12212 abstract int doPostInstall(int status, int uid); 12213 12214 /** @see PackageSettingBase#codePathString */ 12215 abstract String getCodePath(); 12216 /** @see PackageSettingBase#resourcePathString */ 12217 abstract String getResourcePath(); 12218 12219 // Need installer lock especially for dex file removal. 12220 abstract void cleanUpResourcesLI(); 12221 abstract boolean doPostDeleteLI(boolean delete); 12222 12223 /** 12224 * Called before the source arguments are copied. This is used mostly 12225 * for MoveParams when it needs to read the source file to put it in the 12226 * destination. 12227 */ 12228 int doPreCopy() { 12229 return PackageManager.INSTALL_SUCCEEDED; 12230 } 12231 12232 /** 12233 * Called after the source arguments are copied. This is used mostly for 12234 * MoveParams when it needs to read the source file to put it in the 12235 * destination. 12236 * 12237 * @return 12238 */ 12239 int doPostCopy(int uid) { 12240 return PackageManager.INSTALL_SUCCEEDED; 12241 } 12242 12243 protected boolean isFwdLocked() { 12244 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12245 } 12246 12247 protected boolean isExternalAsec() { 12248 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12249 } 12250 12251 protected boolean isEphemeral() { 12252 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12253 } 12254 12255 UserHandle getUser() { 12256 return user; 12257 } 12258 } 12259 12260 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 12261 if (!allCodePaths.isEmpty()) { 12262 if (instructionSets == null) { 12263 throw new IllegalStateException("instructionSet == null"); 12264 } 12265 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 12266 for (String codePath : allCodePaths) { 12267 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 12268 try { 12269 mInstaller.rmdex(codePath, dexCodeInstructionSet); 12270 } catch (InstallerException ignored) { 12271 } 12272 } 12273 } 12274 } 12275 } 12276 12277 /** 12278 * Logic to handle installation of non-ASEC applications, including copying 12279 * and renaming logic. 12280 */ 12281 class FileInstallArgs extends InstallArgs { 12282 private File codeFile; 12283 private File resourceFile; 12284 12285 // Example topology: 12286 // /data/app/com.example/base.apk 12287 // /data/app/com.example/split_foo.apk 12288 // /data/app/com.example/lib/arm/libfoo.so 12289 // /data/app/com.example/lib/arm64/libfoo.so 12290 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 12291 12292 /** New install */ 12293 FileInstallArgs(InstallParams params) { 12294 super(params.origin, params.move, params.observer, params.installFlags, 12295 params.installerPackageName, params.volumeUuid, 12296 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12297 params.grantedRuntimePermissions, 12298 params.traceMethod, params.traceCookie); 12299 if (isFwdLocked()) { 12300 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 12301 } 12302 } 12303 12304 /** Existing install */ 12305 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 12306 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 12307 null, null, null, 0); 12308 this.codeFile = (codePath != null) ? new File(codePath) : null; 12309 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 12310 } 12311 12312 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12313 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 12314 try { 12315 return doCopyApk(imcs, temp); 12316 } finally { 12317 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12318 } 12319 } 12320 12321 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12322 if (origin.staged) { 12323 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 12324 codeFile = origin.file; 12325 resourceFile = origin.file; 12326 return PackageManager.INSTALL_SUCCEEDED; 12327 } 12328 12329 try { 12330 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12331 final File tempDir = 12332 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 12333 codeFile = tempDir; 12334 resourceFile = tempDir; 12335 } catch (IOException e) { 12336 Slog.w(TAG, "Failed to create copy file: " + e); 12337 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12338 } 12339 12340 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 12341 @Override 12342 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 12343 if (!FileUtils.isValidExtFilename(name)) { 12344 throw new IllegalArgumentException("Invalid filename: " + name); 12345 } 12346 try { 12347 final File file = new File(codeFile, name); 12348 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 12349 O_RDWR | O_CREAT, 0644); 12350 Os.chmod(file.getAbsolutePath(), 0644); 12351 return new ParcelFileDescriptor(fd); 12352 } catch (ErrnoException e) { 12353 throw new RemoteException("Failed to open: " + e.getMessage()); 12354 } 12355 } 12356 }; 12357 12358 int ret = PackageManager.INSTALL_SUCCEEDED; 12359 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 12360 if (ret != PackageManager.INSTALL_SUCCEEDED) { 12361 Slog.e(TAG, "Failed to copy package"); 12362 return ret; 12363 } 12364 12365 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 12366 NativeLibraryHelper.Handle handle = null; 12367 try { 12368 handle = NativeLibraryHelper.Handle.create(codeFile); 12369 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 12370 abiOverride); 12371 } catch (IOException e) { 12372 Slog.e(TAG, "Copying native libraries failed", e); 12373 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12374 } finally { 12375 IoUtils.closeQuietly(handle); 12376 } 12377 12378 return ret; 12379 } 12380 12381 int doPreInstall(int status) { 12382 if (status != PackageManager.INSTALL_SUCCEEDED) { 12383 cleanUp(); 12384 } 12385 return status; 12386 } 12387 12388 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12389 if (status != PackageManager.INSTALL_SUCCEEDED) { 12390 cleanUp(); 12391 return false; 12392 } 12393 12394 final File targetDir = codeFile.getParentFile(); 12395 final File beforeCodeFile = codeFile; 12396 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 12397 12398 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 12399 try { 12400 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 12401 } catch (ErrnoException e) { 12402 Slog.w(TAG, "Failed to rename", e); 12403 return false; 12404 } 12405 12406 if (!SELinux.restoreconRecursive(afterCodeFile)) { 12407 Slog.w(TAG, "Failed to restorecon"); 12408 return false; 12409 } 12410 12411 // Reflect the rename internally 12412 codeFile = afterCodeFile; 12413 resourceFile = afterCodeFile; 12414 12415 // Reflect the rename in scanned details 12416 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12417 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12418 afterCodeFile, pkg.baseCodePath)); 12419 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12420 afterCodeFile, pkg.splitCodePaths)); 12421 12422 // Reflect the rename in app info 12423 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12424 pkg.setApplicationInfoCodePath(pkg.codePath); 12425 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12426 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12427 pkg.setApplicationInfoResourcePath(pkg.codePath); 12428 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12429 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12430 12431 return true; 12432 } 12433 12434 int doPostInstall(int status, int uid) { 12435 if (status != PackageManager.INSTALL_SUCCEEDED) { 12436 cleanUp(); 12437 } 12438 return status; 12439 } 12440 12441 @Override 12442 String getCodePath() { 12443 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12444 } 12445 12446 @Override 12447 String getResourcePath() { 12448 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12449 } 12450 12451 private boolean cleanUp() { 12452 if (codeFile == null || !codeFile.exists()) { 12453 return false; 12454 } 12455 12456 removeCodePathLI(codeFile); 12457 12458 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 12459 resourceFile.delete(); 12460 } 12461 12462 return true; 12463 } 12464 12465 void cleanUpResourcesLI() { 12466 // Try enumerating all code paths before deleting 12467 List<String> allCodePaths = Collections.EMPTY_LIST; 12468 if (codeFile != null && codeFile.exists()) { 12469 try { 12470 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12471 allCodePaths = pkg.getAllCodePaths(); 12472 } catch (PackageParserException e) { 12473 // Ignored; we tried our best 12474 } 12475 } 12476 12477 cleanUp(); 12478 removeDexFiles(allCodePaths, instructionSets); 12479 } 12480 12481 boolean doPostDeleteLI(boolean delete) { 12482 // XXX err, shouldn't we respect the delete flag? 12483 cleanUpResourcesLI(); 12484 return true; 12485 } 12486 } 12487 12488 private boolean isAsecExternal(String cid) { 12489 final String asecPath = PackageHelper.getSdFilesystem(cid); 12490 return !asecPath.startsWith(mAsecInternalPath); 12491 } 12492 12493 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 12494 PackageManagerException { 12495 if (copyRet < 0) { 12496 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 12497 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 12498 throw new PackageManagerException(copyRet, message); 12499 } 12500 } 12501 } 12502 12503 /** 12504 * Extract the MountService "container ID" from the full code path of an 12505 * .apk. 12506 */ 12507 static String cidFromCodePath(String fullCodePath) { 12508 int eidx = fullCodePath.lastIndexOf("/"); 12509 String subStr1 = fullCodePath.substring(0, eidx); 12510 int sidx = subStr1.lastIndexOf("/"); 12511 return subStr1.substring(sidx+1, eidx); 12512 } 12513 12514 /** 12515 * Logic to handle installation of ASEC applications, including copying and 12516 * renaming logic. 12517 */ 12518 class AsecInstallArgs extends InstallArgs { 12519 static final String RES_FILE_NAME = "pkg.apk"; 12520 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 12521 12522 String cid; 12523 String packagePath; 12524 String resourcePath; 12525 12526 /** New install */ 12527 AsecInstallArgs(InstallParams params) { 12528 super(params.origin, params.move, params.observer, params.installFlags, 12529 params.installerPackageName, params.volumeUuid, 12530 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12531 params.grantedRuntimePermissions, 12532 params.traceMethod, params.traceCookie); 12533 } 12534 12535 /** Existing install */ 12536 AsecInstallArgs(String fullCodePath, String[] instructionSets, 12537 boolean isExternal, boolean isForwardLocked) { 12538 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 12539 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12540 instructionSets, null, null, null, 0); 12541 // Hackily pretend we're still looking at a full code path 12542 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 12543 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 12544 } 12545 12546 // Extract cid from fullCodePath 12547 int eidx = fullCodePath.lastIndexOf("/"); 12548 String subStr1 = fullCodePath.substring(0, eidx); 12549 int sidx = subStr1.lastIndexOf("/"); 12550 cid = subStr1.substring(sidx+1, eidx); 12551 setMountPath(subStr1); 12552 } 12553 12554 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 12555 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 12556 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12557 instructionSets, null, null, null, 0); 12558 this.cid = cid; 12559 setMountPath(PackageHelper.getSdDir(cid)); 12560 } 12561 12562 void createCopyFile() { 12563 cid = mInstallerService.allocateExternalStageCidLegacy(); 12564 } 12565 12566 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12567 if (origin.staged && origin.cid != null) { 12568 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 12569 cid = origin.cid; 12570 setMountPath(PackageHelper.getSdDir(cid)); 12571 return PackageManager.INSTALL_SUCCEEDED; 12572 } 12573 12574 if (temp) { 12575 createCopyFile(); 12576 } else { 12577 /* 12578 * Pre-emptively destroy the container since it's destroyed if 12579 * copying fails due to it existing anyway. 12580 */ 12581 PackageHelper.destroySdDir(cid); 12582 } 12583 12584 final String newMountPath = imcs.copyPackageToContainer( 12585 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 12586 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 12587 12588 if (newMountPath != null) { 12589 setMountPath(newMountPath); 12590 return PackageManager.INSTALL_SUCCEEDED; 12591 } else { 12592 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12593 } 12594 } 12595 12596 @Override 12597 String getCodePath() { 12598 return packagePath; 12599 } 12600 12601 @Override 12602 String getResourcePath() { 12603 return resourcePath; 12604 } 12605 12606 int doPreInstall(int status) { 12607 if (status != PackageManager.INSTALL_SUCCEEDED) { 12608 // Destroy container 12609 PackageHelper.destroySdDir(cid); 12610 } else { 12611 boolean mounted = PackageHelper.isContainerMounted(cid); 12612 if (!mounted) { 12613 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 12614 Process.SYSTEM_UID); 12615 if (newMountPath != null) { 12616 setMountPath(newMountPath); 12617 } else { 12618 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12619 } 12620 } 12621 } 12622 return status; 12623 } 12624 12625 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12626 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 12627 String newMountPath = null; 12628 if (PackageHelper.isContainerMounted(cid)) { 12629 // Unmount the container 12630 if (!PackageHelper.unMountSdDir(cid)) { 12631 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 12632 return false; 12633 } 12634 } 12635 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 12636 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 12637 " which might be stale. Will try to clean up."); 12638 // Clean up the stale container and proceed to recreate. 12639 if (!PackageHelper.destroySdDir(newCacheId)) { 12640 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 12641 return false; 12642 } 12643 // Successfully cleaned up stale container. Try to rename again. 12644 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 12645 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 12646 + " inspite of cleaning it up."); 12647 return false; 12648 } 12649 } 12650 if (!PackageHelper.isContainerMounted(newCacheId)) { 12651 Slog.w(TAG, "Mounting container " + newCacheId); 12652 newMountPath = PackageHelper.mountSdDir(newCacheId, 12653 getEncryptKey(), Process.SYSTEM_UID); 12654 } else { 12655 newMountPath = PackageHelper.getSdDir(newCacheId); 12656 } 12657 if (newMountPath == null) { 12658 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 12659 return false; 12660 } 12661 Log.i(TAG, "Succesfully renamed " + cid + 12662 " to " + newCacheId + 12663 " at new path: " + newMountPath); 12664 cid = newCacheId; 12665 12666 final File beforeCodeFile = new File(packagePath); 12667 setMountPath(newMountPath); 12668 final File afterCodeFile = new File(packagePath); 12669 12670 // Reflect the rename in scanned details 12671 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12672 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12673 afterCodeFile, pkg.baseCodePath)); 12674 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12675 afterCodeFile, pkg.splitCodePaths)); 12676 12677 // Reflect the rename in app info 12678 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12679 pkg.setApplicationInfoCodePath(pkg.codePath); 12680 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12681 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12682 pkg.setApplicationInfoResourcePath(pkg.codePath); 12683 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12684 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12685 12686 return true; 12687 } 12688 12689 private void setMountPath(String mountPath) { 12690 final File mountFile = new File(mountPath); 12691 12692 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 12693 if (monolithicFile.exists()) { 12694 packagePath = monolithicFile.getAbsolutePath(); 12695 if (isFwdLocked()) { 12696 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 12697 } else { 12698 resourcePath = packagePath; 12699 } 12700 } else { 12701 packagePath = mountFile.getAbsolutePath(); 12702 resourcePath = packagePath; 12703 } 12704 } 12705 12706 int doPostInstall(int status, int uid) { 12707 if (status != PackageManager.INSTALL_SUCCEEDED) { 12708 cleanUp(); 12709 } else { 12710 final int groupOwner; 12711 final String protectedFile; 12712 if (isFwdLocked()) { 12713 groupOwner = UserHandle.getSharedAppGid(uid); 12714 protectedFile = RES_FILE_NAME; 12715 } else { 12716 groupOwner = -1; 12717 protectedFile = null; 12718 } 12719 12720 if (uid < Process.FIRST_APPLICATION_UID 12721 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 12722 Slog.e(TAG, "Failed to finalize " + cid); 12723 PackageHelper.destroySdDir(cid); 12724 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12725 } 12726 12727 boolean mounted = PackageHelper.isContainerMounted(cid); 12728 if (!mounted) { 12729 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 12730 } 12731 } 12732 return status; 12733 } 12734 12735 private void cleanUp() { 12736 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 12737 12738 // Destroy secure container 12739 PackageHelper.destroySdDir(cid); 12740 } 12741 12742 private List<String> getAllCodePaths() { 12743 final File codeFile = new File(getCodePath()); 12744 if (codeFile != null && codeFile.exists()) { 12745 try { 12746 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12747 return pkg.getAllCodePaths(); 12748 } catch (PackageParserException e) { 12749 // Ignored; we tried our best 12750 } 12751 } 12752 return Collections.EMPTY_LIST; 12753 } 12754 12755 void cleanUpResourcesLI() { 12756 // Enumerate all code paths before deleting 12757 cleanUpResourcesLI(getAllCodePaths()); 12758 } 12759 12760 private void cleanUpResourcesLI(List<String> allCodePaths) { 12761 cleanUp(); 12762 removeDexFiles(allCodePaths, instructionSets); 12763 } 12764 12765 String getPackageName() { 12766 return getAsecPackageName(cid); 12767 } 12768 12769 boolean doPostDeleteLI(boolean delete) { 12770 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 12771 final List<String> allCodePaths = getAllCodePaths(); 12772 boolean mounted = PackageHelper.isContainerMounted(cid); 12773 if (mounted) { 12774 // Unmount first 12775 if (PackageHelper.unMountSdDir(cid)) { 12776 mounted = false; 12777 } 12778 } 12779 if (!mounted && delete) { 12780 cleanUpResourcesLI(allCodePaths); 12781 } 12782 return !mounted; 12783 } 12784 12785 @Override 12786 int doPreCopy() { 12787 if (isFwdLocked()) { 12788 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 12789 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 12790 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12791 } 12792 } 12793 12794 return PackageManager.INSTALL_SUCCEEDED; 12795 } 12796 12797 @Override 12798 int doPostCopy(int uid) { 12799 if (isFwdLocked()) { 12800 if (uid < Process.FIRST_APPLICATION_UID 12801 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 12802 RES_FILE_NAME)) { 12803 Slog.e(TAG, "Failed to finalize " + cid); 12804 PackageHelper.destroySdDir(cid); 12805 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12806 } 12807 } 12808 12809 return PackageManager.INSTALL_SUCCEEDED; 12810 } 12811 } 12812 12813 /** 12814 * Logic to handle movement of existing installed applications. 12815 */ 12816 class MoveInstallArgs extends InstallArgs { 12817 private File codeFile; 12818 private File resourceFile; 12819 12820 /** New install */ 12821 MoveInstallArgs(InstallParams params) { 12822 super(params.origin, params.move, params.observer, params.installFlags, 12823 params.installerPackageName, params.volumeUuid, 12824 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12825 params.grantedRuntimePermissions, 12826 params.traceMethod, params.traceCookie); 12827 } 12828 12829 int copyApk(IMediaContainerService imcs, boolean temp) { 12830 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 12831 + move.fromUuid + " to " + move.toUuid); 12832 synchronized (mInstaller) { 12833 try { 12834 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 12835 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 12836 } catch (InstallerException e) { 12837 Slog.w(TAG, "Failed to move app", e); 12838 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12839 } 12840 } 12841 12842 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 12843 resourceFile = codeFile; 12844 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 12845 12846 return PackageManager.INSTALL_SUCCEEDED; 12847 } 12848 12849 int doPreInstall(int status) { 12850 if (status != PackageManager.INSTALL_SUCCEEDED) { 12851 cleanUp(move.toUuid); 12852 } 12853 return status; 12854 } 12855 12856 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12857 if (status != PackageManager.INSTALL_SUCCEEDED) { 12858 cleanUp(move.toUuid); 12859 return false; 12860 } 12861 12862 // Reflect the move in app info 12863 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12864 pkg.setApplicationInfoCodePath(pkg.codePath); 12865 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12866 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12867 pkg.setApplicationInfoResourcePath(pkg.codePath); 12868 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12869 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12870 12871 return true; 12872 } 12873 12874 int doPostInstall(int status, int uid) { 12875 if (status == PackageManager.INSTALL_SUCCEEDED) { 12876 cleanUp(move.fromUuid); 12877 } else { 12878 cleanUp(move.toUuid); 12879 } 12880 return status; 12881 } 12882 12883 @Override 12884 String getCodePath() { 12885 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12886 } 12887 12888 @Override 12889 String getResourcePath() { 12890 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12891 } 12892 12893 private boolean cleanUp(String volumeUuid) { 12894 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 12895 move.dataAppName); 12896 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 12897 synchronized (mInstallLock) { 12898 // Clean up both app data and code 12899 removeDataDirsLI(volumeUuid, move.packageName); 12900 removeCodePathLI(codeFile); 12901 } 12902 return true; 12903 } 12904 12905 void cleanUpResourcesLI() { 12906 throw new UnsupportedOperationException(); 12907 } 12908 12909 boolean doPostDeleteLI(boolean delete) { 12910 throw new UnsupportedOperationException(); 12911 } 12912 } 12913 12914 static String getAsecPackageName(String packageCid) { 12915 int idx = packageCid.lastIndexOf("-"); 12916 if (idx == -1) { 12917 return packageCid; 12918 } 12919 return packageCid.substring(0, idx); 12920 } 12921 12922 // Utility method used to create code paths based on package name and available index. 12923 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 12924 String idxStr = ""; 12925 int idx = 1; 12926 // Fall back to default value of idx=1 if prefix is not 12927 // part of oldCodePath 12928 if (oldCodePath != null) { 12929 String subStr = oldCodePath; 12930 // Drop the suffix right away 12931 if (suffix != null && subStr.endsWith(suffix)) { 12932 subStr = subStr.substring(0, subStr.length() - suffix.length()); 12933 } 12934 // If oldCodePath already contains prefix find out the 12935 // ending index to either increment or decrement. 12936 int sidx = subStr.lastIndexOf(prefix); 12937 if (sidx != -1) { 12938 subStr = subStr.substring(sidx + prefix.length()); 12939 if (subStr != null) { 12940 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 12941 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 12942 } 12943 try { 12944 idx = Integer.parseInt(subStr); 12945 if (idx <= 1) { 12946 idx++; 12947 } else { 12948 idx--; 12949 } 12950 } catch(NumberFormatException e) { 12951 } 12952 } 12953 } 12954 } 12955 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 12956 return prefix + idxStr; 12957 } 12958 12959 private File getNextCodePath(File targetDir, String packageName) { 12960 int suffix = 1; 12961 File result; 12962 do { 12963 result = new File(targetDir, packageName + "-" + suffix); 12964 suffix++; 12965 } while (result.exists()); 12966 return result; 12967 } 12968 12969 // Utility method that returns the relative package path with respect 12970 // to the installation directory. Like say for /data/data/com.test-1.apk 12971 // string com.test-1 is returned. 12972 static String deriveCodePathName(String codePath) { 12973 if (codePath == null) { 12974 return null; 12975 } 12976 final File codeFile = new File(codePath); 12977 final String name = codeFile.getName(); 12978 if (codeFile.isDirectory()) { 12979 return name; 12980 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 12981 final int lastDot = name.lastIndexOf('.'); 12982 return name.substring(0, lastDot); 12983 } else { 12984 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 12985 return null; 12986 } 12987 } 12988 12989 static class PackageInstalledInfo { 12990 String name; 12991 int uid; 12992 // The set of users that originally had this package installed. 12993 int[] origUsers; 12994 // The set of users that now have this package installed. 12995 int[] newUsers; 12996 PackageParser.Package pkg; 12997 int returnCode; 12998 String returnMsg; 12999 PackageRemovedInfo removedInfo; 13000 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13001 13002 public void setError(int code, String msg) { 13003 setReturnCode(code); 13004 setReturnMessage(msg); 13005 Slog.w(TAG, msg); 13006 } 13007 13008 public void setError(String msg, PackageParserException e) { 13009 setReturnCode(e.error); 13010 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13011 Slog.w(TAG, msg, e); 13012 } 13013 13014 public void setError(String msg, PackageManagerException e) { 13015 returnCode = e.error; 13016 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13017 Slog.w(TAG, msg, e); 13018 } 13019 13020 public void setReturnCode(int returnCode) { 13021 this.returnCode = returnCode; 13022 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13023 for (int i = 0; i < childCount; i++) { 13024 addedChildPackages.valueAt(i).returnCode = returnCode; 13025 } 13026 } 13027 13028 private void setReturnMessage(String returnMsg) { 13029 this.returnMsg = returnMsg; 13030 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13031 for (int i = 0; i < childCount; i++) { 13032 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13033 } 13034 } 13035 13036 // In some error cases we want to convey more info back to the observer 13037 String origPackage; 13038 String origPermission; 13039 } 13040 13041 /* 13042 * Install a non-existing package. 13043 */ 13044 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 13045 UserHandle user, String installerPackageName, String volumeUuid, 13046 PackageInstalledInfo res) { 13047 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13048 13049 // Remember this for later, in case we need to rollback this install 13050 String pkgName = pkg.packageName; 13051 13052 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13053 13054 synchronized(mPackages) { 13055 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13056 // A package with the same name is already installed, though 13057 // it has been renamed to an older name. The package we 13058 // are trying to install should be installed as an update to 13059 // the existing one, but that has not been requested, so bail. 13060 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13061 + " without first uninstalling package running as " 13062 + mSettings.mRenamedPackages.get(pkgName)); 13063 return; 13064 } 13065 if (mPackages.containsKey(pkgName)) { 13066 // Don't allow installation over an existing package with the same name. 13067 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13068 + " without first uninstalling."); 13069 return; 13070 } 13071 } 13072 13073 try { 13074 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 13075 System.currentTimeMillis(), user); 13076 13077 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13078 13079 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13080 prepareAppDataAfterInstall(newPackage); 13081 13082 } else { 13083 // Remove package from internal structures, but keep around any 13084 // data that might have already existed 13085 deletePackageLI(pkgName, UserHandle.ALL, false, null, 13086 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13087 } 13088 } catch (PackageManagerException e) { 13089 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13090 } 13091 13092 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13093 } 13094 13095 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13096 // Can't rotate keys during boot or if sharedUser. 13097 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13098 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13099 return false; 13100 } 13101 // app is using upgradeKeySets; make sure all are valid 13102 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13103 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13104 for (int i = 0; i < upgradeKeySets.length; i++) { 13105 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13106 Slog.wtf(TAG, "Package " 13107 + (oldPs.name != null ? oldPs.name : "<null>") 13108 + " contains upgrade-key-set reference to unknown key-set: " 13109 + upgradeKeySets[i] 13110 + " reverting to signatures check."); 13111 return false; 13112 } 13113 } 13114 return true; 13115 } 13116 13117 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13118 // Upgrade keysets are being used. Determine if new package has a superset of the 13119 // required keys. 13120 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13121 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13122 for (int i = 0; i < upgradeKeySets.length; i++) { 13123 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13124 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13125 return true; 13126 } 13127 } 13128 return false; 13129 } 13130 13131 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 13132 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13133 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13134 13135 final PackageParser.Package oldPackage; 13136 final String pkgName = pkg.packageName; 13137 final int[] allUsers; 13138 final boolean weFroze; 13139 13140 // First find the old package info and check signatures 13141 synchronized(mPackages) { 13142 oldPackage = mPackages.get(pkgName); 13143 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13144 if (isEphemeral && !oldIsEphemeral) { 13145 // can't downgrade from full to ephemeral 13146 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13147 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13148 return; 13149 } 13150 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13151 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13152 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13153 if (!checkUpgradeKeySetLP(ps, pkg)) { 13154 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13155 "New package not signed by keys specified by upgrade-keysets: " 13156 + pkgName); 13157 return; 13158 } 13159 } else { 13160 // default to original signature matching 13161 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13162 != PackageManager.SIGNATURE_MATCH) { 13163 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13164 "New package has a different signature: " + pkgName); 13165 return; 13166 } 13167 } 13168 13169 // In case of rollback, remember per-user/profile install state 13170 allUsers = sUserManager.getUserIds(); 13171 13172 // Mark the app as frozen to prevent launching during the upgrade 13173 // process, and then kill all running instances 13174 if (!ps.frozen) { 13175 ps.frozen = true; 13176 weFroze = true; 13177 } else { 13178 weFroze = false; 13179 } 13180 } 13181 13182 try { 13183 replacePackageDirtyLI(pkg, oldPackage, parseFlags, scanFlags, user, allUsers, 13184 installerPackageName, res); 13185 } finally { 13186 // Regardless of success or failure of upgrade steps above, always 13187 // unfreeze the package if we froze it 13188 if (weFroze) { 13189 unfreezePackage(pkgName); 13190 } 13191 } 13192 } 13193 13194 private void replacePackageDirtyLI(PackageParser.Package pkg, PackageParser.Package oldPackage, 13195 int parseFlags, int scanFlags, UserHandle user, int[] allUsers, 13196 String installerPackageName, PackageInstalledInfo res) { 13197 // Update what is removed 13198 res.removedInfo = new PackageRemovedInfo(); 13199 res.removedInfo.uid = oldPackage.applicationInfo.uid; 13200 res.removedInfo.removedPackage = oldPackage.packageName; 13201 res.removedInfo.isUpdate = true; 13202 final int childCount = (oldPackage.childPackages != null) 13203 ? oldPackage.childPackages.size() : 0; 13204 for (int i = 0; i < childCount; i++) { 13205 boolean childPackageUpdated = false; 13206 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 13207 if (res.addedChildPackages != null) { 13208 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13209 if (childRes != null) { 13210 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 13211 childRes.removedInfo.removedPackage = childPkg.packageName; 13212 childRes.removedInfo.isUpdate = true; 13213 childPackageUpdated = true; 13214 } 13215 } 13216 if (!childPackageUpdated) { 13217 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 13218 childRemovedRes.removedPackage = childPkg.packageName; 13219 childRemovedRes.isUpdate = false; 13220 childRemovedRes.dataRemoved = true; 13221 synchronized (mPackages) { 13222 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13223 if (childPs != null) { 13224 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 13225 } 13226 } 13227 if (res.removedInfo.removedChildPackages == null) { 13228 res.removedInfo.removedChildPackages = new ArrayMap<>(); 13229 } 13230 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 13231 } 13232 } 13233 13234 boolean sysPkg = (isSystemApp(oldPackage)); 13235 if (sysPkg) { 13236 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 13237 user, allUsers, installerPackageName, res); 13238 } else { 13239 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 13240 user, allUsers, installerPackageName, res); 13241 } 13242 } 13243 13244 public List<String> getPreviousCodePaths(String packageName) { 13245 final PackageSetting ps = mSettings.mPackages.get(packageName); 13246 final List<String> result = new ArrayList<String>(); 13247 if (ps != null && ps.oldCodePaths != null) { 13248 result.addAll(ps.oldCodePaths); 13249 } 13250 return result; 13251 } 13252 13253 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 13254 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13255 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13256 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 13257 + deletedPackage); 13258 13259 String pkgName = deletedPackage.packageName; 13260 boolean deletedPkg = true; 13261 boolean addedPkg = false; 13262 boolean updatedSettings = false; 13263 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 13264 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 13265 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 13266 13267 final long origUpdateTime = (pkg.mExtras != null) 13268 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 13269 13270 // First delete the existing package while retaining the data directory 13271 if (!deletePackageLI(pkgName, null, true, allUsers, deleteFlags, 13272 res.removedInfo, true, pkg)) { 13273 // If the existing package wasn't successfully deleted 13274 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 13275 deletedPkg = false; 13276 } else { 13277 // Successfully deleted the old package; proceed with replace. 13278 13279 // If deleted package lived in a container, give users a chance to 13280 // relinquish resources before killing. 13281 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 13282 if (DEBUG_INSTALL) { 13283 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 13284 } 13285 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 13286 final ArrayList<String> pkgList = new ArrayList<String>(1); 13287 pkgList.add(deletedPackage.applicationInfo.packageName); 13288 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 13289 } 13290 13291 deleteCodeCacheDirsLI(pkg); 13292 deleteProfilesLI(pkg, /*destroy*/ false); 13293 13294 try { 13295 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 13296 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 13297 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13298 13299 // Update the in-memory copy of the previous code paths. 13300 PackageSetting ps = mSettings.mPackages.get(pkgName); 13301 if (!killApp) { 13302 if (ps.oldCodePaths == null) { 13303 ps.oldCodePaths = new ArraySet<>(); 13304 } 13305 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 13306 if (deletedPackage.splitCodePaths != null) { 13307 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 13308 } 13309 } else { 13310 ps.oldCodePaths = null; 13311 } 13312 if (ps.childPackageNames != null) { 13313 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 13314 final String childPkgName = ps.childPackageNames.get(i); 13315 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 13316 childPs.oldCodePaths = ps.oldCodePaths; 13317 } 13318 } 13319 prepareAppDataAfterInstall(newPackage); 13320 addedPkg = true; 13321 } catch (PackageManagerException e) { 13322 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13323 } 13324 } 13325 13326 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13327 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 13328 13329 // Revert all internal state mutations and added folders for the failed install 13330 if (addedPkg) { 13331 deletePackageLI(pkgName, null, true, allUsers, deleteFlags, 13332 res.removedInfo, true, null); 13333 } 13334 13335 // Restore the old package 13336 if (deletedPkg) { 13337 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 13338 File restoreFile = new File(deletedPackage.codePath); 13339 // Parse old package 13340 boolean oldExternal = isExternal(deletedPackage); 13341 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 13342 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 13343 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 13344 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 13345 try { 13346 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 13347 null); 13348 } catch (PackageManagerException e) { 13349 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 13350 + e.getMessage()); 13351 return; 13352 } 13353 13354 synchronized (mPackages) { 13355 // Ensure the installer package name up to date 13356 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13357 13358 // Update permissions for restored package 13359 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13360 13361 mSettings.writeLPr(); 13362 } 13363 13364 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 13365 } 13366 } else { 13367 synchronized (mPackages) { 13368 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 13369 if (ps != null) { 13370 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 13371 if (res.removedInfo.removedChildPackages != null) { 13372 final int childCount = res.removedInfo.removedChildPackages.size(); 13373 // Iterate in reverse as we may modify the collection 13374 for (int i = childCount - 1; i >= 0; i--) { 13375 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 13376 if (res.addedChildPackages.containsKey(childPackageName)) { 13377 res.removedInfo.removedChildPackages.removeAt(i); 13378 } else { 13379 PackageRemovedInfo childInfo = res.removedInfo 13380 .removedChildPackages.valueAt(i); 13381 childInfo.removedForAllUsers = mPackages.get( 13382 childInfo.removedPackage) == null; 13383 } 13384 } 13385 } 13386 } 13387 } 13388 } 13389 } 13390 13391 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 13392 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13393 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13394 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 13395 + ", old=" + deletedPackage); 13396 13397 final boolean disabledSystem; 13398 13399 // Set the system/privileged flags as needed 13400 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 13401 if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 13402 != 0) { 13403 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13404 } 13405 13406 // Kill package processes including services, providers, etc. 13407 killPackage(deletedPackage, "replace sys pkg"); 13408 13409 // Remove existing system package 13410 removePackageLI(deletedPackage, true); 13411 13412 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 13413 if (!disabledSystem) { 13414 // We didn't need to disable the .apk as a current system package, 13415 // which means we are replacing another update that is already 13416 // installed. We need to make sure to delete the older one's .apk. 13417 res.removedInfo.args = createInstallArgsForExisting(0, 13418 deletedPackage.applicationInfo.getCodePath(), 13419 deletedPackage.applicationInfo.getResourcePath(), 13420 getAppDexInstructionSets(deletedPackage.applicationInfo)); 13421 } else { 13422 res.removedInfo.args = null; 13423 } 13424 13425 // Successfully disabled the old package. Now proceed with re-installation 13426 deleteCodeCacheDirsLI(pkg); 13427 deleteProfilesLI(pkg, /*destroy*/ false); 13428 13429 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13430 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 13431 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 13432 13433 PackageParser.Package newPackage = null; 13434 try { 13435 // Add the package to the internal data structures 13436 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 13437 13438 // Set the update and install times 13439 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 13440 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 13441 System.currentTimeMillis()); 13442 13443 // Check for shared user id changes 13444 String invalidPackageName = getParentOrChildPackageChangedSharedUser( 13445 deletedPackage, newPackage); 13446 if (invalidPackageName != null) { 13447 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13448 "Forbidding shared user change from " + deletedPkgSetting.sharedUser 13449 + " to " + invalidPackageName); 13450 } 13451 13452 // Update the package dynamic state if succeeded 13453 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13454 // Now that the install succeeded make sure we remove data 13455 // directories for any child package the update removed. 13456 final int deletedChildCount = (deletedPackage.childPackages != null) 13457 ? deletedPackage.childPackages.size() : 0; 13458 final int newChildCount = (newPackage.childPackages != null) 13459 ? newPackage.childPackages.size() : 0; 13460 for (int i = 0; i < deletedChildCount; i++) { 13461 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 13462 boolean childPackageDeleted = true; 13463 for (int j = 0; j < newChildCount; j++) { 13464 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 13465 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 13466 childPackageDeleted = false; 13467 break; 13468 } 13469 } 13470 if (childPackageDeleted) { 13471 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 13472 deletedChildPkg.packageName); 13473 if (ps != null && res.removedInfo.removedChildPackages != null) { 13474 PackageRemovedInfo removedChildRes = res.removedInfo 13475 .removedChildPackages.get(deletedChildPkg.packageName); 13476 removePackageDataLI(ps, allUsers, removedChildRes, 0, false); 13477 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 13478 } 13479 } 13480 } 13481 13482 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13483 prepareAppDataAfterInstall(newPackage); 13484 } 13485 } catch (PackageManagerException e) { 13486 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 13487 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13488 } 13489 13490 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13491 // Re installation failed. Restore old information 13492 // Remove new pkg information 13493 if (newPackage != null) { 13494 removeInstalledPackageLI(newPackage, true); 13495 } 13496 // Add back the old system package 13497 try { 13498 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 13499 } catch (PackageManagerException e) { 13500 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 13501 } 13502 13503 synchronized (mPackages) { 13504 if (disabledSystem) { 13505 enableSystemPackageLPw(deletedPackage); 13506 } 13507 13508 // Ensure the installer package name up to date 13509 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13510 13511 // Update permissions for restored package 13512 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13513 13514 mSettings.writeLPr(); 13515 } 13516 13517 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 13518 + " after failed upgrade"); 13519 } 13520 } 13521 13522 /** 13523 * Checks whether the parent or any of the child packages have a change shared 13524 * user. For a package to be a valid update the shred users of the parent and 13525 * the children should match. We may later support changing child shared users. 13526 * @param oldPkg The updated package. 13527 * @param newPkg The update package. 13528 * @return The shared user that change between the versions. 13529 */ 13530 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 13531 PackageParser.Package newPkg) { 13532 // Check parent shared user 13533 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 13534 return newPkg.packageName; 13535 } 13536 // Check child shared users 13537 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13538 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 13539 for (int i = 0; i < newChildCount; i++) { 13540 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 13541 // If this child was present, did it have the same shared user? 13542 for (int j = 0; j < oldChildCount; j++) { 13543 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 13544 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 13545 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 13546 return newChildPkg.packageName; 13547 } 13548 } 13549 } 13550 return null; 13551 } 13552 13553 private void removeNativeBinariesLI(PackageSetting ps) { 13554 // Remove the lib path for the parent package 13555 if (ps != null) { 13556 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 13557 // Remove the lib path for the child packages 13558 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 13559 for (int i = 0; i < childCount; i++) { 13560 PackageSetting childPs = null; 13561 synchronized (mPackages) { 13562 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 13563 } 13564 if (childPs != null) { 13565 NativeLibraryHelper.removeNativeBinariesLI(childPs 13566 .legacyNativeLibraryPathString); 13567 } 13568 } 13569 } 13570 } 13571 13572 private void enableSystemPackageLPw(PackageParser.Package pkg) { 13573 // Enable the parent package 13574 mSettings.enableSystemPackageLPw(pkg.packageName); 13575 // Enable the child packages 13576 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13577 for (int i = 0; i < childCount; i++) { 13578 PackageParser.Package childPkg = pkg.childPackages.get(i); 13579 mSettings.enableSystemPackageLPw(childPkg.packageName); 13580 } 13581 } 13582 13583 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 13584 PackageParser.Package newPkg) { 13585 // Disable the parent package (parent always replaced) 13586 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 13587 // Disable the child packages 13588 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13589 for (int i = 0; i < childCount; i++) { 13590 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 13591 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 13592 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 13593 } 13594 return disabled; 13595 } 13596 13597 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 13598 String installerPackageName) { 13599 // Enable the parent package 13600 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 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.setInstallerPackageName(childPkg.packageName, installerPackageName); 13606 } 13607 } 13608 13609 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 13610 // Collect all used permissions in the UID 13611 ArraySet<String> usedPermissions = new ArraySet<>(); 13612 final int packageCount = su.packages.size(); 13613 for (int i = 0; i < packageCount; i++) { 13614 PackageSetting ps = su.packages.valueAt(i); 13615 if (ps.pkg == null) { 13616 continue; 13617 } 13618 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 13619 for (int j = 0; j < requestedPermCount; j++) { 13620 String permission = ps.pkg.requestedPermissions.get(j); 13621 BasePermission bp = mSettings.mPermissions.get(permission); 13622 if (bp != null) { 13623 usedPermissions.add(permission); 13624 } 13625 } 13626 } 13627 13628 PermissionsState permissionsState = su.getPermissionsState(); 13629 // Prune install permissions 13630 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 13631 final int installPermCount = installPermStates.size(); 13632 for (int i = installPermCount - 1; i >= 0; i--) { 13633 PermissionState permissionState = installPermStates.get(i); 13634 if (!usedPermissions.contains(permissionState.getName())) { 13635 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 13636 if (bp != null) { 13637 permissionsState.revokeInstallPermission(bp); 13638 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 13639 PackageManager.MASK_PERMISSION_FLAGS, 0); 13640 } 13641 } 13642 } 13643 13644 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 13645 13646 // Prune runtime permissions 13647 for (int userId : allUserIds) { 13648 List<PermissionState> runtimePermStates = permissionsState 13649 .getRuntimePermissionStates(userId); 13650 final int runtimePermCount = runtimePermStates.size(); 13651 for (int i = runtimePermCount - 1; i >= 0; i--) { 13652 PermissionState permissionState = runtimePermStates.get(i); 13653 if (!usedPermissions.contains(permissionState.getName())) { 13654 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 13655 if (bp != null) { 13656 permissionsState.revokeRuntimePermission(bp, userId); 13657 permissionsState.updatePermissionFlags(bp, userId, 13658 PackageManager.MASK_PERMISSION_FLAGS, 0); 13659 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 13660 runtimePermissionChangedUserIds, userId); 13661 } 13662 } 13663 } 13664 } 13665 13666 return runtimePermissionChangedUserIds; 13667 } 13668 13669 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 13670 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 13671 // Update the parent package setting 13672 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 13673 res, user); 13674 // Update the child packages setting 13675 final int childCount = (newPackage.childPackages != null) 13676 ? newPackage.childPackages.size() : 0; 13677 for (int i = 0; i < childCount; i++) { 13678 PackageParser.Package childPackage = newPackage.childPackages.get(i); 13679 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 13680 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 13681 childRes.origUsers, childRes, user); 13682 } 13683 } 13684 13685 private void updateSettingsInternalLI(PackageParser.Package newPackage, 13686 String installerPackageName, int[] allUsers, int[] installedForUsers, 13687 PackageInstalledInfo res, UserHandle user) { 13688 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 13689 13690 String pkgName = newPackage.packageName; 13691 synchronized (mPackages) { 13692 //write settings. the installStatus will be incomplete at this stage. 13693 //note that the new package setting would have already been 13694 //added to mPackages. It hasn't been persisted yet. 13695 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 13696 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 13697 mSettings.writeLPr(); 13698 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13699 } 13700 13701 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 13702 synchronized (mPackages) { 13703 updatePermissionsLPw(newPackage.packageName, newPackage, 13704 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 13705 ? UPDATE_PERMISSIONS_ALL : 0)); 13706 // For system-bundled packages, we assume that installing an upgraded version 13707 // of the package implies that the user actually wants to run that new code, 13708 // so we enable the package. 13709 PackageSetting ps = mSettings.mPackages.get(pkgName); 13710 final int userId = user.getIdentifier(); 13711 if (ps != null) { 13712 if (isSystemApp(newPackage)) { 13713 if (DEBUG_INSTALL) { 13714 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 13715 } 13716 // Enable system package for requested users 13717 if (res.origUsers != null) { 13718 for (int origUserId : res.origUsers) { 13719 if (userId == UserHandle.USER_ALL || userId == origUserId) { 13720 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 13721 origUserId, installerPackageName); 13722 } 13723 } 13724 } 13725 // Also convey the prior install/uninstall state 13726 if (allUsers != null && installedForUsers != null) { 13727 for (int currentUserId : allUsers) { 13728 final boolean installed = ArrayUtils.contains( 13729 installedForUsers, currentUserId); 13730 if (DEBUG_INSTALL) { 13731 Slog.d(TAG, " user " + currentUserId + " => " + installed); 13732 } 13733 ps.setInstalled(installed, currentUserId); 13734 } 13735 // these install state changes will be persisted in the 13736 // upcoming call to mSettings.writeLPr(). 13737 } 13738 } 13739 // It's implied that when a user requests installation, they want the app to be 13740 // installed and enabled. 13741 if (userId != UserHandle.USER_ALL) { 13742 ps.setInstalled(true, userId); 13743 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 13744 } 13745 } 13746 res.name = pkgName; 13747 res.uid = newPackage.applicationInfo.uid; 13748 res.pkg = newPackage; 13749 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 13750 mSettings.setInstallerPackageName(pkgName, installerPackageName); 13751 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13752 //to update install status 13753 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 13754 mSettings.writeLPr(); 13755 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13756 } 13757 13758 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13759 } 13760 13761 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 13762 try { 13763 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 13764 installPackageLI(args, res); 13765 } finally { 13766 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13767 } 13768 } 13769 13770 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 13771 final int installFlags = args.installFlags; 13772 final String installerPackageName = args.installerPackageName; 13773 final String volumeUuid = args.volumeUuid; 13774 final File tmpPackageFile = new File(args.getCodePath()); 13775 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 13776 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 13777 || (args.volumeUuid != null)); 13778 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 13779 boolean replace = false; 13780 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 13781 if (args.move != null) { 13782 // moving a complete application; perform an initial scan on the new install location 13783 scanFlags |= SCAN_INITIAL; 13784 } 13785 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 13786 scanFlags |= SCAN_DONT_KILL_APP; 13787 } 13788 13789 // Result object to be returned 13790 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13791 13792 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 13793 13794 // Sanity check 13795 if (ephemeral && (forwardLocked || onExternal)) { 13796 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 13797 + " external=" + onExternal); 13798 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13799 return; 13800 } 13801 13802 // Retrieve PackageSettings and parse package 13803 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 13804 | PackageParser.PARSE_ENFORCE_CODE 13805 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 13806 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 13807 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 13808 PackageParser pp = new PackageParser(); 13809 pp.setSeparateProcesses(mSeparateProcesses); 13810 pp.setDisplayMetrics(mMetrics); 13811 13812 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 13813 final PackageParser.Package pkg; 13814 try { 13815 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 13816 } catch (PackageParserException e) { 13817 res.setError("Failed parse during installPackageLI", e); 13818 return; 13819 } finally { 13820 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13821 } 13822 13823 // If we are installing a clustered package add results for the children 13824 if (pkg.childPackages != null) { 13825 synchronized (mPackages) { 13826 final int childCount = pkg.childPackages.size(); 13827 for (int i = 0; i < childCount; i++) { 13828 PackageParser.Package childPkg = pkg.childPackages.get(i); 13829 PackageInstalledInfo childRes = new PackageInstalledInfo(); 13830 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13831 childRes.pkg = childPkg; 13832 childRes.name = childPkg.packageName; 13833 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13834 if (childPs != null) { 13835 childRes.origUsers = childPs.queryInstalledUsers( 13836 sUserManager.getUserIds(), true); 13837 } 13838 if ((mPackages.containsKey(childPkg.packageName))) { 13839 childRes.removedInfo = new PackageRemovedInfo(); 13840 childRes.removedInfo.removedPackage = childPkg.packageName; 13841 } 13842 if (res.addedChildPackages == null) { 13843 res.addedChildPackages = new ArrayMap<>(); 13844 } 13845 res.addedChildPackages.put(childPkg.packageName, childRes); 13846 } 13847 } 13848 } 13849 13850 // If package doesn't declare API override, mark that we have an install 13851 // time CPU ABI override. 13852 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 13853 pkg.cpuAbiOverride = args.abiOverride; 13854 } 13855 13856 String pkgName = res.name = pkg.packageName; 13857 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 13858 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 13859 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 13860 return; 13861 } 13862 } 13863 13864 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 13865 try { 13866 PackageParser.collectCertificates(pkg, parseFlags); 13867 } catch (PackageParserException e) { 13868 res.setError("Failed collect during installPackageLI", e); 13869 return; 13870 } finally { 13871 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13872 } 13873 13874 // Get rid of all references to package scan path via parser. 13875 pp = null; 13876 String oldCodePath = null; 13877 boolean systemApp = false; 13878 synchronized (mPackages) { 13879 // Check if installing already existing package 13880 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 13881 String oldName = mSettings.mRenamedPackages.get(pkgName); 13882 if (pkg.mOriginalPackages != null 13883 && pkg.mOriginalPackages.contains(oldName) 13884 && mPackages.containsKey(oldName)) { 13885 // This package is derived from an original package, 13886 // and this device has been updating from that original 13887 // name. We must continue using the original name, so 13888 // rename the new package here. 13889 pkg.setPackageName(oldName); 13890 pkgName = pkg.packageName; 13891 replace = true; 13892 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 13893 + oldName + " pkgName=" + pkgName); 13894 } else if (mPackages.containsKey(pkgName)) { 13895 // This package, under its official name, already exists 13896 // on the device; we should replace it. 13897 replace = true; 13898 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 13899 } 13900 13901 // Child packages are installed through the parent package 13902 if (pkg.parentPackage != null) { 13903 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 13904 "Package " + pkg.packageName + " is child of package " 13905 + pkg.parentPackage.parentPackage + ". Child packages " 13906 + "can be updated only through the parent package."); 13907 return; 13908 } 13909 13910 if (replace) { 13911 // Prevent apps opting out from runtime permissions 13912 PackageParser.Package oldPackage = mPackages.get(pkgName); 13913 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 13914 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 13915 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 13916 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 13917 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 13918 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 13919 + " doesn't support runtime permissions but the old" 13920 + " target SDK " + oldTargetSdk + " does."); 13921 return; 13922 } 13923 13924 // Prevent installing of child packages 13925 if (oldPackage.parentPackage != null) { 13926 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 13927 "Package " + pkg.packageName + " is child of package " 13928 + oldPackage.parentPackage + ". Child packages " 13929 + "can be updated only through the parent package."); 13930 return; 13931 } 13932 } 13933 } 13934 13935 PackageSetting ps = mSettings.mPackages.get(pkgName); 13936 if (ps != null) { 13937 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 13938 13939 // Quick sanity check that we're signed correctly if updating; 13940 // we'll check this again later when scanning, but we want to 13941 // bail early here before tripping over redefined permissions. 13942 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13943 if (!checkUpgradeKeySetLP(ps, pkg)) { 13944 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 13945 + pkg.packageName + " upgrade keys do not match the " 13946 + "previously installed version"); 13947 return; 13948 } 13949 } else { 13950 try { 13951 verifySignaturesLP(ps, pkg); 13952 } catch (PackageManagerException e) { 13953 res.setError(e.error, e.getMessage()); 13954 return; 13955 } 13956 } 13957 13958 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 13959 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 13960 systemApp = (ps.pkg.applicationInfo.flags & 13961 ApplicationInfo.FLAG_SYSTEM) != 0; 13962 } 13963 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13964 } 13965 13966 // Check whether the newly-scanned package wants to define an already-defined perm 13967 int N = pkg.permissions.size(); 13968 for (int i = N-1; i >= 0; i--) { 13969 PackageParser.Permission perm = pkg.permissions.get(i); 13970 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 13971 if (bp != null) { 13972 // If the defining package is signed with our cert, it's okay. This 13973 // also includes the "updating the same package" case, of course. 13974 // "updating same package" could also involve key-rotation. 13975 final boolean sigsOk; 13976 if (bp.sourcePackage.equals(pkg.packageName) 13977 && (bp.packageSetting instanceof PackageSetting) 13978 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 13979 scanFlags))) { 13980 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 13981 } else { 13982 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 13983 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 13984 } 13985 if (!sigsOk) { 13986 // If the owning package is the system itself, we log but allow 13987 // install to proceed; we fail the install on all other permission 13988 // redefinitions. 13989 if (!bp.sourcePackage.equals("android")) { 13990 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 13991 + pkg.packageName + " attempting to redeclare permission " 13992 + perm.info.name + " already owned by " + bp.sourcePackage); 13993 res.origPermission = perm.info.name; 13994 res.origPackage = bp.sourcePackage; 13995 return; 13996 } else { 13997 Slog.w(TAG, "Package " + pkg.packageName 13998 + " attempting to redeclare system permission " 13999 + perm.info.name + "; ignoring new declaration"); 14000 pkg.permissions.remove(i); 14001 } 14002 } 14003 } 14004 } 14005 } 14006 14007 if (systemApp) { 14008 if (onExternal) { 14009 // Abort update; system app can't be replaced with app on sdcard 14010 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14011 "Cannot install updates to system apps on sdcard"); 14012 return; 14013 } else if (ephemeral) { 14014 // Abort update; system app can't be replaced with an ephemeral app 14015 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14016 "Cannot update a system app with an ephemeral app"); 14017 return; 14018 } 14019 } 14020 14021 if (args.move != null) { 14022 // We did an in-place move, so dex is ready to roll 14023 scanFlags |= SCAN_NO_DEX; 14024 scanFlags |= SCAN_MOVE; 14025 14026 synchronized (mPackages) { 14027 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14028 if (ps == null) { 14029 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14030 "Missing settings for moved package " + pkgName); 14031 } 14032 14033 // We moved the entire application as-is, so bring over the 14034 // previously derived ABI information. 14035 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14036 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14037 } 14038 14039 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14040 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14041 scanFlags |= SCAN_NO_DEX; 14042 14043 try { 14044 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14045 args.abiOverride : pkg.cpuAbiOverride); 14046 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14047 true /* extract libs */); 14048 } catch (PackageManagerException pme) { 14049 Slog.e(TAG, "Error deriving application ABI", pme); 14050 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14051 return; 14052 } 14053 14054 14055 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14056 // Do not run PackageDexOptimizer through the local performDexOpt 14057 // method because `pkg` is not in `mPackages` yet. 14058 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 14059 false /* checkProfiles */, getCompilerFilterForReason(REASON_INSTALL)); 14060 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14061 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14062 String msg = "Extracking package failed for " + pkgName; 14063 res.setError(INSTALL_FAILED_DEXOPT, msg); 14064 return; 14065 } 14066 } 14067 14068 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14069 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14070 return; 14071 } 14072 14073 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14074 14075 if (replace) { 14076 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14077 installerPackageName, res); 14078 } else { 14079 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14080 args.user, installerPackageName, volumeUuid, res); 14081 } 14082 synchronized (mPackages) { 14083 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14084 if (ps != null) { 14085 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14086 } 14087 14088 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14089 for (int i = 0; i < childCount; i++) { 14090 PackageParser.Package childPkg = pkg.childPackages.get(i); 14091 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14092 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14093 if (childPs != null) { 14094 childRes.newUsers = childPs.queryInstalledUsers( 14095 sUserManager.getUserIds(), true); 14096 } 14097 } 14098 } 14099 } 14100 14101 private void startIntentFilterVerifications(int userId, boolean replacing, 14102 PackageParser.Package pkg) { 14103 if (mIntentFilterVerifierComponent == null) { 14104 Slog.w(TAG, "No IntentFilter verification will not be done as " 14105 + "there is no IntentFilterVerifier available!"); 14106 return; 14107 } 14108 14109 final int verifierUid = getPackageUid( 14110 mIntentFilterVerifierComponent.getPackageName(), 14111 MATCH_DEBUG_TRIAGED_MISSING, 14112 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 14113 14114 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14115 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14116 mHandler.sendMessage(msg); 14117 14118 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14119 for (int i = 0; i < childCount; i++) { 14120 PackageParser.Package childPkg = pkg.childPackages.get(i); 14121 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14122 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 14123 mHandler.sendMessage(msg); 14124 } 14125 } 14126 14127 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 14128 PackageParser.Package pkg) { 14129 int size = pkg.activities.size(); 14130 if (size == 0) { 14131 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14132 "No activity, so no need to verify any IntentFilter!"); 14133 return; 14134 } 14135 14136 final boolean hasDomainURLs = hasDomainURLs(pkg); 14137 if (!hasDomainURLs) { 14138 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14139 "No domain URLs, so no need to verify any IntentFilter!"); 14140 return; 14141 } 14142 14143 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 14144 + " if any IntentFilter from the " + size 14145 + " Activities needs verification ..."); 14146 14147 int count = 0; 14148 final String packageName = pkg.packageName; 14149 14150 synchronized (mPackages) { 14151 // If this is a new install and we see that we've already run verification for this 14152 // package, we have nothing to do: it means the state was restored from backup. 14153 if (!replacing) { 14154 IntentFilterVerificationInfo ivi = 14155 mSettings.getIntentFilterVerificationLPr(packageName); 14156 if (ivi != null) { 14157 if (DEBUG_DOMAIN_VERIFICATION) { 14158 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 14159 + ivi.getStatusString()); 14160 } 14161 return; 14162 } 14163 } 14164 14165 // If any filters need to be verified, then all need to be. 14166 boolean needToVerify = false; 14167 for (PackageParser.Activity a : pkg.activities) { 14168 for (ActivityIntentInfo filter : a.intents) { 14169 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 14170 if (DEBUG_DOMAIN_VERIFICATION) { 14171 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 14172 } 14173 needToVerify = true; 14174 break; 14175 } 14176 } 14177 } 14178 14179 if (needToVerify) { 14180 final int verificationId = mIntentFilterVerificationToken++; 14181 for (PackageParser.Activity a : pkg.activities) { 14182 for (ActivityIntentInfo filter : a.intents) { 14183 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 14184 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14185 "Verification needed for IntentFilter:" + filter.toString()); 14186 mIntentFilterVerifier.addOneIntentFilterVerification( 14187 verifierUid, userId, verificationId, filter, packageName); 14188 count++; 14189 } 14190 } 14191 } 14192 } 14193 } 14194 14195 if (count > 0) { 14196 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 14197 + " IntentFilter verification" + (count > 1 ? "s" : "") 14198 + " for userId:" + userId); 14199 mIntentFilterVerifier.startVerifications(userId); 14200 } else { 14201 if (DEBUG_DOMAIN_VERIFICATION) { 14202 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 14203 } 14204 } 14205 } 14206 14207 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 14208 final ComponentName cn = filter.activity.getComponentName(); 14209 final String packageName = cn.getPackageName(); 14210 14211 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 14212 packageName); 14213 if (ivi == null) { 14214 return true; 14215 } 14216 int status = ivi.getStatus(); 14217 switch (status) { 14218 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 14219 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 14220 return true; 14221 14222 default: 14223 // Nothing to do 14224 return false; 14225 } 14226 } 14227 14228 private static boolean isMultiArch(ApplicationInfo info) { 14229 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 14230 } 14231 14232 private static boolean isExternal(PackageParser.Package pkg) { 14233 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14234 } 14235 14236 private static boolean isExternal(PackageSetting ps) { 14237 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14238 } 14239 14240 private static boolean isEphemeral(PackageParser.Package pkg) { 14241 return pkg.applicationInfo.isEphemeralApp(); 14242 } 14243 14244 private static boolean isEphemeral(PackageSetting ps) { 14245 return ps.pkg != null && isEphemeral(ps.pkg); 14246 } 14247 14248 private static boolean isSystemApp(PackageParser.Package pkg) { 14249 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 14250 } 14251 14252 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 14253 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14254 } 14255 14256 private static boolean hasDomainURLs(PackageParser.Package pkg) { 14257 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 14258 } 14259 14260 private static boolean isSystemApp(PackageSetting ps) { 14261 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 14262 } 14263 14264 private static boolean isUpdatedSystemApp(PackageSetting ps) { 14265 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 14266 } 14267 14268 private int packageFlagsToInstallFlags(PackageSetting ps) { 14269 int installFlags = 0; 14270 if (isEphemeral(ps)) { 14271 installFlags |= PackageManager.INSTALL_EPHEMERAL; 14272 } 14273 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 14274 // This existing package was an external ASEC install when we have 14275 // the external flag without a UUID 14276 installFlags |= PackageManager.INSTALL_EXTERNAL; 14277 } 14278 if (ps.isForwardLocked()) { 14279 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 14280 } 14281 return installFlags; 14282 } 14283 14284 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 14285 if (isExternal(pkg)) { 14286 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14287 return StorageManager.UUID_PRIMARY_PHYSICAL; 14288 } else { 14289 return pkg.volumeUuid; 14290 } 14291 } else { 14292 return StorageManager.UUID_PRIVATE_INTERNAL; 14293 } 14294 } 14295 14296 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 14297 if (isExternal(pkg)) { 14298 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14299 return mSettings.getExternalVersion(); 14300 } else { 14301 return mSettings.findOrCreateVersion(pkg.volumeUuid); 14302 } 14303 } else { 14304 return mSettings.getInternalVersion(); 14305 } 14306 } 14307 14308 private void deleteTempPackageFiles() { 14309 final FilenameFilter filter = new FilenameFilter() { 14310 public boolean accept(File dir, String name) { 14311 return name.startsWith("vmdl") && name.endsWith(".tmp"); 14312 } 14313 }; 14314 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 14315 file.delete(); 14316 } 14317 } 14318 14319 @Override 14320 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 14321 int flags) { 14322 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 14323 flags); 14324 } 14325 14326 @Override 14327 public void deletePackage(final String packageName, 14328 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 14329 mContext.enforceCallingOrSelfPermission( 14330 android.Manifest.permission.DELETE_PACKAGES, null); 14331 Preconditions.checkNotNull(packageName); 14332 Preconditions.checkNotNull(observer); 14333 final int uid = Binder.getCallingUid(); 14334 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 14335 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 14336 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 14337 mContext.enforceCallingOrSelfPermission( 14338 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14339 "deletePackage for user " + userId); 14340 } 14341 14342 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 14343 try { 14344 observer.onPackageDeleted(packageName, 14345 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 14346 } catch (RemoteException re) { 14347 } 14348 return; 14349 } 14350 14351 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 14352 try { 14353 observer.onPackageDeleted(packageName, 14354 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 14355 } catch (RemoteException re) { 14356 } 14357 return; 14358 } 14359 14360 if (DEBUG_REMOVE) { 14361 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 14362 + " deleteAllUsers: " + deleteAllUsers ); 14363 } 14364 // Queue up an async operation since the package deletion may take a little while. 14365 mHandler.post(new Runnable() { 14366 public void run() { 14367 mHandler.removeCallbacks(this); 14368 int returnCode; 14369 if (!deleteAllUsers) { 14370 returnCode = deletePackageX(packageName, userId, flags); 14371 } else { 14372 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 14373 // If nobody is blocking uninstall, proceed with delete for all users 14374 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 14375 returnCode = deletePackageX(packageName, userId, flags); 14376 } else { 14377 // Otherwise uninstall individually for users with blockUninstalls=false 14378 final int userFlags = flags & ~PackageManager.DELETE_ALL_USERS; 14379 for (int userId : users) { 14380 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 14381 returnCode = deletePackageX(packageName, userId, userFlags); 14382 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 14383 Slog.w(TAG, "Package delete failed for user " + userId 14384 + ", returnCode " + returnCode); 14385 } 14386 } 14387 } 14388 // The app has only been marked uninstalled for certain users. 14389 // We still need to report that delete was blocked 14390 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 14391 } 14392 } 14393 try { 14394 observer.onPackageDeleted(packageName, returnCode, null); 14395 } catch (RemoteException e) { 14396 Log.i(TAG, "Observer no longer exists."); 14397 } //end catch 14398 } //end run 14399 }); 14400 } 14401 14402 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 14403 int[] result = EMPTY_INT_ARRAY; 14404 for (int userId : userIds) { 14405 if (getBlockUninstallForUser(packageName, userId)) { 14406 result = ArrayUtils.appendInt(result, userId); 14407 } 14408 } 14409 return result; 14410 } 14411 14412 @Override 14413 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 14414 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 14415 } 14416 14417 private boolean isPackageDeviceAdmin(String packageName, int userId) { 14418 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 14419 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 14420 try { 14421 if (dpm != null) { 14422 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 14423 /* callingUserOnly =*/ false); 14424 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 14425 : deviceOwnerComponentName.getPackageName(); 14426 // Does the package contains the device owner? 14427 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 14428 // this check is probably not needed, since DO should be registered as a device 14429 // admin on some user too. (Original bug for this: b/17657954) 14430 if (packageName.equals(deviceOwnerPackageName)) { 14431 return true; 14432 } 14433 // Does it contain a device admin for any user? 14434 int[] users; 14435 if (userId == UserHandle.USER_ALL) { 14436 users = sUserManager.getUserIds(); 14437 } else { 14438 users = new int[]{userId}; 14439 } 14440 for (int i = 0; i < users.length; ++i) { 14441 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 14442 return true; 14443 } 14444 } 14445 } 14446 } catch (RemoteException e) { 14447 } 14448 return false; 14449 } 14450 14451 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 14452 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 14453 } 14454 14455 /** 14456 * This method is an internal method that could be get invoked either 14457 * to delete an installed package or to clean up a failed installation. 14458 * After deleting an installed package, a broadcast is sent to notify any 14459 * listeners that the package has been installed. For cleaning up a failed 14460 * installation, the broadcast is not necessary since the package's 14461 * installation wouldn't have sent the initial broadcast either 14462 * The key steps in deleting a package are 14463 * deleting the package information in internal structures like mPackages, 14464 * deleting the packages base directories through installd 14465 * updating mSettings to reflect current status 14466 * persisting settings for later use 14467 * sending a broadcast if necessary 14468 */ 14469 private int deletePackageX(String packageName, int userId, int flags) { 14470 final PackageRemovedInfo info = new PackageRemovedInfo(); 14471 final boolean res; 14472 14473 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 14474 ? UserHandle.ALL : new UserHandle(userId); 14475 14476 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 14477 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 14478 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 14479 } 14480 14481 PackageSetting uninstalledPs = null; 14482 14483 // for the uninstall-updates case and restricted profiles, remember the per- 14484 // user handle installed state 14485 int[] allUsers; 14486 synchronized (mPackages) { 14487 uninstalledPs = mSettings.mPackages.get(packageName); 14488 if (uninstalledPs == null) { 14489 Slog.w(TAG, "Not removing non-existent package " + packageName); 14490 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14491 } 14492 allUsers = sUserManager.getUserIds(); 14493 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 14494 } 14495 14496 synchronized (mInstallLock) { 14497 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 14498 res = deletePackageLI(packageName, removeForUser, true, allUsers, 14499 flags | REMOVE_CHATTY, info, true, null); 14500 deleteProfilesLI(packageName, /*destroy*/ true); 14501 synchronized (mPackages) { 14502 if (res) { 14503 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 14504 } 14505 } 14506 } 14507 14508 if (res) { 14509 final boolean killApp = (flags & PackageManager.INSTALL_DONT_KILL_APP) == 0; 14510 info.sendPackageRemovedBroadcasts(killApp); 14511 info.sendSystemPackageUpdatedBroadcasts(); 14512 info.sendSystemPackageAppearedBroadcasts(); 14513 } 14514 // Force a gc here. 14515 Runtime.getRuntime().gc(); 14516 // Delete the resources here after sending the broadcast to let 14517 // other processes clean up before deleting resources. 14518 if (info.args != null) { 14519 synchronized (mInstallLock) { 14520 info.args.doPostDeleteLI(true); 14521 } 14522 } 14523 14524 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14525 } 14526 14527 class PackageRemovedInfo { 14528 String removedPackage; 14529 int uid = -1; 14530 int removedAppId = -1; 14531 int[] origUsers; 14532 int[] removedUsers = null; 14533 boolean isRemovedPackageSystemUpdate = false; 14534 boolean isUpdate; 14535 boolean dataRemoved; 14536 boolean removedForAllUsers; 14537 // Clean up resources deleted packages. 14538 InstallArgs args = null; 14539 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 14540 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 14541 14542 void sendPackageRemovedBroadcasts(boolean killApp) { 14543 sendPackageRemovedBroadcastInternal(killApp); 14544 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 14545 for (int i = 0; i < childCount; i++) { 14546 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 14547 childInfo.sendPackageRemovedBroadcastInternal(killApp); 14548 } 14549 } 14550 14551 void sendSystemPackageUpdatedBroadcasts() { 14552 if (isRemovedPackageSystemUpdate) { 14553 sendSystemPackageUpdatedBroadcastsInternal(); 14554 final int childCount = (removedChildPackages != null) 14555 ? removedChildPackages.size() : 0; 14556 for (int i = 0; i < childCount; i++) { 14557 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 14558 if (childInfo.isRemovedPackageSystemUpdate) { 14559 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 14560 } 14561 } 14562 } 14563 } 14564 14565 void sendSystemPackageAppearedBroadcasts() { 14566 final int packageCount = (appearedChildPackages != null) 14567 ? appearedChildPackages.size() : 0; 14568 for (int i = 0; i < packageCount; i++) { 14569 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 14570 for (int userId : installedInfo.newUsers) { 14571 sendPackageAddedForUser(installedInfo.name, true, 14572 UserHandle.getAppId(installedInfo.uid), userId); 14573 } 14574 } 14575 } 14576 14577 private void sendSystemPackageUpdatedBroadcastsInternal() { 14578 Bundle extras = new Bundle(2); 14579 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 14580 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14581 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 14582 extras, 0, null, null, null); 14583 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 14584 extras, 0, null, null, null); 14585 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 14586 null, 0, removedPackage, null, null); 14587 } 14588 14589 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 14590 Bundle extras = new Bundle(2); 14591 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 14592 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 14593 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 14594 if (isUpdate || isRemovedPackageSystemUpdate) { 14595 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14596 } 14597 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 14598 if (removedPackage != null) { 14599 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 14600 extras, 0, null, null, removedUsers); 14601 if (dataRemoved && !isRemovedPackageSystemUpdate) { 14602 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 14603 removedPackage, extras, 0, null, null, removedUsers); 14604 } 14605 } 14606 if (removedAppId >= 0) { 14607 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 14608 removedUsers); 14609 } 14610 } 14611 } 14612 14613 /* 14614 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 14615 * flag is not set, the data directory is removed as well. 14616 * make sure this flag is set for partially installed apps. If not its meaningless to 14617 * delete a partially installed application. 14618 */ 14619 private void removePackageDataLI(PackageSetting ps, int[] allUserHandles, 14620 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 14621 String packageName = ps.name; 14622 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 14623 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 14624 // Retrieve object to delete permissions for shared user later on 14625 final PackageSetting deletedPs; 14626 // reader 14627 synchronized (mPackages) { 14628 deletedPs = mSettings.mPackages.get(packageName); 14629 if (outInfo != null) { 14630 outInfo.removedPackage = packageName; 14631 outInfo.removedUsers = deletedPs != null 14632 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 14633 : null; 14634 } 14635 } 14636 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 14637 removeDataDirsLI(ps.volumeUuid, packageName); 14638 if (outInfo != null) { 14639 outInfo.dataRemoved = true; 14640 } 14641 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 14642 } 14643 // writer 14644 synchronized (mPackages) { 14645 if (deletedPs != null) { 14646 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 14647 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 14648 clearDefaultBrowserIfNeeded(packageName); 14649 if (outInfo != null) { 14650 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 14651 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 14652 } 14653 updatePermissionsLPw(deletedPs.name, null, 0); 14654 if (deletedPs.sharedUser != null) { 14655 // Remove permissions associated with package. Since runtime 14656 // permissions are per user we have to kill the removed package 14657 // or packages running under the shared user of the removed 14658 // package if revoking the permissions requested only by the removed 14659 // package is successful and this causes a change in gids. 14660 for (int userId : UserManagerService.getInstance().getUserIds()) { 14661 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 14662 userId); 14663 if (userIdToKill == UserHandle.USER_ALL 14664 || userIdToKill >= UserHandle.USER_SYSTEM) { 14665 // If gids changed for this user, kill all affected packages. 14666 mHandler.post(new Runnable() { 14667 @Override 14668 public void run() { 14669 // This has to happen with no lock held. 14670 killApplication(deletedPs.name, deletedPs.appId, 14671 KILL_APP_REASON_GIDS_CHANGED); 14672 } 14673 }); 14674 break; 14675 } 14676 } 14677 } 14678 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 14679 } 14680 // make sure to preserve per-user disabled state if this removal was just 14681 // a downgrade of a system app to the factory package 14682 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 14683 if (DEBUG_REMOVE) { 14684 Slog.d(TAG, "Propagating install state across downgrade"); 14685 } 14686 for (int userId : allUserHandles) { 14687 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 14688 if (DEBUG_REMOVE) { 14689 Slog.d(TAG, " user " + userId + " => " + installed); 14690 } 14691 ps.setInstalled(installed, userId); 14692 } 14693 } 14694 } 14695 // can downgrade to reader 14696 if (writeSettings) { 14697 // Save settings now 14698 mSettings.writeLPr(); 14699 } 14700 } 14701 if (outInfo != null) { 14702 // A user ID was deleted here. Go through all users and remove it 14703 // from KeyStore. 14704 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 14705 } 14706 } 14707 14708 static boolean locationIsPrivileged(File path) { 14709 try { 14710 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 14711 .getCanonicalPath(); 14712 return path.getCanonicalPath().startsWith(privilegedAppDir); 14713 } catch (IOException e) { 14714 Slog.e(TAG, "Unable to access code path " + path); 14715 } 14716 return false; 14717 } 14718 14719 /* 14720 * Tries to delete system package. 14721 */ 14722 private boolean deleteSystemPackageLI(PackageParser.Package deletedPkg, 14723 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 14724 boolean writeSettings) { 14725 if (deletedPs.parentPackageName != null) { 14726 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 14727 return false; 14728 } 14729 14730 final boolean applyUserRestrictions 14731 = (allUserHandles != null) && (outInfo.origUsers != null); 14732 final PackageSetting disabledPs; 14733 // Confirm if the system package has been updated 14734 // An updated system app can be deleted. This will also have to restore 14735 // the system pkg from system partition 14736 // reader 14737 synchronized (mPackages) { 14738 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 14739 } 14740 14741 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 14742 + " disabledPs=" + disabledPs); 14743 14744 if (disabledPs == null) { 14745 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 14746 return false; 14747 } else if (DEBUG_REMOVE) { 14748 Slog.d(TAG, "Deleting system pkg from data partition"); 14749 } 14750 14751 if (DEBUG_REMOVE) { 14752 if (applyUserRestrictions) { 14753 Slog.d(TAG, "Remembering install states:"); 14754 for (int userId : allUserHandles) { 14755 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 14756 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 14757 } 14758 } 14759 } 14760 14761 // Delete the updated package 14762 outInfo.isRemovedPackageSystemUpdate = true; 14763 if (outInfo.removedChildPackages != null) { 14764 final int childCount = (deletedPs.childPackageNames != null) 14765 ? deletedPs.childPackageNames.size() : 0; 14766 for (int i = 0; i < childCount; i++) { 14767 String childPackageName = deletedPs.childPackageNames.get(i); 14768 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 14769 .contains(childPackageName)) { 14770 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 14771 childPackageName); 14772 if (childInfo != null) { 14773 childInfo.isRemovedPackageSystemUpdate = true; 14774 } 14775 } 14776 } 14777 } 14778 14779 if (disabledPs.versionCode < deletedPs.versionCode) { 14780 // Delete data for downgrades 14781 flags &= ~PackageManager.DELETE_KEEP_DATA; 14782 } else { 14783 // Preserve data by setting flag 14784 flags |= PackageManager.DELETE_KEEP_DATA; 14785 } 14786 14787 boolean ret = deleteInstalledPackageLI(deletedPs, true, flags, allUserHandles, 14788 outInfo, writeSettings, disabledPs.pkg); 14789 if (!ret) { 14790 return false; 14791 } 14792 14793 // writer 14794 synchronized (mPackages) { 14795 // Reinstate the old system package 14796 enableSystemPackageLPw(disabledPs.pkg); 14797 // Remove any native libraries from the upgraded package. 14798 removeNativeBinariesLI(deletedPs); 14799 } 14800 14801 // Install the system package 14802 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 14803 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 14804 if (locationIsPrivileged(disabledPs.codePath)) { 14805 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 14806 } 14807 14808 final PackageParser.Package newPkg; 14809 try { 14810 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 14811 } catch (PackageManagerException e) { 14812 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 14813 + e.getMessage()); 14814 return false; 14815 } 14816 14817 prepareAppDataAfterInstall(newPkg); 14818 14819 // writer 14820 synchronized (mPackages) { 14821 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 14822 14823 // Propagate the permissions state as we do not want to drop on the floor 14824 // runtime permissions. The update permissions method below will take 14825 // care of removing obsolete permissions and grant install permissions. 14826 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 14827 updatePermissionsLPw(newPkg.packageName, newPkg, 14828 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 14829 14830 if (applyUserRestrictions) { 14831 if (DEBUG_REMOVE) { 14832 Slog.d(TAG, "Propagating install state across reinstall"); 14833 } 14834 for (int userId : allUserHandles) { 14835 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 14836 if (DEBUG_REMOVE) { 14837 Slog.d(TAG, " user " + userId + " => " + installed); 14838 } 14839 ps.setInstalled(installed, userId); 14840 14841 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 14842 } 14843 // Regardless of writeSettings we need to ensure that this restriction 14844 // state propagation is persisted 14845 mSettings.writeAllUsersPackageRestrictionsLPr(); 14846 } 14847 // can downgrade to reader here 14848 if (writeSettings) { 14849 mSettings.writeLPr(); 14850 } 14851 } 14852 return true; 14853 } 14854 14855 private boolean deleteInstalledPackageLI(PackageSetting ps, 14856 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 14857 PackageRemovedInfo outInfo, boolean writeSettings, 14858 PackageParser.Package replacingPackage) { 14859 synchronized (mPackages) { 14860 if (outInfo != null) { 14861 outInfo.uid = ps.appId; 14862 } 14863 14864 if (outInfo != null && outInfo.removedChildPackages != null) { 14865 final int childCount = (ps.childPackageNames != null) 14866 ? ps.childPackageNames.size() : 0; 14867 for (int i = 0; i < childCount; i++) { 14868 String childPackageName = ps.childPackageNames.get(i); 14869 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 14870 if (childPs == null) { 14871 return false; 14872 } 14873 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 14874 childPackageName); 14875 if (childInfo != null) { 14876 childInfo.uid = childPs.appId; 14877 } 14878 } 14879 } 14880 } 14881 14882 // Delete package data from internal structures and also remove data if flag is set 14883 removePackageDataLI(ps, allUserHandles, outInfo, flags, writeSettings); 14884 14885 // Delete the child packages data 14886 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14887 for (int i = 0; i < childCount; i++) { 14888 PackageSetting childPs; 14889 synchronized (mPackages) { 14890 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14891 } 14892 if (childPs != null) { 14893 PackageRemovedInfo childOutInfo = (outInfo != null 14894 && outInfo.removedChildPackages != null) 14895 ? outInfo.removedChildPackages.get(childPs.name) : null; 14896 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 14897 && (replacingPackage != null 14898 && !replacingPackage.hasChildPackage(childPs.name)) 14899 ? flags & ~DELETE_KEEP_DATA : flags; 14900 removePackageDataLI(childPs, allUserHandles, childOutInfo, 14901 deleteFlags, writeSettings); 14902 } 14903 } 14904 14905 // Delete application code and resources only for parent packages 14906 if (ps.parentPackageName == null) { 14907 if (deleteCodeAndResources && (outInfo != null)) { 14908 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 14909 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 14910 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 14911 } 14912 } 14913 14914 return true; 14915 } 14916 14917 @Override 14918 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 14919 int userId) { 14920 mContext.enforceCallingOrSelfPermission( 14921 android.Manifest.permission.DELETE_PACKAGES, null); 14922 synchronized (mPackages) { 14923 PackageSetting ps = mSettings.mPackages.get(packageName); 14924 if (ps == null) { 14925 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 14926 return false; 14927 } 14928 if (!ps.getInstalled(userId)) { 14929 // Can't block uninstall for an app that is not installed or enabled. 14930 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 14931 return false; 14932 } 14933 ps.setBlockUninstall(blockUninstall, userId); 14934 mSettings.writePackageRestrictionsLPr(userId); 14935 } 14936 return true; 14937 } 14938 14939 @Override 14940 public boolean getBlockUninstallForUser(String packageName, int userId) { 14941 synchronized (mPackages) { 14942 PackageSetting ps = mSettings.mPackages.get(packageName); 14943 if (ps == null) { 14944 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 14945 return false; 14946 } 14947 return ps.getBlockUninstall(userId); 14948 } 14949 } 14950 14951 @Override 14952 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 14953 int callingUid = Binder.getCallingUid(); 14954 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 14955 throw new SecurityException( 14956 "setRequiredForSystemUser can only be run by the system or root"); 14957 } 14958 synchronized (mPackages) { 14959 PackageSetting ps = mSettings.mPackages.get(packageName); 14960 if (ps == null) { 14961 Log.w(TAG, "Package doesn't exist: " + packageName); 14962 return false; 14963 } 14964 if (systemUserApp) { 14965 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 14966 } else { 14967 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 14968 } 14969 mSettings.writeLPr(); 14970 } 14971 return true; 14972 } 14973 14974 /* 14975 * This method handles package deletion in general 14976 */ 14977 private boolean deletePackageLI(String packageName, UserHandle user, 14978 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 14979 PackageRemovedInfo outInfo, boolean writeSettings, 14980 PackageParser.Package replacingPackage) { 14981 if (packageName == null) { 14982 Slog.w(TAG, "Attempt to delete null packageName."); 14983 return false; 14984 } 14985 14986 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 14987 14988 PackageSetting ps; 14989 14990 synchronized (mPackages) { 14991 ps = mSettings.mPackages.get(packageName); 14992 if (ps == null) { 14993 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 14994 return false; 14995 } 14996 14997 if (ps.parentPackageName != null && (!isSystemApp(ps) 14998 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 14999 if (DEBUG_REMOVE) { 15000 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15001 + ((user == null) ? UserHandle.USER_ALL : user)); 15002 } 15003 final int removedUserId = (user != null) ? user.getIdentifier() 15004 : UserHandle.USER_ALL; 15005 if (!clearPackageStateForUser(ps, removedUserId, outInfo)) { 15006 return false; 15007 } 15008 markPackageUninstalledForUserLPw(ps, user); 15009 scheduleWritePackageRestrictionsLocked(user); 15010 return true; 15011 } 15012 } 15013 15014 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15015 && user.getIdentifier() != UserHandle.USER_ALL)) { 15016 // The caller is asking that the package only be deleted for a single 15017 // user. To do this, we just mark its uninstalled state and delete 15018 // its data. If this is a system app, we only allow this to happen if 15019 // they have set the special DELETE_SYSTEM_APP which requests different 15020 // semantics than normal for uninstalling system apps. 15021 markPackageUninstalledForUserLPw(ps, user); 15022 15023 if (!isSystemApp(ps)) { 15024 // Do not uninstall the APK if an app should be cached 15025 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15026 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15027 // Other user still have this package installed, so all 15028 // we need to do is clear this user's data and save that 15029 // it is uninstalled. 15030 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15031 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 15032 return false; 15033 } 15034 scheduleWritePackageRestrictionsLocked(user); 15035 return true; 15036 } else { 15037 // We need to set it back to 'installed' so the uninstall 15038 // broadcasts will be sent correctly. 15039 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15040 ps.setInstalled(true, user.getIdentifier()); 15041 } 15042 } else { 15043 // This is a system app, so we assume that the 15044 // other users still have this package installed, so all 15045 // we need to do is clear this user's data and save that 15046 // it is uninstalled. 15047 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15048 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 15049 return false; 15050 } 15051 scheduleWritePackageRestrictionsLocked(user); 15052 return true; 15053 } 15054 } 15055 15056 // If we are deleting a composite package for all users, keep track 15057 // of result for each child. 15058 if (ps.childPackageNames != null && outInfo != null) { 15059 synchronized (mPackages) { 15060 final int childCount = ps.childPackageNames.size(); 15061 outInfo.removedChildPackages = new ArrayMap<>(childCount); 15062 for (int i = 0; i < childCount; i++) { 15063 String childPackageName = ps.childPackageNames.get(i); 15064 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 15065 childInfo.removedPackage = childPackageName; 15066 outInfo.removedChildPackages.put(childPackageName, childInfo); 15067 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15068 if (childPs != null) { 15069 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 15070 } 15071 } 15072 } 15073 } 15074 15075 boolean ret = false; 15076 if (isSystemApp(ps)) { 15077 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 15078 // When an updated system application is deleted we delete the existing resources 15079 // as well and fall back to existing code in system partition 15080 ret = deleteSystemPackageLI(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 15081 } else { 15082 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 15083 // Kill application pre-emptively especially for apps on sd. 15084 final boolean killApp = (flags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15085 if (killApp) { 15086 killApplication(packageName, ps.appId, "uninstall pkg"); 15087 } 15088 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, allUserHandles, 15089 outInfo, writeSettings, replacingPackage); 15090 } 15091 15092 // Take a note whether we deleted the package for all users 15093 if (outInfo != null) { 15094 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15095 if (outInfo.removedChildPackages != null) { 15096 synchronized (mPackages) { 15097 final int childCount = outInfo.removedChildPackages.size(); 15098 for (int i = 0; i < childCount; i++) { 15099 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 15100 if (childInfo != null) { 15101 childInfo.removedForAllUsers = mPackages.get( 15102 childInfo.removedPackage) == null; 15103 } 15104 } 15105 } 15106 } 15107 // If we uninstalled an update to a system app there may be some 15108 // child packages that appeared as they are declared in the system 15109 // app but were not declared in the update. 15110 if (isSystemApp(ps)) { 15111 synchronized (mPackages) { 15112 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 15113 final int childCount = (updatedPs.childPackageNames != null) 15114 ? updatedPs.childPackageNames.size() : 0; 15115 for (int i = 0; i < childCount; i++) { 15116 String childPackageName = updatedPs.childPackageNames.get(i); 15117 if (outInfo.removedChildPackages == null 15118 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 15119 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15120 if (childPs == null) { 15121 continue; 15122 } 15123 PackageInstalledInfo installRes = new PackageInstalledInfo(); 15124 installRes.name = childPackageName; 15125 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 15126 installRes.pkg = mPackages.get(childPackageName); 15127 installRes.uid = childPs.pkg.applicationInfo.uid; 15128 if (outInfo.appearedChildPackages == null) { 15129 outInfo.appearedChildPackages = new ArrayMap<>(); 15130 } 15131 outInfo.appearedChildPackages.put(childPackageName, installRes); 15132 } 15133 } 15134 } 15135 } 15136 } 15137 15138 return ret; 15139 } 15140 15141 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 15142 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 15143 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 15144 for (int nextUserId : userIds) { 15145 if (DEBUG_REMOVE) { 15146 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 15147 } 15148 ps.setUserState(nextUserId, COMPONENT_ENABLED_STATE_DEFAULT, 15149 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 15150 false /*hidden*/, false /*suspended*/, null, null, null, 15151 false /*blockUninstall*/, 15152 ps.readUserState(nextUserId).domainVerificationStatus, 0); 15153 } 15154 } 15155 15156 private boolean clearPackageStateForUser(PackageSetting ps, int userId, 15157 PackageRemovedInfo outInfo) { 15158 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 15159 : new int[] {userId}; 15160 for (int nextUserId : userIds) { 15161 if (DEBUG_REMOVE) { 15162 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 15163 + nextUserId); 15164 } 15165 final int flags = StorageManager.FLAG_STORAGE_CE| StorageManager.FLAG_STORAGE_DE; 15166 try { 15167 mInstaller.destroyAppData(ps.volumeUuid, ps.name, nextUserId, flags); 15168 } catch (InstallerException e) { 15169 Slog.w(TAG, "Couldn't remove cache files for package " + ps.name, e); 15170 return false; 15171 } 15172 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 15173 schedulePackageCleaning(ps.name, nextUserId, false); 15174 synchronized (mPackages) { 15175 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 15176 scheduleWritePackageRestrictionsLocked(nextUserId); 15177 } 15178 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 15179 } 15180 } 15181 15182 if (outInfo != null) { 15183 outInfo.removedPackage = ps.name; 15184 outInfo.removedAppId = ps.appId; 15185 outInfo.removedUsers = userIds; 15186 } 15187 15188 return true; 15189 } 15190 15191 private final class ClearStorageConnection implements ServiceConnection { 15192 IMediaContainerService mContainerService; 15193 15194 @Override 15195 public void onServiceConnected(ComponentName name, IBinder service) { 15196 synchronized (this) { 15197 mContainerService = IMediaContainerService.Stub.asInterface(service); 15198 notifyAll(); 15199 } 15200 } 15201 15202 @Override 15203 public void onServiceDisconnected(ComponentName name) { 15204 } 15205 } 15206 15207 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 15208 final boolean mounted; 15209 if (Environment.isExternalStorageEmulated()) { 15210 mounted = true; 15211 } else { 15212 final String status = Environment.getExternalStorageState(); 15213 15214 mounted = status.equals(Environment.MEDIA_MOUNTED) 15215 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 15216 } 15217 15218 if (!mounted) { 15219 return; 15220 } 15221 15222 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 15223 int[] users; 15224 if (userId == UserHandle.USER_ALL) { 15225 users = sUserManager.getUserIds(); 15226 } else { 15227 users = new int[] { userId }; 15228 } 15229 final ClearStorageConnection conn = new ClearStorageConnection(); 15230 if (mContext.bindServiceAsUser( 15231 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 15232 try { 15233 for (int curUser : users) { 15234 long timeout = SystemClock.uptimeMillis() + 5000; 15235 synchronized (conn) { 15236 long now = SystemClock.uptimeMillis(); 15237 while (conn.mContainerService == null && now < timeout) { 15238 try { 15239 conn.wait(timeout - now); 15240 } catch (InterruptedException e) { 15241 } 15242 } 15243 } 15244 if (conn.mContainerService == null) { 15245 return; 15246 } 15247 15248 final UserEnvironment userEnv = new UserEnvironment(curUser); 15249 clearDirectory(conn.mContainerService, 15250 userEnv.buildExternalStorageAppCacheDirs(packageName)); 15251 if (allData) { 15252 clearDirectory(conn.mContainerService, 15253 userEnv.buildExternalStorageAppDataDirs(packageName)); 15254 clearDirectory(conn.mContainerService, 15255 userEnv.buildExternalStorageAppMediaDirs(packageName)); 15256 } 15257 } 15258 } finally { 15259 mContext.unbindService(conn); 15260 } 15261 } 15262 } 15263 15264 @Override 15265 public void clearApplicationProfileData(String packageName) { 15266 enforceSystemOrRoot("Only the system can clear all profile data"); 15267 try { 15268 mInstaller.clearAppProfiles(packageName); 15269 } catch (InstallerException ex) { 15270 Log.e(TAG, "Could not clear profile data of package " + packageName); 15271 } 15272 } 15273 15274 @Override 15275 public void clearApplicationUserData(final String packageName, 15276 final IPackageDataObserver observer, final int userId) { 15277 mContext.enforceCallingOrSelfPermission( 15278 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 15279 15280 enforceCrossUserPermission(Binder.getCallingUid(), userId, 15281 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 15282 15283 final DevicePolicyManagerInternal dpmi = LocalServices 15284 .getService(DevicePolicyManagerInternal.class); 15285 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 15286 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 15287 } 15288 // Queue up an async operation since the package deletion may take a little while. 15289 mHandler.post(new Runnable() { 15290 public void run() { 15291 mHandler.removeCallbacks(this); 15292 final boolean succeeded; 15293 synchronized (mInstallLock) { 15294 succeeded = clearApplicationUserDataLI(packageName, userId); 15295 } 15296 clearExternalStorageDataSync(packageName, userId, true); 15297 if (succeeded) { 15298 // invoke DeviceStorageMonitor's update method to clear any notifications 15299 DeviceStorageMonitorInternal dsm = LocalServices 15300 .getService(DeviceStorageMonitorInternal.class); 15301 if (dsm != null) { 15302 dsm.checkMemory(); 15303 } 15304 } 15305 if(observer != null) { 15306 try { 15307 observer.onRemoveCompleted(packageName, succeeded); 15308 } catch (RemoteException e) { 15309 Log.i(TAG, "Observer no longer exists."); 15310 } 15311 } //end if observer 15312 } //end run 15313 }); 15314 } 15315 15316 private boolean clearApplicationUserDataLI(String packageName, int userId) { 15317 if (packageName == null) { 15318 Slog.w(TAG, "Attempt to delete null packageName."); 15319 return false; 15320 } 15321 15322 // Try finding details about the requested package 15323 PackageParser.Package pkg; 15324 synchronized (mPackages) { 15325 pkg = mPackages.get(packageName); 15326 if (pkg == null) { 15327 final PackageSetting ps = mSettings.mPackages.get(packageName); 15328 if (ps != null) { 15329 pkg = ps.pkg; 15330 } 15331 } 15332 15333 if (pkg == null) { 15334 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15335 return false; 15336 } 15337 15338 PackageSetting ps = (PackageSetting) pkg.mExtras; 15339 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15340 } 15341 15342 // Always delete data directories for package, even if we found no other 15343 // record of app. This helps users recover from UID mismatches without 15344 // resorting to a full data wipe. 15345 // TODO: triage flags as part of 26466827 15346 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15347 try { 15348 mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags); 15349 } catch (InstallerException e) { 15350 Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e); 15351 return false; 15352 } 15353 15354 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15355 removeKeystoreDataIfNeeded(userId, appId); 15356 15357 // Create a native library symlink only if we have native libraries 15358 // and if the native libraries are 32 bit libraries. We do not provide 15359 // this symlink for 64 bit libraries. 15360 if (pkg.applicationInfo.primaryCpuAbi != null && 15361 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 15362 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 15363 try { 15364 mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 15365 nativeLibPath, userId); 15366 } catch (InstallerException e) { 15367 Slog.w(TAG, "Failed linking native library dir", e); 15368 return false; 15369 } 15370 } 15371 15372 return true; 15373 } 15374 15375 /** 15376 * Reverts user permission state changes (permissions and flags) in 15377 * all packages for a given user. 15378 * 15379 * @param userId The device user for which to do a reset. 15380 */ 15381 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 15382 final int packageCount = mPackages.size(); 15383 for (int i = 0; i < packageCount; i++) { 15384 PackageParser.Package pkg = mPackages.valueAt(i); 15385 PackageSetting ps = (PackageSetting) pkg.mExtras; 15386 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15387 } 15388 } 15389 15390 /** 15391 * Reverts user permission state changes (permissions and flags). 15392 * 15393 * @param ps The package for which to reset. 15394 * @param userId The device user for which to do a reset. 15395 */ 15396 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 15397 final PackageSetting ps, final int userId) { 15398 if (ps.pkg == null) { 15399 return; 15400 } 15401 15402 // These are flags that can change base on user actions. 15403 final int userSettableMask = FLAG_PERMISSION_USER_SET 15404 | FLAG_PERMISSION_USER_FIXED 15405 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 15406 | FLAG_PERMISSION_REVIEW_REQUIRED; 15407 15408 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 15409 | FLAG_PERMISSION_POLICY_FIXED; 15410 15411 boolean writeInstallPermissions = false; 15412 boolean writeRuntimePermissions = false; 15413 15414 final int permissionCount = ps.pkg.requestedPermissions.size(); 15415 for (int i = 0; i < permissionCount; i++) { 15416 String permission = ps.pkg.requestedPermissions.get(i); 15417 15418 BasePermission bp = mSettings.mPermissions.get(permission); 15419 if (bp == null) { 15420 continue; 15421 } 15422 15423 // If shared user we just reset the state to which only this app contributed. 15424 if (ps.sharedUser != null) { 15425 boolean used = false; 15426 final int packageCount = ps.sharedUser.packages.size(); 15427 for (int j = 0; j < packageCount; j++) { 15428 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 15429 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 15430 && pkg.pkg.requestedPermissions.contains(permission)) { 15431 used = true; 15432 break; 15433 } 15434 } 15435 if (used) { 15436 continue; 15437 } 15438 } 15439 15440 PermissionsState permissionsState = ps.getPermissionsState(); 15441 15442 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 15443 15444 // Always clear the user settable flags. 15445 final boolean hasInstallState = permissionsState.getInstallPermissionState( 15446 bp.name) != null; 15447 // If permission review is enabled and this is a legacy app, mark the 15448 // permission as requiring a review as this is the initial state. 15449 int flags = 0; 15450 if (Build.PERMISSIONS_REVIEW_REQUIRED 15451 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 15452 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 15453 } 15454 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 15455 if (hasInstallState) { 15456 writeInstallPermissions = true; 15457 } else { 15458 writeRuntimePermissions = true; 15459 } 15460 } 15461 15462 // Below is only runtime permission handling. 15463 if (!bp.isRuntime()) { 15464 continue; 15465 } 15466 15467 // Never clobber system or policy. 15468 if ((oldFlags & policyOrSystemFlags) != 0) { 15469 continue; 15470 } 15471 15472 // If this permission was granted by default, make sure it is. 15473 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 15474 if (permissionsState.grantRuntimePermission(bp, userId) 15475 != PERMISSION_OPERATION_FAILURE) { 15476 writeRuntimePermissions = true; 15477 } 15478 // If permission review is enabled the permissions for a legacy apps 15479 // are represented as constantly granted runtime ones, so don't revoke. 15480 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 15481 // Otherwise, reset the permission. 15482 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 15483 switch (revokeResult) { 15484 case PERMISSION_OPERATION_SUCCESS: { 15485 writeRuntimePermissions = true; 15486 } break; 15487 15488 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 15489 writeRuntimePermissions = true; 15490 final int appId = ps.appId; 15491 mHandler.post(new Runnable() { 15492 @Override 15493 public void run() { 15494 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 15495 } 15496 }); 15497 } break; 15498 } 15499 } 15500 } 15501 15502 // Synchronously write as we are taking permissions away. 15503 if (writeRuntimePermissions) { 15504 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 15505 } 15506 15507 // Synchronously write as we are taking permissions away. 15508 if (writeInstallPermissions) { 15509 mSettings.writeLPr(); 15510 } 15511 } 15512 15513 /** 15514 * Remove entries from the keystore daemon. Will only remove it if the 15515 * {@code appId} is valid. 15516 */ 15517 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 15518 if (appId < 0) { 15519 return; 15520 } 15521 15522 final KeyStore keyStore = KeyStore.getInstance(); 15523 if (keyStore != null) { 15524 if (userId == UserHandle.USER_ALL) { 15525 for (final int individual : sUserManager.getUserIds()) { 15526 keyStore.clearUid(UserHandle.getUid(individual, appId)); 15527 } 15528 } else { 15529 keyStore.clearUid(UserHandle.getUid(userId, appId)); 15530 } 15531 } else { 15532 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 15533 } 15534 } 15535 15536 @Override 15537 public void deleteApplicationCacheFiles(final String packageName, 15538 final IPackageDataObserver observer) { 15539 mContext.enforceCallingOrSelfPermission( 15540 android.Manifest.permission.DELETE_CACHE_FILES, null); 15541 // Queue up an async operation since the package deletion may take a little while. 15542 final int userId = UserHandle.getCallingUserId(); 15543 mHandler.post(new Runnable() { 15544 public void run() { 15545 mHandler.removeCallbacks(this); 15546 final boolean succeded; 15547 synchronized (mInstallLock) { 15548 succeded = deleteApplicationCacheFilesLI(packageName, userId); 15549 } 15550 clearExternalStorageDataSync(packageName, userId, false); 15551 if (observer != null) { 15552 try { 15553 observer.onRemoveCompleted(packageName, succeded); 15554 } catch (RemoteException e) { 15555 Log.i(TAG, "Observer no longer exists."); 15556 } 15557 } //end if observer 15558 } //end run 15559 }); 15560 } 15561 15562 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 15563 if (packageName == null) { 15564 Slog.w(TAG, "Attempt to delete null packageName."); 15565 return false; 15566 } 15567 PackageParser.Package p; 15568 synchronized (mPackages) { 15569 p = mPackages.get(packageName); 15570 } 15571 if (p == null) { 15572 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 15573 return false; 15574 } 15575 final ApplicationInfo applicationInfo = p.applicationInfo; 15576 if (applicationInfo == null) { 15577 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 15578 return false; 15579 } 15580 // TODO: triage flags as part of 26466827 15581 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15582 try { 15583 mInstaller.clearAppData(p.volumeUuid, packageName, userId, 15584 flags | Installer.FLAG_CLEAR_CACHE_ONLY); 15585 } catch (InstallerException e) { 15586 Slog.w(TAG, "Couldn't remove cache files for package " 15587 + packageName + " u" + userId, e); 15588 return false; 15589 } 15590 return true; 15591 } 15592 15593 @Override 15594 public void getPackageSizeInfo(final String packageName, int userHandle, 15595 final IPackageStatsObserver observer) { 15596 mContext.enforceCallingOrSelfPermission( 15597 android.Manifest.permission.GET_PACKAGE_SIZE, null); 15598 if (packageName == null) { 15599 throw new IllegalArgumentException("Attempt to get size of null packageName"); 15600 } 15601 15602 PackageStats stats = new PackageStats(packageName, userHandle); 15603 15604 /* 15605 * Queue up an async operation since the package measurement may take a 15606 * little while. 15607 */ 15608 Message msg = mHandler.obtainMessage(INIT_COPY); 15609 msg.obj = new MeasureParams(stats, observer); 15610 mHandler.sendMessage(msg); 15611 } 15612 15613 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 15614 PackageStats pStats) { 15615 if (packageName == null) { 15616 Slog.w(TAG, "Attempt to get size of null packageName."); 15617 return false; 15618 } 15619 PackageParser.Package p; 15620 boolean dataOnly = false; 15621 String libDirRoot = null; 15622 String asecPath = null; 15623 PackageSetting ps = null; 15624 synchronized (mPackages) { 15625 p = mPackages.get(packageName); 15626 ps = mSettings.mPackages.get(packageName); 15627 if(p == null) { 15628 dataOnly = true; 15629 if((ps == null) || (ps.pkg == null)) { 15630 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 15631 return false; 15632 } 15633 p = ps.pkg; 15634 } 15635 if (ps != null) { 15636 libDirRoot = ps.legacyNativeLibraryPathString; 15637 } 15638 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 15639 final long token = Binder.clearCallingIdentity(); 15640 try { 15641 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 15642 if (secureContainerId != null) { 15643 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 15644 } 15645 } finally { 15646 Binder.restoreCallingIdentity(token); 15647 } 15648 } 15649 } 15650 String publicSrcDir = null; 15651 if(!dataOnly) { 15652 final ApplicationInfo applicationInfo = p.applicationInfo; 15653 if (applicationInfo == null) { 15654 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 15655 return false; 15656 } 15657 if (p.isForwardLocked()) { 15658 publicSrcDir = applicationInfo.getBaseResourcePath(); 15659 } 15660 } 15661 // TODO: extend to measure size of split APKs 15662 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 15663 // not just the first level. 15664 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 15665 // just the primary. 15666 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 15667 15668 String apkPath; 15669 File packageDir = new File(p.codePath); 15670 15671 if (packageDir.isDirectory() && p.canHaveOatDir()) { 15672 apkPath = packageDir.getAbsolutePath(); 15673 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 15674 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 15675 libDirRoot = null; 15676 } 15677 } else { 15678 apkPath = p.baseCodePath; 15679 } 15680 15681 // TODO: triage flags as part of 26466827 15682 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15683 try { 15684 mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath, 15685 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 15686 } catch (InstallerException e) { 15687 return false; 15688 } 15689 15690 // Fix-up for forward-locked applications in ASEC containers. 15691 if (!isExternal(p)) { 15692 pStats.codeSize += pStats.externalCodeSize; 15693 pStats.externalCodeSize = 0L; 15694 } 15695 15696 return true; 15697 } 15698 15699 private int getUidTargetSdkVersionLockedLPr(int uid) { 15700 Object obj = mSettings.getUserIdLPr(uid); 15701 if (obj instanceof SharedUserSetting) { 15702 final SharedUserSetting sus = (SharedUserSetting) obj; 15703 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 15704 final Iterator<PackageSetting> it = sus.packages.iterator(); 15705 while (it.hasNext()) { 15706 final PackageSetting ps = it.next(); 15707 if (ps.pkg != null) { 15708 int v = ps.pkg.applicationInfo.targetSdkVersion; 15709 if (v < vers) vers = v; 15710 } 15711 } 15712 return vers; 15713 } else if (obj instanceof PackageSetting) { 15714 final PackageSetting ps = (PackageSetting) obj; 15715 if (ps.pkg != null) { 15716 return ps.pkg.applicationInfo.targetSdkVersion; 15717 } 15718 } 15719 return Build.VERSION_CODES.CUR_DEVELOPMENT; 15720 } 15721 15722 @Override 15723 public void addPreferredActivity(IntentFilter filter, int match, 15724 ComponentName[] set, ComponentName activity, int userId) { 15725 addPreferredActivityInternal(filter, match, set, activity, true, userId, 15726 "Adding preferred"); 15727 } 15728 15729 private void addPreferredActivityInternal(IntentFilter filter, int match, 15730 ComponentName[] set, ComponentName activity, boolean always, int userId, 15731 String opname) { 15732 // writer 15733 int callingUid = Binder.getCallingUid(); 15734 enforceCrossUserPermission(callingUid, userId, 15735 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 15736 if (filter.countActions() == 0) { 15737 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 15738 return; 15739 } 15740 synchronized (mPackages) { 15741 if (mContext.checkCallingOrSelfPermission( 15742 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15743 != PackageManager.PERMISSION_GRANTED) { 15744 if (getUidTargetSdkVersionLockedLPr(callingUid) 15745 < Build.VERSION_CODES.FROYO) { 15746 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 15747 + callingUid); 15748 return; 15749 } 15750 mContext.enforceCallingOrSelfPermission( 15751 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15752 } 15753 15754 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 15755 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 15756 + userId + ":"); 15757 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15758 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 15759 scheduleWritePackageRestrictionsLocked(userId); 15760 } 15761 } 15762 15763 @Override 15764 public void replacePreferredActivity(IntentFilter filter, int match, 15765 ComponentName[] set, ComponentName activity, int userId) { 15766 if (filter.countActions() != 1) { 15767 throw new IllegalArgumentException( 15768 "replacePreferredActivity expects filter to have only 1 action."); 15769 } 15770 if (filter.countDataAuthorities() != 0 15771 || filter.countDataPaths() != 0 15772 || filter.countDataSchemes() > 1 15773 || filter.countDataTypes() != 0) { 15774 throw new IllegalArgumentException( 15775 "replacePreferredActivity expects filter to have no data authorities, " + 15776 "paths, or types; and at most one scheme."); 15777 } 15778 15779 final int callingUid = Binder.getCallingUid(); 15780 enforceCrossUserPermission(callingUid, userId, 15781 true /* requireFullPermission */, false /* checkShell */, 15782 "replace preferred activity"); 15783 synchronized (mPackages) { 15784 if (mContext.checkCallingOrSelfPermission( 15785 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15786 != PackageManager.PERMISSION_GRANTED) { 15787 if (getUidTargetSdkVersionLockedLPr(callingUid) 15788 < Build.VERSION_CODES.FROYO) { 15789 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 15790 + Binder.getCallingUid()); 15791 return; 15792 } 15793 mContext.enforceCallingOrSelfPermission( 15794 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15795 } 15796 15797 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 15798 if (pir != null) { 15799 // Get all of the existing entries that exactly match this filter. 15800 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 15801 if (existing != null && existing.size() == 1) { 15802 PreferredActivity cur = existing.get(0); 15803 if (DEBUG_PREFERRED) { 15804 Slog.i(TAG, "Checking replace of preferred:"); 15805 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15806 if (!cur.mPref.mAlways) { 15807 Slog.i(TAG, " -- CUR; not mAlways!"); 15808 } else { 15809 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 15810 Slog.i(TAG, " -- CUR: mSet=" 15811 + Arrays.toString(cur.mPref.mSetComponents)); 15812 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 15813 Slog.i(TAG, " -- NEW: mMatch=" 15814 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 15815 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 15816 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 15817 } 15818 } 15819 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 15820 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 15821 && cur.mPref.sameSet(set)) { 15822 // Setting the preferred activity to what it happens to be already 15823 if (DEBUG_PREFERRED) { 15824 Slog.i(TAG, "Replacing with same preferred activity " 15825 + cur.mPref.mShortComponent + " for user " 15826 + userId + ":"); 15827 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15828 } 15829 return; 15830 } 15831 } 15832 15833 if (existing != null) { 15834 if (DEBUG_PREFERRED) { 15835 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 15836 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15837 } 15838 for (int i = 0; i < existing.size(); i++) { 15839 PreferredActivity pa = existing.get(i); 15840 if (DEBUG_PREFERRED) { 15841 Slog.i(TAG, "Removing existing preferred activity " 15842 + pa.mPref.mComponent + ":"); 15843 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 15844 } 15845 pir.removeFilter(pa); 15846 } 15847 } 15848 } 15849 addPreferredActivityInternal(filter, match, set, activity, true, userId, 15850 "Replacing preferred"); 15851 } 15852 } 15853 15854 @Override 15855 public void clearPackagePreferredActivities(String packageName) { 15856 final int uid = Binder.getCallingUid(); 15857 // writer 15858 synchronized (mPackages) { 15859 PackageParser.Package pkg = mPackages.get(packageName); 15860 if (pkg == null || pkg.applicationInfo.uid != uid) { 15861 if (mContext.checkCallingOrSelfPermission( 15862 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15863 != PackageManager.PERMISSION_GRANTED) { 15864 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 15865 < Build.VERSION_CODES.FROYO) { 15866 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 15867 + Binder.getCallingUid()); 15868 return; 15869 } 15870 mContext.enforceCallingOrSelfPermission( 15871 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15872 } 15873 } 15874 15875 int user = UserHandle.getCallingUserId(); 15876 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 15877 scheduleWritePackageRestrictionsLocked(user); 15878 } 15879 } 15880 } 15881 15882 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15883 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 15884 ArrayList<PreferredActivity> removed = null; 15885 boolean changed = false; 15886 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15887 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 15888 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15889 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 15890 continue; 15891 } 15892 Iterator<PreferredActivity> it = pir.filterIterator(); 15893 while (it.hasNext()) { 15894 PreferredActivity pa = it.next(); 15895 // Mark entry for removal only if it matches the package name 15896 // and the entry is of type "always". 15897 if (packageName == null || 15898 (pa.mPref.mComponent.getPackageName().equals(packageName) 15899 && pa.mPref.mAlways)) { 15900 if (removed == null) { 15901 removed = new ArrayList<PreferredActivity>(); 15902 } 15903 removed.add(pa); 15904 } 15905 } 15906 if (removed != null) { 15907 for (int j=0; j<removed.size(); j++) { 15908 PreferredActivity pa = removed.get(j); 15909 pir.removeFilter(pa); 15910 } 15911 changed = true; 15912 } 15913 } 15914 return changed; 15915 } 15916 15917 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15918 private void clearIntentFilterVerificationsLPw(int userId) { 15919 final int packageCount = mPackages.size(); 15920 for (int i = 0; i < packageCount; i++) { 15921 PackageParser.Package pkg = mPackages.valueAt(i); 15922 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 15923 } 15924 } 15925 15926 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15927 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 15928 if (userId == UserHandle.USER_ALL) { 15929 if (mSettings.removeIntentFilterVerificationLPw(packageName, 15930 sUserManager.getUserIds())) { 15931 for (int oneUserId : sUserManager.getUserIds()) { 15932 scheduleWritePackageRestrictionsLocked(oneUserId); 15933 } 15934 } 15935 } else { 15936 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 15937 scheduleWritePackageRestrictionsLocked(userId); 15938 } 15939 } 15940 } 15941 15942 void clearDefaultBrowserIfNeeded(String packageName) { 15943 for (int oneUserId : sUserManager.getUserIds()) { 15944 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 15945 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 15946 if (packageName.equals(defaultBrowserPackageName)) { 15947 setDefaultBrowserPackageName(null, oneUserId); 15948 } 15949 } 15950 } 15951 15952 @Override 15953 public void resetApplicationPreferences(int userId) { 15954 mContext.enforceCallingOrSelfPermission( 15955 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15956 // writer 15957 synchronized (mPackages) { 15958 final long identity = Binder.clearCallingIdentity(); 15959 try { 15960 clearPackagePreferredActivitiesLPw(null, userId); 15961 mSettings.applyDefaultPreferredAppsLPw(this, userId); 15962 // TODO: We have to reset the default SMS and Phone. This requires 15963 // significant refactoring to keep all default apps in the package 15964 // manager (cleaner but more work) or have the services provide 15965 // callbacks to the package manager to request a default app reset. 15966 applyFactoryDefaultBrowserLPw(userId); 15967 clearIntentFilterVerificationsLPw(userId); 15968 primeDomainVerificationsLPw(userId); 15969 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 15970 scheduleWritePackageRestrictionsLocked(userId); 15971 } finally { 15972 Binder.restoreCallingIdentity(identity); 15973 } 15974 } 15975 } 15976 15977 @Override 15978 public int getPreferredActivities(List<IntentFilter> outFilters, 15979 List<ComponentName> outActivities, String packageName) { 15980 15981 int num = 0; 15982 final int userId = UserHandle.getCallingUserId(); 15983 // reader 15984 synchronized (mPackages) { 15985 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 15986 if (pir != null) { 15987 final Iterator<PreferredActivity> it = pir.filterIterator(); 15988 while (it.hasNext()) { 15989 final PreferredActivity pa = it.next(); 15990 if (packageName == null 15991 || (pa.mPref.mComponent.getPackageName().equals(packageName) 15992 && pa.mPref.mAlways)) { 15993 if (outFilters != null) { 15994 outFilters.add(new IntentFilter(pa)); 15995 } 15996 if (outActivities != null) { 15997 outActivities.add(pa.mPref.mComponent); 15998 } 15999 } 16000 } 16001 } 16002 } 16003 16004 return num; 16005 } 16006 16007 @Override 16008 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16009 int userId) { 16010 int callingUid = Binder.getCallingUid(); 16011 if (callingUid != Process.SYSTEM_UID) { 16012 throw new SecurityException( 16013 "addPersistentPreferredActivity can only be run by the system"); 16014 } 16015 if (filter.countActions() == 0) { 16016 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16017 return; 16018 } 16019 synchronized (mPackages) { 16020 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16021 ":"); 16022 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16023 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16024 new PersistentPreferredActivity(filter, activity)); 16025 scheduleWritePackageRestrictionsLocked(userId); 16026 } 16027 } 16028 16029 @Override 16030 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16031 int callingUid = Binder.getCallingUid(); 16032 if (callingUid != Process.SYSTEM_UID) { 16033 throw new SecurityException( 16034 "clearPackagePersistentPreferredActivities can only be run by the system"); 16035 } 16036 ArrayList<PersistentPreferredActivity> removed = null; 16037 boolean changed = false; 16038 synchronized (mPackages) { 16039 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16040 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16041 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16042 .valueAt(i); 16043 if (userId != thisUserId) { 16044 continue; 16045 } 16046 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16047 while (it.hasNext()) { 16048 PersistentPreferredActivity ppa = it.next(); 16049 // Mark entry for removal only if it matches the package name. 16050 if (ppa.mComponent.getPackageName().equals(packageName)) { 16051 if (removed == null) { 16052 removed = new ArrayList<PersistentPreferredActivity>(); 16053 } 16054 removed.add(ppa); 16055 } 16056 } 16057 if (removed != null) { 16058 for (int j=0; j<removed.size(); j++) { 16059 PersistentPreferredActivity ppa = removed.get(j); 16060 ppir.removeFilter(ppa); 16061 } 16062 changed = true; 16063 } 16064 } 16065 16066 if (changed) { 16067 scheduleWritePackageRestrictionsLocked(userId); 16068 } 16069 } 16070 } 16071 16072 /** 16073 * Common machinery for picking apart a restored XML blob and passing 16074 * it to a caller-supplied functor to be applied to the running system. 16075 */ 16076 private void restoreFromXml(XmlPullParser parser, int userId, 16077 String expectedStartTag, BlobXmlRestorer functor) 16078 throws IOException, XmlPullParserException { 16079 int type; 16080 while ((type = parser.next()) != XmlPullParser.START_TAG 16081 && type != XmlPullParser.END_DOCUMENT) { 16082 } 16083 if (type != XmlPullParser.START_TAG) { 16084 // oops didn't find a start tag?! 16085 if (DEBUG_BACKUP) { 16086 Slog.e(TAG, "Didn't find start tag during restore"); 16087 } 16088 return; 16089 } 16090Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16091 // this is supposed to be TAG_PREFERRED_BACKUP 16092 if (!expectedStartTag.equals(parser.getName())) { 16093 if (DEBUG_BACKUP) { 16094 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16095 } 16096 return; 16097 } 16098 16099 // skip interfering stuff, then we're aligned with the backing implementation 16100 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16101Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16102 functor.apply(parser, userId); 16103 } 16104 16105 private interface BlobXmlRestorer { 16106 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16107 } 16108 16109 /** 16110 * Non-Binder method, support for the backup/restore mechanism: write the 16111 * full set of preferred activities in its canonical XML format. Returns the 16112 * XML output as a byte array, or null if there is none. 16113 */ 16114 @Override 16115 public byte[] getPreferredActivityBackup(int userId) { 16116 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16117 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16118 } 16119 16120 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16121 try { 16122 final XmlSerializer serializer = new FastXmlSerializer(); 16123 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16124 serializer.startDocument(null, true); 16125 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16126 16127 synchronized (mPackages) { 16128 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16129 } 16130 16131 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16132 serializer.endDocument(); 16133 serializer.flush(); 16134 } catch (Exception e) { 16135 if (DEBUG_BACKUP) { 16136 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16137 } 16138 return null; 16139 } 16140 16141 return dataStream.toByteArray(); 16142 } 16143 16144 @Override 16145 public void restorePreferredActivities(byte[] backup, int userId) { 16146 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16147 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16148 } 16149 16150 try { 16151 final XmlPullParser parser = Xml.newPullParser(); 16152 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16153 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16154 new BlobXmlRestorer() { 16155 @Override 16156 public void apply(XmlPullParser parser, int userId) 16157 throws XmlPullParserException, IOException { 16158 synchronized (mPackages) { 16159 mSettings.readPreferredActivitiesLPw(parser, userId); 16160 } 16161 } 16162 } ); 16163 } catch (Exception e) { 16164 if (DEBUG_BACKUP) { 16165 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16166 } 16167 } 16168 } 16169 16170 /** 16171 * Non-Binder method, support for the backup/restore mechanism: write the 16172 * default browser (etc) settings in its canonical XML format. Returns the default 16173 * browser XML representation as a byte array, or null if there is none. 16174 */ 16175 @Override 16176 public byte[] getDefaultAppsBackup(int userId) { 16177 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16178 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 16179 } 16180 16181 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16182 try { 16183 final XmlSerializer serializer = new FastXmlSerializer(); 16184 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16185 serializer.startDocument(null, true); 16186 serializer.startTag(null, TAG_DEFAULT_APPS); 16187 16188 synchronized (mPackages) { 16189 mSettings.writeDefaultAppsLPr(serializer, userId); 16190 } 16191 16192 serializer.endTag(null, TAG_DEFAULT_APPS); 16193 serializer.endDocument(); 16194 serializer.flush(); 16195 } catch (Exception e) { 16196 if (DEBUG_BACKUP) { 16197 Slog.e(TAG, "Unable to write default apps for backup", e); 16198 } 16199 return null; 16200 } 16201 16202 return dataStream.toByteArray(); 16203 } 16204 16205 @Override 16206 public void restoreDefaultApps(byte[] backup, int userId) { 16207 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16208 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16209 } 16210 16211 try { 16212 final XmlPullParser parser = Xml.newPullParser(); 16213 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16214 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16215 new BlobXmlRestorer() { 16216 @Override 16217 public void apply(XmlPullParser parser, int userId) 16218 throws XmlPullParserException, IOException { 16219 synchronized (mPackages) { 16220 mSettings.readDefaultAppsLPw(parser, userId); 16221 } 16222 } 16223 } ); 16224 } catch (Exception e) { 16225 if (DEBUG_BACKUP) { 16226 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16227 } 16228 } 16229 } 16230 16231 @Override 16232 public byte[] getIntentFilterVerificationBackup(int userId) { 16233 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16234 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 16235 } 16236 16237 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16238 try { 16239 final XmlSerializer serializer = new FastXmlSerializer(); 16240 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16241 serializer.startDocument(null, true); 16242 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 16243 16244 synchronized (mPackages) { 16245 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 16246 } 16247 16248 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 16249 serializer.endDocument(); 16250 serializer.flush(); 16251 } catch (Exception e) { 16252 if (DEBUG_BACKUP) { 16253 Slog.e(TAG, "Unable to write default apps for backup", e); 16254 } 16255 return null; 16256 } 16257 16258 return dataStream.toByteArray(); 16259 } 16260 16261 @Override 16262 public void restoreIntentFilterVerification(byte[] backup, int userId) { 16263 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16264 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16265 } 16266 16267 try { 16268 final XmlPullParser parser = Xml.newPullParser(); 16269 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16270 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 16271 new BlobXmlRestorer() { 16272 @Override 16273 public void apply(XmlPullParser parser, int userId) 16274 throws XmlPullParserException, IOException { 16275 synchronized (mPackages) { 16276 mSettings.readAllDomainVerificationsLPr(parser, userId); 16277 mSettings.writeLPr(); 16278 } 16279 } 16280 } ); 16281 } catch (Exception e) { 16282 if (DEBUG_BACKUP) { 16283 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16284 } 16285 } 16286 } 16287 16288 @Override 16289 public byte[] getPermissionGrantBackup(int userId) { 16290 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16291 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 16292 } 16293 16294 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16295 try { 16296 final XmlSerializer serializer = new FastXmlSerializer(); 16297 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16298 serializer.startDocument(null, true); 16299 serializer.startTag(null, TAG_PERMISSION_BACKUP); 16300 16301 synchronized (mPackages) { 16302 serializeRuntimePermissionGrantsLPr(serializer, userId); 16303 } 16304 16305 serializer.endTag(null, TAG_PERMISSION_BACKUP); 16306 serializer.endDocument(); 16307 serializer.flush(); 16308 } catch (Exception e) { 16309 if (DEBUG_BACKUP) { 16310 Slog.e(TAG, "Unable to write default apps for backup", e); 16311 } 16312 return null; 16313 } 16314 16315 return dataStream.toByteArray(); 16316 } 16317 16318 @Override 16319 public void restorePermissionGrants(byte[] backup, int userId) { 16320 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16321 throw new SecurityException("Only the system may call restorePermissionGrants()"); 16322 } 16323 16324 try { 16325 final XmlPullParser parser = Xml.newPullParser(); 16326 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16327 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 16328 new BlobXmlRestorer() { 16329 @Override 16330 public void apply(XmlPullParser parser, int userId) 16331 throws XmlPullParserException, IOException { 16332 synchronized (mPackages) { 16333 processRestoredPermissionGrantsLPr(parser, userId); 16334 } 16335 } 16336 } ); 16337 } catch (Exception e) { 16338 if (DEBUG_BACKUP) { 16339 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16340 } 16341 } 16342 } 16343 16344 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 16345 throws IOException { 16346 serializer.startTag(null, TAG_ALL_GRANTS); 16347 16348 final int N = mSettings.mPackages.size(); 16349 for (int i = 0; i < N; i++) { 16350 final PackageSetting ps = mSettings.mPackages.valueAt(i); 16351 boolean pkgGrantsKnown = false; 16352 16353 PermissionsState packagePerms = ps.getPermissionsState(); 16354 16355 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 16356 final int grantFlags = state.getFlags(); 16357 // only look at grants that are not system/policy fixed 16358 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 16359 final boolean isGranted = state.isGranted(); 16360 // And only back up the user-twiddled state bits 16361 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 16362 final String packageName = mSettings.mPackages.keyAt(i); 16363 if (!pkgGrantsKnown) { 16364 serializer.startTag(null, TAG_GRANT); 16365 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 16366 pkgGrantsKnown = true; 16367 } 16368 16369 final boolean userSet = 16370 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 16371 final boolean userFixed = 16372 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 16373 final boolean revoke = 16374 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 16375 16376 serializer.startTag(null, TAG_PERMISSION); 16377 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 16378 if (isGranted) { 16379 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 16380 } 16381 if (userSet) { 16382 serializer.attribute(null, ATTR_USER_SET, "true"); 16383 } 16384 if (userFixed) { 16385 serializer.attribute(null, ATTR_USER_FIXED, "true"); 16386 } 16387 if (revoke) { 16388 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 16389 } 16390 serializer.endTag(null, TAG_PERMISSION); 16391 } 16392 } 16393 } 16394 16395 if (pkgGrantsKnown) { 16396 serializer.endTag(null, TAG_GRANT); 16397 } 16398 } 16399 16400 serializer.endTag(null, TAG_ALL_GRANTS); 16401 } 16402 16403 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 16404 throws XmlPullParserException, IOException { 16405 String pkgName = null; 16406 int outerDepth = parser.getDepth(); 16407 int type; 16408 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 16409 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 16410 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 16411 continue; 16412 } 16413 16414 final String tagName = parser.getName(); 16415 if (tagName.equals(TAG_GRANT)) { 16416 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 16417 if (DEBUG_BACKUP) { 16418 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 16419 } 16420 } else if (tagName.equals(TAG_PERMISSION)) { 16421 16422 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 16423 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 16424 16425 int newFlagSet = 0; 16426 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 16427 newFlagSet |= FLAG_PERMISSION_USER_SET; 16428 } 16429 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 16430 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 16431 } 16432 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 16433 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 16434 } 16435 if (DEBUG_BACKUP) { 16436 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 16437 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 16438 } 16439 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16440 if (ps != null) { 16441 // Already installed so we apply the grant immediately 16442 if (DEBUG_BACKUP) { 16443 Slog.v(TAG, " + already installed; applying"); 16444 } 16445 PermissionsState perms = ps.getPermissionsState(); 16446 BasePermission bp = mSettings.mPermissions.get(permName); 16447 if (bp != null) { 16448 if (isGranted) { 16449 perms.grantRuntimePermission(bp, userId); 16450 } 16451 if (newFlagSet != 0) { 16452 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 16453 } 16454 } 16455 } else { 16456 // Need to wait for post-restore install to apply the grant 16457 if (DEBUG_BACKUP) { 16458 Slog.v(TAG, " - not yet installed; saving for later"); 16459 } 16460 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 16461 isGranted, newFlagSet, userId); 16462 } 16463 } else { 16464 PackageManagerService.reportSettingsProblem(Log.WARN, 16465 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 16466 XmlUtils.skipCurrentTag(parser); 16467 } 16468 } 16469 16470 scheduleWriteSettingsLocked(); 16471 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16472 } 16473 16474 @Override 16475 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 16476 int sourceUserId, int targetUserId, int flags) { 16477 mContext.enforceCallingOrSelfPermission( 16478 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16479 int callingUid = Binder.getCallingUid(); 16480 enforceOwnerRights(ownerPackage, callingUid); 16481 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16482 if (intentFilter.countActions() == 0) { 16483 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 16484 return; 16485 } 16486 synchronized (mPackages) { 16487 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 16488 ownerPackage, targetUserId, flags); 16489 CrossProfileIntentResolver resolver = 16490 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16491 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 16492 // We have all those whose filter is equal. Now checking if the rest is equal as well. 16493 if (existing != null) { 16494 int size = existing.size(); 16495 for (int i = 0; i < size; i++) { 16496 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 16497 return; 16498 } 16499 } 16500 } 16501 resolver.addFilter(newFilter); 16502 scheduleWritePackageRestrictionsLocked(sourceUserId); 16503 } 16504 } 16505 16506 @Override 16507 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 16508 mContext.enforceCallingOrSelfPermission( 16509 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16510 int callingUid = Binder.getCallingUid(); 16511 enforceOwnerRights(ownerPackage, callingUid); 16512 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16513 synchronized (mPackages) { 16514 CrossProfileIntentResolver resolver = 16515 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16516 ArraySet<CrossProfileIntentFilter> set = 16517 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 16518 for (CrossProfileIntentFilter filter : set) { 16519 if (filter.getOwnerPackage().equals(ownerPackage)) { 16520 resolver.removeFilter(filter); 16521 } 16522 } 16523 scheduleWritePackageRestrictionsLocked(sourceUserId); 16524 } 16525 } 16526 16527 // Enforcing that callingUid is owning pkg on userId 16528 private void enforceOwnerRights(String pkg, int callingUid) { 16529 // The system owns everything. 16530 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 16531 return; 16532 } 16533 int callingUserId = UserHandle.getUserId(callingUid); 16534 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 16535 if (pi == null) { 16536 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 16537 + callingUserId); 16538 } 16539 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 16540 throw new SecurityException("Calling uid " + callingUid 16541 + " does not own package " + pkg); 16542 } 16543 } 16544 16545 @Override 16546 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 16547 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 16548 } 16549 16550 private Intent getHomeIntent() { 16551 Intent intent = new Intent(Intent.ACTION_MAIN); 16552 intent.addCategory(Intent.CATEGORY_HOME); 16553 return intent; 16554 } 16555 16556 private IntentFilter getHomeFilter() { 16557 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 16558 filter.addCategory(Intent.CATEGORY_HOME); 16559 filter.addCategory(Intent.CATEGORY_DEFAULT); 16560 return filter; 16561 } 16562 16563 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 16564 int userId) { 16565 Intent intent = getHomeIntent(); 16566 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 16567 PackageManager.GET_META_DATA, userId); 16568 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 16569 true, false, false, userId); 16570 16571 allHomeCandidates.clear(); 16572 if (list != null) { 16573 for (ResolveInfo ri : list) { 16574 allHomeCandidates.add(ri); 16575 } 16576 } 16577 return (preferred == null || preferred.activityInfo == null) 16578 ? null 16579 : new ComponentName(preferred.activityInfo.packageName, 16580 preferred.activityInfo.name); 16581 } 16582 16583 @Override 16584 public void setHomeActivity(ComponentName comp, int userId) { 16585 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 16586 getHomeActivitiesAsUser(homeActivities, userId); 16587 16588 boolean found = false; 16589 16590 final int size = homeActivities.size(); 16591 final ComponentName[] set = new ComponentName[size]; 16592 for (int i = 0; i < size; i++) { 16593 final ResolveInfo candidate = homeActivities.get(i); 16594 final ActivityInfo info = candidate.activityInfo; 16595 final ComponentName activityName = new ComponentName(info.packageName, info.name); 16596 set[i] = activityName; 16597 if (!found && activityName.equals(comp)) { 16598 found = true; 16599 } 16600 } 16601 if (!found) { 16602 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 16603 + userId); 16604 } 16605 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 16606 set, comp, userId); 16607 } 16608 16609 @Override 16610 public void setApplicationEnabledSetting(String appPackageName, 16611 int newState, int flags, int userId, String callingPackage) { 16612 if (!sUserManager.exists(userId)) return; 16613 if (callingPackage == null) { 16614 callingPackage = Integer.toString(Binder.getCallingUid()); 16615 } 16616 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 16617 } 16618 16619 @Override 16620 public void setComponentEnabledSetting(ComponentName componentName, 16621 int newState, int flags, int userId) { 16622 if (!sUserManager.exists(userId)) return; 16623 setEnabledSetting(componentName.getPackageName(), 16624 componentName.getClassName(), newState, flags, userId, null); 16625 } 16626 16627 private void setEnabledSetting(final String packageName, String className, int newState, 16628 final int flags, int userId, String callingPackage) { 16629 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 16630 || newState == COMPONENT_ENABLED_STATE_ENABLED 16631 || newState == COMPONENT_ENABLED_STATE_DISABLED 16632 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 16633 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 16634 throw new IllegalArgumentException("Invalid new component state: " 16635 + newState); 16636 } 16637 PackageSetting pkgSetting; 16638 final int uid = Binder.getCallingUid(); 16639 final int permission = mContext.checkCallingOrSelfPermission( 16640 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 16641 enforceCrossUserPermission(uid, userId, 16642 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 16643 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 16644 boolean sendNow = false; 16645 boolean isApp = (className == null); 16646 String componentName = isApp ? packageName : className; 16647 int packageUid = -1; 16648 ArrayList<String> components; 16649 16650 // writer 16651 synchronized (mPackages) { 16652 pkgSetting = mSettings.mPackages.get(packageName); 16653 if (pkgSetting == null) { 16654 if (className == null) { 16655 throw new IllegalArgumentException("Unknown package: " + packageName); 16656 } 16657 throw new IllegalArgumentException( 16658 "Unknown component: " + packageName + "/" + className); 16659 } 16660 // Allow root and verify that userId is not being specified by a different user 16661 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 16662 throw new SecurityException( 16663 "Permission Denial: attempt to change component state from pid=" 16664 + Binder.getCallingPid() 16665 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 16666 } 16667 if (className == null) { 16668 // We're dealing with an application/package level state change 16669 if (pkgSetting.getEnabled(userId) == newState) { 16670 // Nothing to do 16671 return; 16672 } 16673 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 16674 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 16675 // Don't care about who enables an app. 16676 callingPackage = null; 16677 } 16678 pkgSetting.setEnabled(newState, userId, callingPackage); 16679 // pkgSetting.pkg.mSetEnabled = newState; 16680 } else { 16681 // We're dealing with a component level state change 16682 // First, verify that this is a valid class name. 16683 PackageParser.Package pkg = pkgSetting.pkg; 16684 if (pkg == null || !pkg.hasComponentClassName(className)) { 16685 if (pkg != null && 16686 pkg.applicationInfo.targetSdkVersion >= 16687 Build.VERSION_CODES.JELLY_BEAN) { 16688 throw new IllegalArgumentException("Component class " + className 16689 + " does not exist in " + packageName); 16690 } else { 16691 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 16692 + className + " does not exist in " + packageName); 16693 } 16694 } 16695 switch (newState) { 16696 case COMPONENT_ENABLED_STATE_ENABLED: 16697 if (!pkgSetting.enableComponentLPw(className, userId)) { 16698 return; 16699 } 16700 break; 16701 case COMPONENT_ENABLED_STATE_DISABLED: 16702 if (!pkgSetting.disableComponentLPw(className, userId)) { 16703 return; 16704 } 16705 break; 16706 case COMPONENT_ENABLED_STATE_DEFAULT: 16707 if (!pkgSetting.restoreComponentLPw(className, userId)) { 16708 return; 16709 } 16710 break; 16711 default: 16712 Slog.e(TAG, "Invalid new component state: " + newState); 16713 return; 16714 } 16715 } 16716 scheduleWritePackageRestrictionsLocked(userId); 16717 components = mPendingBroadcasts.get(userId, packageName); 16718 final boolean newPackage = components == null; 16719 if (newPackage) { 16720 components = new ArrayList<String>(); 16721 } 16722 if (!components.contains(componentName)) { 16723 components.add(componentName); 16724 } 16725 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 16726 sendNow = true; 16727 // Purge entry from pending broadcast list if another one exists already 16728 // since we are sending one right away. 16729 mPendingBroadcasts.remove(userId, packageName); 16730 } else { 16731 if (newPackage) { 16732 mPendingBroadcasts.put(userId, packageName, components); 16733 } 16734 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 16735 // Schedule a message 16736 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 16737 } 16738 } 16739 } 16740 16741 long callingId = Binder.clearCallingIdentity(); 16742 try { 16743 if (sendNow) { 16744 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 16745 sendPackageChangedBroadcast(packageName, 16746 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 16747 } 16748 } finally { 16749 Binder.restoreCallingIdentity(callingId); 16750 } 16751 } 16752 16753 @Override 16754 public void flushPackageRestrictionsAsUser(int userId) { 16755 if (!sUserManager.exists(userId)) { 16756 return; 16757 } 16758 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 16759 false /* checkShell */, "flushPackageRestrictions"); 16760 synchronized (mPackages) { 16761 mSettings.writePackageRestrictionsLPr(userId); 16762 mDirtyUsers.remove(userId); 16763 if (mDirtyUsers.isEmpty()) { 16764 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 16765 } 16766 } 16767 } 16768 16769 private void sendPackageChangedBroadcast(String packageName, 16770 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 16771 if (DEBUG_INSTALL) 16772 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 16773 + componentNames); 16774 Bundle extras = new Bundle(4); 16775 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 16776 String nameList[] = new String[componentNames.size()]; 16777 componentNames.toArray(nameList); 16778 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 16779 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 16780 extras.putInt(Intent.EXTRA_UID, packageUid); 16781 // If this is not reporting a change of the overall package, then only send it 16782 // to registered receivers. We don't want to launch a swath of apps for every 16783 // little component state change. 16784 final int flags = !componentNames.contains(packageName) 16785 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 16786 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 16787 new int[] {UserHandle.getUserId(packageUid)}); 16788 } 16789 16790 @Override 16791 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 16792 if (!sUserManager.exists(userId)) return; 16793 final int uid = Binder.getCallingUid(); 16794 final int permission = mContext.checkCallingOrSelfPermission( 16795 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 16796 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 16797 enforceCrossUserPermission(uid, userId, 16798 true /* requireFullPermission */, true /* checkShell */, "stop package"); 16799 // writer 16800 synchronized (mPackages) { 16801 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 16802 allowedByPermission, uid, userId)) { 16803 scheduleWritePackageRestrictionsLocked(userId); 16804 } 16805 } 16806 } 16807 16808 @Override 16809 public String getInstallerPackageName(String packageName) { 16810 // reader 16811 synchronized (mPackages) { 16812 return mSettings.getInstallerPackageNameLPr(packageName); 16813 } 16814 } 16815 16816 @Override 16817 public int getApplicationEnabledSetting(String packageName, int userId) { 16818 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 16819 int uid = Binder.getCallingUid(); 16820 enforceCrossUserPermission(uid, userId, 16821 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 16822 // reader 16823 synchronized (mPackages) { 16824 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 16825 } 16826 } 16827 16828 @Override 16829 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 16830 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 16831 int uid = Binder.getCallingUid(); 16832 enforceCrossUserPermission(uid, userId, 16833 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 16834 // reader 16835 synchronized (mPackages) { 16836 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 16837 } 16838 } 16839 16840 @Override 16841 public void enterSafeMode() { 16842 enforceSystemOrRoot("Only the system can request entering safe mode"); 16843 16844 if (!mSystemReady) { 16845 mSafeMode = true; 16846 } 16847 } 16848 16849 @Override 16850 public void systemReady() { 16851 mSystemReady = true; 16852 16853 // Read the compatibilty setting when the system is ready. 16854 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 16855 mContext.getContentResolver(), 16856 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 16857 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 16858 if (DEBUG_SETTINGS) { 16859 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 16860 } 16861 16862 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 16863 16864 synchronized (mPackages) { 16865 // Verify that all of the preferred activity components actually 16866 // exist. It is possible for applications to be updated and at 16867 // that point remove a previously declared activity component that 16868 // had been set as a preferred activity. We try to clean this up 16869 // the next time we encounter that preferred activity, but it is 16870 // possible for the user flow to never be able to return to that 16871 // situation so here we do a sanity check to make sure we haven't 16872 // left any junk around. 16873 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 16874 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16875 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16876 removed.clear(); 16877 for (PreferredActivity pa : pir.filterSet()) { 16878 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 16879 removed.add(pa); 16880 } 16881 } 16882 if (removed.size() > 0) { 16883 for (int r=0; r<removed.size(); r++) { 16884 PreferredActivity pa = removed.get(r); 16885 Slog.w(TAG, "Removing dangling preferred activity: " 16886 + pa.mPref.mComponent); 16887 pir.removeFilter(pa); 16888 } 16889 mSettings.writePackageRestrictionsLPr( 16890 mSettings.mPreferredActivities.keyAt(i)); 16891 } 16892 } 16893 16894 for (int userId : UserManagerService.getInstance().getUserIds()) { 16895 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 16896 grantPermissionsUserIds = ArrayUtils.appendInt( 16897 grantPermissionsUserIds, userId); 16898 } 16899 } 16900 } 16901 sUserManager.systemReady(); 16902 16903 // If we upgraded grant all default permissions before kicking off. 16904 for (int userId : grantPermissionsUserIds) { 16905 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 16906 } 16907 16908 // Kick off any messages waiting for system ready 16909 if (mPostSystemReadyMessages != null) { 16910 for (Message msg : mPostSystemReadyMessages) { 16911 msg.sendToTarget(); 16912 } 16913 mPostSystemReadyMessages = null; 16914 } 16915 16916 // Watch for external volumes that come and go over time 16917 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16918 storage.registerListener(mStorageListener); 16919 16920 mInstallerService.systemReady(); 16921 mPackageDexOptimizer.systemReady(); 16922 16923 MountServiceInternal mountServiceInternal = LocalServices.getService( 16924 MountServiceInternal.class); 16925 mountServiceInternal.addExternalStoragePolicy( 16926 new MountServiceInternal.ExternalStorageMountPolicy() { 16927 @Override 16928 public int getMountMode(int uid, String packageName) { 16929 if (Process.isIsolated(uid)) { 16930 return Zygote.MOUNT_EXTERNAL_NONE; 16931 } 16932 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 16933 return Zygote.MOUNT_EXTERNAL_DEFAULT; 16934 } 16935 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 16936 return Zygote.MOUNT_EXTERNAL_DEFAULT; 16937 } 16938 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 16939 return Zygote.MOUNT_EXTERNAL_READ; 16940 } 16941 return Zygote.MOUNT_EXTERNAL_WRITE; 16942 } 16943 16944 @Override 16945 public boolean hasExternalStorage(int uid, String packageName) { 16946 return true; 16947 } 16948 }); 16949 } 16950 16951 @Override 16952 public boolean isSafeMode() { 16953 return mSafeMode; 16954 } 16955 16956 @Override 16957 public boolean hasSystemUidErrors() { 16958 return mHasSystemUidErrors; 16959 } 16960 16961 static String arrayToString(int[] array) { 16962 StringBuffer buf = new StringBuffer(128); 16963 buf.append('['); 16964 if (array != null) { 16965 for (int i=0; i<array.length; i++) { 16966 if (i > 0) buf.append(", "); 16967 buf.append(array[i]); 16968 } 16969 } 16970 buf.append(']'); 16971 return buf.toString(); 16972 } 16973 16974 static class DumpState { 16975 public static final int DUMP_LIBS = 1 << 0; 16976 public static final int DUMP_FEATURES = 1 << 1; 16977 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 16978 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 16979 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 16980 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 16981 public static final int DUMP_PERMISSIONS = 1 << 6; 16982 public static final int DUMP_PACKAGES = 1 << 7; 16983 public static final int DUMP_SHARED_USERS = 1 << 8; 16984 public static final int DUMP_MESSAGES = 1 << 9; 16985 public static final int DUMP_PROVIDERS = 1 << 10; 16986 public static final int DUMP_VERIFIERS = 1 << 11; 16987 public static final int DUMP_PREFERRED = 1 << 12; 16988 public static final int DUMP_PREFERRED_XML = 1 << 13; 16989 public static final int DUMP_KEYSETS = 1 << 14; 16990 public static final int DUMP_VERSION = 1 << 15; 16991 public static final int DUMP_INSTALLS = 1 << 16; 16992 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 16993 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 16994 16995 public static final int OPTION_SHOW_FILTERS = 1 << 0; 16996 16997 private int mTypes; 16998 16999 private int mOptions; 17000 17001 private boolean mTitlePrinted; 17002 17003 private SharedUserSetting mSharedUser; 17004 17005 public boolean isDumping(int type) { 17006 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17007 return true; 17008 } 17009 17010 return (mTypes & type) != 0; 17011 } 17012 17013 public void setDump(int type) { 17014 mTypes |= type; 17015 } 17016 17017 public boolean isOptionEnabled(int option) { 17018 return (mOptions & option) != 0; 17019 } 17020 17021 public void setOptionEnabled(int option) { 17022 mOptions |= option; 17023 } 17024 17025 public boolean onTitlePrinted() { 17026 final boolean printed = mTitlePrinted; 17027 mTitlePrinted = true; 17028 return printed; 17029 } 17030 17031 public boolean getTitlePrinted() { 17032 return mTitlePrinted; 17033 } 17034 17035 public void setTitlePrinted(boolean enabled) { 17036 mTitlePrinted = enabled; 17037 } 17038 17039 public SharedUserSetting getSharedUser() { 17040 return mSharedUser; 17041 } 17042 17043 public void setSharedUser(SharedUserSetting user) { 17044 mSharedUser = user; 17045 } 17046 } 17047 17048 @Override 17049 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17050 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17051 (new PackageManagerShellCommand(this)).exec( 17052 this, in, out, err, args, resultReceiver); 17053 } 17054 17055 @Override 17056 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17057 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17058 != PackageManager.PERMISSION_GRANTED) { 17059 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17060 + Binder.getCallingPid() 17061 + ", uid=" + Binder.getCallingUid() 17062 + " without permission " 17063 + android.Manifest.permission.DUMP); 17064 return; 17065 } 17066 17067 DumpState dumpState = new DumpState(); 17068 boolean fullPreferred = false; 17069 boolean checkin = false; 17070 17071 String packageName = null; 17072 ArraySet<String> permissionNames = null; 17073 17074 int opti = 0; 17075 while (opti < args.length) { 17076 String opt = args[opti]; 17077 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 17078 break; 17079 } 17080 opti++; 17081 17082 if ("-a".equals(opt)) { 17083 // Right now we only know how to print all. 17084 } else if ("-h".equals(opt)) { 17085 pw.println("Package manager dump options:"); 17086 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 17087 pw.println(" --checkin: dump for a checkin"); 17088 pw.println(" -f: print details of intent filters"); 17089 pw.println(" -h: print this help"); 17090 pw.println(" cmd may be one of:"); 17091 pw.println(" l[ibraries]: list known shared libraries"); 17092 pw.println(" f[eatures]: list device features"); 17093 pw.println(" k[eysets]: print known keysets"); 17094 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 17095 pw.println(" perm[issions]: dump permissions"); 17096 pw.println(" permission [name ...]: dump declaration and use of given permission"); 17097 pw.println(" pref[erred]: print preferred package settings"); 17098 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 17099 pw.println(" prov[iders]: dump content providers"); 17100 pw.println(" p[ackages]: dump installed packages"); 17101 pw.println(" s[hared-users]: dump shared user IDs"); 17102 pw.println(" m[essages]: print collected runtime messages"); 17103 pw.println(" v[erifiers]: print package verifier info"); 17104 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 17105 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 17106 pw.println(" version: print database version info"); 17107 pw.println(" write: write current settings now"); 17108 pw.println(" installs: details about install sessions"); 17109 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 17110 pw.println(" <package.name>: info about given package"); 17111 return; 17112 } else if ("--checkin".equals(opt)) { 17113 checkin = true; 17114 } else if ("-f".equals(opt)) { 17115 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17116 } else { 17117 pw.println("Unknown argument: " + opt + "; use -h for help"); 17118 } 17119 } 17120 17121 // Is the caller requesting to dump a particular piece of data? 17122 if (opti < args.length) { 17123 String cmd = args[opti]; 17124 opti++; 17125 // Is this a package name? 17126 if ("android".equals(cmd) || cmd.contains(".")) { 17127 packageName = cmd; 17128 // When dumping a single package, we always dump all of its 17129 // filter information since the amount of data will be reasonable. 17130 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17131 } else if ("check-permission".equals(cmd)) { 17132 if (opti >= args.length) { 17133 pw.println("Error: check-permission missing permission argument"); 17134 return; 17135 } 17136 String perm = args[opti]; 17137 opti++; 17138 if (opti >= args.length) { 17139 pw.println("Error: check-permission missing package argument"); 17140 return; 17141 } 17142 String pkg = args[opti]; 17143 opti++; 17144 int user = UserHandle.getUserId(Binder.getCallingUid()); 17145 if (opti < args.length) { 17146 try { 17147 user = Integer.parseInt(args[opti]); 17148 } catch (NumberFormatException e) { 17149 pw.println("Error: check-permission user argument is not a number: " 17150 + args[opti]); 17151 return; 17152 } 17153 } 17154 pw.println(checkPermission(perm, pkg, user)); 17155 return; 17156 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 17157 dumpState.setDump(DumpState.DUMP_LIBS); 17158 } else if ("f".equals(cmd) || "features".equals(cmd)) { 17159 dumpState.setDump(DumpState.DUMP_FEATURES); 17160 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 17161 if (opti >= args.length) { 17162 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 17163 | DumpState.DUMP_SERVICE_RESOLVERS 17164 | DumpState.DUMP_RECEIVER_RESOLVERS 17165 | DumpState.DUMP_CONTENT_RESOLVERS); 17166 } else { 17167 while (opti < args.length) { 17168 String name = args[opti]; 17169 if ("a".equals(name) || "activity".equals(name)) { 17170 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 17171 } else if ("s".equals(name) || "service".equals(name)) { 17172 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 17173 } else if ("r".equals(name) || "receiver".equals(name)) { 17174 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 17175 } else if ("c".equals(name) || "content".equals(name)) { 17176 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 17177 } else { 17178 pw.println("Error: unknown resolver table type: " + name); 17179 return; 17180 } 17181 opti++; 17182 } 17183 } 17184 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 17185 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 17186 } else if ("permission".equals(cmd)) { 17187 if (opti >= args.length) { 17188 pw.println("Error: permission requires permission name"); 17189 return; 17190 } 17191 permissionNames = new ArraySet<>(); 17192 while (opti < args.length) { 17193 permissionNames.add(args[opti]); 17194 opti++; 17195 } 17196 dumpState.setDump(DumpState.DUMP_PERMISSIONS 17197 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 17198 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 17199 dumpState.setDump(DumpState.DUMP_PREFERRED); 17200 } else if ("preferred-xml".equals(cmd)) { 17201 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 17202 if (opti < args.length && "--full".equals(args[opti])) { 17203 fullPreferred = true; 17204 opti++; 17205 } 17206 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 17207 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 17208 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 17209 dumpState.setDump(DumpState.DUMP_PACKAGES); 17210 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 17211 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 17212 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 17213 dumpState.setDump(DumpState.DUMP_PROVIDERS); 17214 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 17215 dumpState.setDump(DumpState.DUMP_MESSAGES); 17216 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 17217 dumpState.setDump(DumpState.DUMP_VERIFIERS); 17218 } else if ("i".equals(cmd) || "ifv".equals(cmd) 17219 || "intent-filter-verifiers".equals(cmd)) { 17220 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 17221 } else if ("version".equals(cmd)) { 17222 dumpState.setDump(DumpState.DUMP_VERSION); 17223 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 17224 dumpState.setDump(DumpState.DUMP_KEYSETS); 17225 } else if ("installs".equals(cmd)) { 17226 dumpState.setDump(DumpState.DUMP_INSTALLS); 17227 } else if ("write".equals(cmd)) { 17228 synchronized (mPackages) { 17229 mSettings.writeLPr(); 17230 pw.println("Settings written."); 17231 return; 17232 } 17233 } 17234 } 17235 17236 if (checkin) { 17237 pw.println("vers,1"); 17238 } 17239 17240 // reader 17241 synchronized (mPackages) { 17242 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 17243 if (!checkin) { 17244 if (dumpState.onTitlePrinted()) 17245 pw.println(); 17246 pw.println("Database versions:"); 17247 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 17248 } 17249 } 17250 17251 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 17252 if (!checkin) { 17253 if (dumpState.onTitlePrinted()) 17254 pw.println(); 17255 pw.println("Verifiers:"); 17256 pw.print(" Required: "); 17257 pw.print(mRequiredVerifierPackage); 17258 pw.print(" (uid="); 17259 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17260 UserHandle.USER_SYSTEM)); 17261 pw.println(")"); 17262 } else if (mRequiredVerifierPackage != null) { 17263 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 17264 pw.print(","); 17265 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17266 UserHandle.USER_SYSTEM)); 17267 } 17268 } 17269 17270 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 17271 packageName == null) { 17272 if (mIntentFilterVerifierComponent != null) { 17273 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 17274 if (!checkin) { 17275 if (dumpState.onTitlePrinted()) 17276 pw.println(); 17277 pw.println("Intent Filter Verifier:"); 17278 pw.print(" Using: "); 17279 pw.print(verifierPackageName); 17280 pw.print(" (uid="); 17281 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17282 UserHandle.USER_SYSTEM)); 17283 pw.println(")"); 17284 } else if (verifierPackageName != null) { 17285 pw.print("ifv,"); pw.print(verifierPackageName); 17286 pw.print(","); 17287 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17288 UserHandle.USER_SYSTEM)); 17289 } 17290 } else { 17291 pw.println(); 17292 pw.println("No Intent Filter Verifier available!"); 17293 } 17294 } 17295 17296 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 17297 boolean printedHeader = false; 17298 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 17299 while (it.hasNext()) { 17300 String name = it.next(); 17301 SharedLibraryEntry ent = mSharedLibraries.get(name); 17302 if (!checkin) { 17303 if (!printedHeader) { 17304 if (dumpState.onTitlePrinted()) 17305 pw.println(); 17306 pw.println("Libraries:"); 17307 printedHeader = true; 17308 } 17309 pw.print(" "); 17310 } else { 17311 pw.print("lib,"); 17312 } 17313 pw.print(name); 17314 if (!checkin) { 17315 pw.print(" -> "); 17316 } 17317 if (ent.path != null) { 17318 if (!checkin) { 17319 pw.print("(jar) "); 17320 pw.print(ent.path); 17321 } else { 17322 pw.print(",jar,"); 17323 pw.print(ent.path); 17324 } 17325 } else { 17326 if (!checkin) { 17327 pw.print("(apk) "); 17328 pw.print(ent.apk); 17329 } else { 17330 pw.print(",apk,"); 17331 pw.print(ent.apk); 17332 } 17333 } 17334 pw.println(); 17335 } 17336 } 17337 17338 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 17339 if (dumpState.onTitlePrinted()) 17340 pw.println(); 17341 if (!checkin) { 17342 pw.println("Features:"); 17343 } 17344 17345 for (FeatureInfo feat : mAvailableFeatures.values()) { 17346 if (checkin) { 17347 pw.print("feat,"); 17348 pw.print(feat.name); 17349 pw.print(","); 17350 pw.println(feat.version); 17351 } else { 17352 pw.print(" "); 17353 pw.print(feat.name); 17354 if (feat.version > 0) { 17355 pw.print(" version="); 17356 pw.print(feat.version); 17357 } 17358 pw.println(); 17359 } 17360 } 17361 } 17362 17363 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 17364 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 17365 : "Activity Resolver Table:", " ", packageName, 17366 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17367 dumpState.setTitlePrinted(true); 17368 } 17369 } 17370 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 17371 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 17372 : "Receiver Resolver Table:", " ", packageName, 17373 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17374 dumpState.setTitlePrinted(true); 17375 } 17376 } 17377 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 17378 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 17379 : "Service Resolver Table:", " ", packageName, 17380 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17381 dumpState.setTitlePrinted(true); 17382 } 17383 } 17384 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 17385 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 17386 : "Provider Resolver Table:", " ", packageName, 17387 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17388 dumpState.setTitlePrinted(true); 17389 } 17390 } 17391 17392 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 17393 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17394 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17395 int user = mSettings.mPreferredActivities.keyAt(i); 17396 if (pir.dump(pw, 17397 dumpState.getTitlePrinted() 17398 ? "\nPreferred Activities User " + user + ":" 17399 : "Preferred Activities User " + user + ":", " ", 17400 packageName, true, false)) { 17401 dumpState.setTitlePrinted(true); 17402 } 17403 } 17404 } 17405 17406 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 17407 pw.flush(); 17408 FileOutputStream fout = new FileOutputStream(fd); 17409 BufferedOutputStream str = new BufferedOutputStream(fout); 17410 XmlSerializer serializer = new FastXmlSerializer(); 17411 try { 17412 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 17413 serializer.startDocument(null, true); 17414 serializer.setFeature( 17415 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 17416 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 17417 serializer.endDocument(); 17418 serializer.flush(); 17419 } catch (IllegalArgumentException e) { 17420 pw.println("Failed writing: " + e); 17421 } catch (IllegalStateException e) { 17422 pw.println("Failed writing: " + e); 17423 } catch (IOException e) { 17424 pw.println("Failed writing: " + e); 17425 } 17426 } 17427 17428 if (!checkin 17429 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 17430 && packageName == null) { 17431 pw.println(); 17432 int count = mSettings.mPackages.size(); 17433 if (count == 0) { 17434 pw.println("No applications!"); 17435 pw.println(); 17436 } else { 17437 final String prefix = " "; 17438 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 17439 if (allPackageSettings.size() == 0) { 17440 pw.println("No domain preferred apps!"); 17441 pw.println(); 17442 } else { 17443 pw.println("App verification status:"); 17444 pw.println(); 17445 count = 0; 17446 for (PackageSetting ps : allPackageSettings) { 17447 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 17448 if (ivi == null || ivi.getPackageName() == null) continue; 17449 pw.println(prefix + "Package: " + ivi.getPackageName()); 17450 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 17451 pw.println(prefix + "Status: " + ivi.getStatusString()); 17452 pw.println(); 17453 count++; 17454 } 17455 if (count == 0) { 17456 pw.println(prefix + "No app verification established."); 17457 pw.println(); 17458 } 17459 for (int userId : sUserManager.getUserIds()) { 17460 pw.println("App linkages for user " + userId + ":"); 17461 pw.println(); 17462 count = 0; 17463 for (PackageSetting ps : allPackageSettings) { 17464 final long status = ps.getDomainVerificationStatusForUser(userId); 17465 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 17466 continue; 17467 } 17468 pw.println(prefix + "Package: " + ps.name); 17469 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 17470 String statusStr = IntentFilterVerificationInfo. 17471 getStatusStringFromValue(status); 17472 pw.println(prefix + "Status: " + statusStr); 17473 pw.println(); 17474 count++; 17475 } 17476 if (count == 0) { 17477 pw.println(prefix + "No configured app linkages."); 17478 pw.println(); 17479 } 17480 } 17481 } 17482 } 17483 } 17484 17485 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 17486 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 17487 if (packageName == null && permissionNames == null) { 17488 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 17489 if (iperm == 0) { 17490 if (dumpState.onTitlePrinted()) 17491 pw.println(); 17492 pw.println("AppOp Permissions:"); 17493 } 17494 pw.print(" AppOp Permission "); 17495 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 17496 pw.println(":"); 17497 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 17498 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 17499 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 17500 } 17501 } 17502 } 17503 } 17504 17505 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 17506 boolean printedSomething = false; 17507 for (PackageParser.Provider p : mProviders.mProviders.values()) { 17508 if (packageName != null && !packageName.equals(p.info.packageName)) { 17509 continue; 17510 } 17511 if (!printedSomething) { 17512 if (dumpState.onTitlePrinted()) 17513 pw.println(); 17514 pw.println("Registered ContentProviders:"); 17515 printedSomething = true; 17516 } 17517 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 17518 pw.print(" "); pw.println(p.toString()); 17519 } 17520 printedSomething = false; 17521 for (Map.Entry<String, PackageParser.Provider> entry : 17522 mProvidersByAuthority.entrySet()) { 17523 PackageParser.Provider p = entry.getValue(); 17524 if (packageName != null && !packageName.equals(p.info.packageName)) { 17525 continue; 17526 } 17527 if (!printedSomething) { 17528 if (dumpState.onTitlePrinted()) 17529 pw.println(); 17530 pw.println("ContentProvider Authorities:"); 17531 printedSomething = true; 17532 } 17533 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 17534 pw.print(" "); pw.println(p.toString()); 17535 if (p.info != null && p.info.applicationInfo != null) { 17536 final String appInfo = p.info.applicationInfo.toString(); 17537 pw.print(" applicationInfo="); pw.println(appInfo); 17538 } 17539 } 17540 } 17541 17542 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 17543 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 17544 } 17545 17546 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 17547 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 17548 } 17549 17550 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 17551 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 17552 } 17553 17554 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 17555 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 17556 } 17557 17558 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 17559 // XXX should handle packageName != null by dumping only install data that 17560 // the given package is involved with. 17561 if (dumpState.onTitlePrinted()) pw.println(); 17562 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 17563 } 17564 17565 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 17566 if (dumpState.onTitlePrinted()) pw.println(); 17567 mSettings.dumpReadMessagesLPr(pw, dumpState); 17568 17569 pw.println(); 17570 pw.println("Package warning messages:"); 17571 BufferedReader in = null; 17572 String line = null; 17573 try { 17574 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 17575 while ((line = in.readLine()) != null) { 17576 if (line.contains("ignored: updated version")) continue; 17577 pw.println(line); 17578 } 17579 } catch (IOException ignored) { 17580 } finally { 17581 IoUtils.closeQuietly(in); 17582 } 17583 } 17584 17585 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 17586 BufferedReader in = null; 17587 String line = null; 17588 try { 17589 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 17590 while ((line = in.readLine()) != null) { 17591 if (line.contains("ignored: updated version")) continue; 17592 pw.print("msg,"); 17593 pw.println(line); 17594 } 17595 } catch (IOException ignored) { 17596 } finally { 17597 IoUtils.closeQuietly(in); 17598 } 17599 } 17600 } 17601 } 17602 17603 private String dumpDomainString(String packageName) { 17604 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 17605 .getList(); 17606 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 17607 17608 ArraySet<String> result = new ArraySet<>(); 17609 if (iviList.size() > 0) { 17610 for (IntentFilterVerificationInfo ivi : iviList) { 17611 for (String host : ivi.getDomains()) { 17612 result.add(host); 17613 } 17614 } 17615 } 17616 if (filters != null && filters.size() > 0) { 17617 for (IntentFilter filter : filters) { 17618 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 17619 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 17620 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 17621 result.addAll(filter.getHostsList()); 17622 } 17623 } 17624 } 17625 17626 StringBuilder sb = new StringBuilder(result.size() * 16); 17627 for (String domain : result) { 17628 if (sb.length() > 0) sb.append(" "); 17629 sb.append(domain); 17630 } 17631 return sb.toString(); 17632 } 17633 17634 // ------- apps on sdcard specific code ------- 17635 static final boolean DEBUG_SD_INSTALL = false; 17636 17637 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 17638 17639 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 17640 17641 private boolean mMediaMounted = false; 17642 17643 static String getEncryptKey() { 17644 try { 17645 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 17646 SD_ENCRYPTION_KEYSTORE_NAME); 17647 if (sdEncKey == null) { 17648 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 17649 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 17650 if (sdEncKey == null) { 17651 Slog.e(TAG, "Failed to create encryption keys"); 17652 return null; 17653 } 17654 } 17655 return sdEncKey; 17656 } catch (NoSuchAlgorithmException nsae) { 17657 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 17658 return null; 17659 } catch (IOException ioe) { 17660 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 17661 return null; 17662 } 17663 } 17664 17665 /* 17666 * Update media status on PackageManager. 17667 */ 17668 @Override 17669 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 17670 int callingUid = Binder.getCallingUid(); 17671 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 17672 throw new SecurityException("Media status can only be updated by the system"); 17673 } 17674 // reader; this apparently protects mMediaMounted, but should probably 17675 // be a different lock in that case. 17676 synchronized (mPackages) { 17677 Log.i(TAG, "Updating external media status from " 17678 + (mMediaMounted ? "mounted" : "unmounted") + " to " 17679 + (mediaStatus ? "mounted" : "unmounted")); 17680 if (DEBUG_SD_INSTALL) 17681 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 17682 + ", mMediaMounted=" + mMediaMounted); 17683 if (mediaStatus == mMediaMounted) { 17684 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 17685 : 0, -1); 17686 mHandler.sendMessage(msg); 17687 return; 17688 } 17689 mMediaMounted = mediaStatus; 17690 } 17691 // Queue up an async operation since the package installation may take a 17692 // little while. 17693 mHandler.post(new Runnable() { 17694 public void run() { 17695 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 17696 } 17697 }); 17698 } 17699 17700 /** 17701 * Called by MountService when the initial ASECs to scan are available. 17702 * Should block until all the ASEC containers are finished being scanned. 17703 */ 17704 public void scanAvailableAsecs() { 17705 updateExternalMediaStatusInner(true, false, false); 17706 } 17707 17708 /* 17709 * Collect information of applications on external media, map them against 17710 * existing containers and update information based on current mount status. 17711 * Please note that we always have to report status if reportStatus has been 17712 * set to true especially when unloading packages. 17713 */ 17714 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 17715 boolean externalStorage) { 17716 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 17717 int[] uidArr = EmptyArray.INT; 17718 17719 final String[] list = PackageHelper.getSecureContainerList(); 17720 if (ArrayUtils.isEmpty(list)) { 17721 Log.i(TAG, "No secure containers found"); 17722 } else { 17723 // Process list of secure containers and categorize them 17724 // as active or stale based on their package internal state. 17725 17726 // reader 17727 synchronized (mPackages) { 17728 for (String cid : list) { 17729 // Leave stages untouched for now; installer service owns them 17730 if (PackageInstallerService.isStageName(cid)) continue; 17731 17732 if (DEBUG_SD_INSTALL) 17733 Log.i(TAG, "Processing container " + cid); 17734 String pkgName = getAsecPackageName(cid); 17735 if (pkgName == null) { 17736 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 17737 continue; 17738 } 17739 if (DEBUG_SD_INSTALL) 17740 Log.i(TAG, "Looking for pkg : " + pkgName); 17741 17742 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17743 if (ps == null) { 17744 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 17745 continue; 17746 } 17747 17748 /* 17749 * Skip packages that are not external if we're unmounting 17750 * external storage. 17751 */ 17752 if (externalStorage && !isMounted && !isExternal(ps)) { 17753 continue; 17754 } 17755 17756 final AsecInstallArgs args = new AsecInstallArgs(cid, 17757 getAppDexInstructionSets(ps), ps.isForwardLocked()); 17758 // The package status is changed only if the code path 17759 // matches between settings and the container id. 17760 if (ps.codePathString != null 17761 && ps.codePathString.startsWith(args.getCodePath())) { 17762 if (DEBUG_SD_INSTALL) { 17763 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 17764 + " at code path: " + ps.codePathString); 17765 } 17766 17767 // We do have a valid package installed on sdcard 17768 processCids.put(args, ps.codePathString); 17769 final int uid = ps.appId; 17770 if (uid != -1) { 17771 uidArr = ArrayUtils.appendInt(uidArr, uid); 17772 } 17773 } else { 17774 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 17775 + ps.codePathString); 17776 } 17777 } 17778 } 17779 17780 Arrays.sort(uidArr); 17781 } 17782 17783 // Process packages with valid entries. 17784 if (isMounted) { 17785 if (DEBUG_SD_INSTALL) 17786 Log.i(TAG, "Loading packages"); 17787 loadMediaPackages(processCids, uidArr, externalStorage); 17788 startCleaningPackages(); 17789 mInstallerService.onSecureContainersAvailable(); 17790 } else { 17791 if (DEBUG_SD_INSTALL) 17792 Log.i(TAG, "Unloading packages"); 17793 unloadMediaPackages(processCids, uidArr, reportStatus); 17794 } 17795 } 17796 17797 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17798 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 17799 final int size = infos.size(); 17800 final String[] packageNames = new String[size]; 17801 final int[] packageUids = new int[size]; 17802 for (int i = 0; i < size; i++) { 17803 final ApplicationInfo info = infos.get(i); 17804 packageNames[i] = info.packageName; 17805 packageUids[i] = info.uid; 17806 } 17807 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 17808 finishedReceiver); 17809 } 17810 17811 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17812 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 17813 sendResourcesChangedBroadcast(mediaStatus, replacing, 17814 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 17815 } 17816 17817 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17818 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 17819 int size = pkgList.length; 17820 if (size > 0) { 17821 // Send broadcasts here 17822 Bundle extras = new Bundle(); 17823 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 17824 if (uidArr != null) { 17825 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 17826 } 17827 if (replacing) { 17828 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 17829 } 17830 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 17831 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 17832 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 17833 } 17834 } 17835 17836 /* 17837 * Look at potentially valid container ids from processCids If package 17838 * information doesn't match the one on record or package scanning fails, 17839 * the cid is added to list of removeCids. We currently don't delete stale 17840 * containers. 17841 */ 17842 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 17843 boolean externalStorage) { 17844 ArrayList<String> pkgList = new ArrayList<String>(); 17845 Set<AsecInstallArgs> keys = processCids.keySet(); 17846 17847 for (AsecInstallArgs args : keys) { 17848 String codePath = processCids.get(args); 17849 if (DEBUG_SD_INSTALL) 17850 Log.i(TAG, "Loading container : " + args.cid); 17851 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 17852 try { 17853 // Make sure there are no container errors first. 17854 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 17855 Slog.e(TAG, "Failed to mount cid : " + args.cid 17856 + " when installing from sdcard"); 17857 continue; 17858 } 17859 // Check code path here. 17860 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 17861 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 17862 + " does not match one in settings " + codePath); 17863 continue; 17864 } 17865 // Parse package 17866 int parseFlags = mDefParseFlags; 17867 if (args.isExternalAsec()) { 17868 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 17869 } 17870 if (args.isFwdLocked()) { 17871 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 17872 } 17873 17874 synchronized (mInstallLock) { 17875 PackageParser.Package pkg = null; 17876 try { 17877 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 17878 } catch (PackageManagerException e) { 17879 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 17880 } 17881 // Scan the package 17882 if (pkg != null) { 17883 /* 17884 * TODO why is the lock being held? doPostInstall is 17885 * called in other places without the lock. This needs 17886 * to be straightened out. 17887 */ 17888 // writer 17889 synchronized (mPackages) { 17890 retCode = PackageManager.INSTALL_SUCCEEDED; 17891 pkgList.add(pkg.packageName); 17892 // Post process args 17893 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 17894 pkg.applicationInfo.uid); 17895 } 17896 } else { 17897 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 17898 } 17899 } 17900 17901 } finally { 17902 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 17903 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 17904 } 17905 } 17906 } 17907 // writer 17908 synchronized (mPackages) { 17909 // If the platform SDK has changed since the last time we booted, 17910 // we need to re-grant app permission to catch any new ones that 17911 // appear. This is really a hack, and means that apps can in some 17912 // cases get permissions that the user didn't initially explicitly 17913 // allow... it would be nice to have some better way to handle 17914 // this situation. 17915 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 17916 : mSettings.getInternalVersion(); 17917 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 17918 : StorageManager.UUID_PRIVATE_INTERNAL; 17919 17920 int updateFlags = UPDATE_PERMISSIONS_ALL; 17921 if (ver.sdkVersion != mSdkVersion) { 17922 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 17923 + mSdkVersion + "; regranting permissions for external"); 17924 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 17925 } 17926 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 17927 17928 // Yay, everything is now upgraded 17929 ver.forceCurrent(); 17930 17931 // can downgrade to reader 17932 // Persist settings 17933 mSettings.writeLPr(); 17934 } 17935 // Send a broadcast to let everyone know we are done processing 17936 if (pkgList.size() > 0) { 17937 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 17938 } 17939 } 17940 17941 /* 17942 * Utility method to unload a list of specified containers 17943 */ 17944 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 17945 // Just unmount all valid containers. 17946 for (AsecInstallArgs arg : cidArgs) { 17947 synchronized (mInstallLock) { 17948 arg.doPostDeleteLI(false); 17949 } 17950 } 17951 } 17952 17953 /* 17954 * Unload packages mounted on external media. This involves deleting package 17955 * data from internal structures, sending broadcasts about disabled packages, 17956 * gc'ing to free up references, unmounting all secure containers 17957 * corresponding to packages on external media, and posting a 17958 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 17959 * that we always have to post this message if status has been requested no 17960 * matter what. 17961 */ 17962 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 17963 final boolean reportStatus) { 17964 if (DEBUG_SD_INSTALL) 17965 Log.i(TAG, "unloading media packages"); 17966 ArrayList<String> pkgList = new ArrayList<String>(); 17967 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 17968 final Set<AsecInstallArgs> keys = processCids.keySet(); 17969 for (AsecInstallArgs args : keys) { 17970 String pkgName = args.getPackageName(); 17971 if (DEBUG_SD_INSTALL) 17972 Log.i(TAG, "Trying to unload pkg : " + pkgName); 17973 // Delete package internally 17974 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 17975 synchronized (mInstallLock) { 17976 boolean res = deletePackageLI(pkgName, null, false, null, 17977 PackageManager.DELETE_KEEP_DATA, outInfo, false, null); 17978 if (res) { 17979 pkgList.add(pkgName); 17980 } else { 17981 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 17982 failedList.add(args); 17983 } 17984 } 17985 } 17986 17987 // reader 17988 synchronized (mPackages) { 17989 // We didn't update the settings after removing each package; 17990 // write them now for all packages. 17991 mSettings.writeLPr(); 17992 } 17993 17994 // We have to absolutely send UPDATED_MEDIA_STATUS only 17995 // after confirming that all the receivers processed the ordered 17996 // broadcast when packages get disabled, force a gc to clean things up. 17997 // and unload all the containers. 17998 if (pkgList.size() > 0) { 17999 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18000 new IIntentReceiver.Stub() { 18001 public void performReceive(Intent intent, int resultCode, String data, 18002 Bundle extras, boolean ordered, boolean sticky, 18003 int sendingUser) throws RemoteException { 18004 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18005 reportStatus ? 1 : 0, 1, keys); 18006 mHandler.sendMessage(msg); 18007 } 18008 }); 18009 } else { 18010 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 18011 keys); 18012 mHandler.sendMessage(msg); 18013 } 18014 } 18015 18016 private void loadPrivatePackages(final VolumeInfo vol) { 18017 mHandler.post(new Runnable() { 18018 @Override 18019 public void run() { 18020 loadPrivatePackagesInner(vol); 18021 } 18022 }); 18023 } 18024 18025 private void loadPrivatePackagesInner(VolumeInfo vol) { 18026 final String volumeUuid = vol.fsUuid; 18027 if (TextUtils.isEmpty(volumeUuid)) { 18028 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 18029 return; 18030 } 18031 18032 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 18033 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 18034 18035 final VersionInfo ver; 18036 final List<PackageSetting> packages; 18037 synchronized (mPackages) { 18038 ver = mSettings.findOrCreateVersion(volumeUuid); 18039 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18040 } 18041 18042 // TODO: introduce a new concept similar to "frozen" to prevent these 18043 // apps from being launched until after data has been fully reconciled 18044 for (PackageSetting ps : packages) { 18045 synchronized (mInstallLock) { 18046 final PackageParser.Package pkg; 18047 try { 18048 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 18049 loaded.add(pkg.applicationInfo); 18050 18051 } catch (PackageManagerException e) { 18052 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 18053 } 18054 18055 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 18056 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 18057 } 18058 } 18059 } 18060 18061 // Reconcile app data for all started/unlocked users 18062 final StorageManager sm = mContext.getSystemService(StorageManager.class); 18063 final UserManager um = mContext.getSystemService(UserManager.class); 18064 for (UserInfo user : um.getUsers()) { 18065 final int flags; 18066 if (um.isUserUnlocked(user.id)) { 18067 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18068 } else if (um.isUserRunning(user.id)) { 18069 flags = StorageManager.FLAG_STORAGE_DE; 18070 } else { 18071 continue; 18072 } 18073 18074 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 18075 reconcileAppsData(volumeUuid, user.id, flags); 18076 } 18077 18078 synchronized (mPackages) { 18079 int updateFlags = UPDATE_PERMISSIONS_ALL; 18080 if (ver.sdkVersion != mSdkVersion) { 18081 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18082 + mSdkVersion + "; regranting permissions for " + volumeUuid); 18083 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18084 } 18085 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18086 18087 // Yay, everything is now upgraded 18088 ver.forceCurrent(); 18089 18090 mSettings.writeLPr(); 18091 } 18092 18093 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 18094 sendResourcesChangedBroadcast(true, false, loaded, null); 18095 } 18096 18097 private void unloadPrivatePackages(final VolumeInfo vol) { 18098 mHandler.post(new Runnable() { 18099 @Override 18100 public void run() { 18101 unloadPrivatePackagesInner(vol); 18102 } 18103 }); 18104 } 18105 18106 private void unloadPrivatePackagesInner(VolumeInfo vol) { 18107 final String volumeUuid = vol.fsUuid; 18108 if (TextUtils.isEmpty(volumeUuid)) { 18109 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 18110 return; 18111 } 18112 18113 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 18114 synchronized (mInstallLock) { 18115 synchronized (mPackages) { 18116 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 18117 for (PackageSetting ps : packages) { 18118 if (ps.pkg == null) continue; 18119 18120 final ApplicationInfo info = ps.pkg.applicationInfo; 18121 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18122 if (deletePackageLI(ps.name, null, false, null, 18123 PackageManager.DELETE_KEEP_DATA, outInfo, false, null)) { 18124 unloaded.add(info); 18125 } else { 18126 Slog.w(TAG, "Failed to unload " + ps.codePath); 18127 } 18128 } 18129 18130 mSettings.writeLPr(); 18131 } 18132 } 18133 18134 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 18135 sendResourcesChangedBroadcast(false, false, unloaded, null); 18136 } 18137 18138 /** 18139 * Examine all users present on given mounted volume, and destroy data 18140 * belonging to users that are no longer valid, or whose user ID has been 18141 * recycled. 18142 */ 18143 private void reconcileUsers(String volumeUuid) { 18144 // TODO: also reconcile DE directories 18145 final File[] files = FileUtils 18146 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)); 18147 for (File file : files) { 18148 if (!file.isDirectory()) continue; 18149 18150 final int userId; 18151 final UserInfo info; 18152 try { 18153 userId = Integer.parseInt(file.getName()); 18154 info = sUserManager.getUserInfo(userId); 18155 } catch (NumberFormatException e) { 18156 Slog.w(TAG, "Invalid user directory " + file); 18157 continue; 18158 } 18159 18160 boolean destroyUser = false; 18161 if (info == null) { 18162 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18163 + " because no matching user was found"); 18164 destroyUser = true; 18165 } else { 18166 try { 18167 UserManagerService.enforceSerialNumber(file, info.serialNumber); 18168 } catch (IOException e) { 18169 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18170 + " because we failed to enforce serial number: " + e); 18171 destroyUser = true; 18172 } 18173 } 18174 18175 if (destroyUser) { 18176 synchronized (mInstallLock) { 18177 try { 18178 mInstaller.removeUserDataDirs(volumeUuid, userId); 18179 } catch (InstallerException e) { 18180 Slog.w(TAG, "Failed to clean up user dirs", e); 18181 } 18182 } 18183 } 18184 } 18185 } 18186 18187 private void assertPackageKnown(String volumeUuid, String packageName) 18188 throws PackageManagerException { 18189 synchronized (mPackages) { 18190 final PackageSetting ps = mSettings.mPackages.get(packageName); 18191 if (ps == null) { 18192 throw new PackageManagerException("Package " + packageName + " is unknown"); 18193 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18194 throw new PackageManagerException( 18195 "Package " + packageName + " found on unknown volume " + volumeUuid 18196 + "; expected volume " + ps.volumeUuid); 18197 } 18198 } 18199 } 18200 18201 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 18202 throws PackageManagerException { 18203 synchronized (mPackages) { 18204 final PackageSetting ps = mSettings.mPackages.get(packageName); 18205 if (ps == null) { 18206 throw new PackageManagerException("Package " + packageName + " is unknown"); 18207 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18208 throw new PackageManagerException( 18209 "Package " + packageName + " found on unknown volume " + volumeUuid 18210 + "; expected volume " + ps.volumeUuid); 18211 } else if (!ps.getInstalled(userId)) { 18212 throw new PackageManagerException( 18213 "Package " + packageName + " not installed for user " + userId); 18214 } 18215 } 18216 } 18217 18218 /** 18219 * Examine all apps present on given mounted volume, and destroy apps that 18220 * aren't expected, either due to uninstallation or reinstallation on 18221 * another volume. 18222 */ 18223 private void reconcileApps(String volumeUuid) { 18224 final File[] files = FileUtils 18225 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 18226 for (File file : files) { 18227 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 18228 && !PackageInstallerService.isStageName(file.getName()); 18229 if (!isPackage) { 18230 // Ignore entries which are not packages 18231 continue; 18232 } 18233 18234 try { 18235 final PackageLite pkg = PackageParser.parsePackageLite(file, 18236 PackageParser.PARSE_MUST_BE_APK); 18237 assertPackageKnown(volumeUuid, pkg.packageName); 18238 18239 } catch (PackageParserException | PackageManagerException e) { 18240 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18241 synchronized (mInstallLock) { 18242 removeCodePathLI(file); 18243 } 18244 } 18245 } 18246 } 18247 18248 /** 18249 * Reconcile all app data for the given user. 18250 * <p> 18251 * Verifies that directories exist and that ownership and labeling is 18252 * correct for all installed apps on all mounted volumes. 18253 */ 18254 void reconcileAppsData(int userId, int flags) { 18255 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18256 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18257 final String volumeUuid = vol.getFsUuid(); 18258 reconcileAppsData(volumeUuid, userId, flags); 18259 } 18260 } 18261 18262 /** 18263 * Reconcile all app data on given mounted volume. 18264 * <p> 18265 * Destroys app data that isn't expected, either due to uninstallation or 18266 * reinstallation on another volume. 18267 * <p> 18268 * Verifies that directories exist and that ownership and labeling is 18269 * correct for all installed apps. 18270 */ 18271 private void reconcileAppsData(String volumeUuid, int userId, int flags) { 18272 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 18273 + Integer.toHexString(flags)); 18274 18275 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 18276 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 18277 18278 boolean restoreconNeeded = false; 18279 18280 // First look for stale data that doesn't belong, and check if things 18281 // have changed since we did our last restorecon 18282 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18283 if (!isUserKeyUnlocked(userId)) { 18284 throw new RuntimeException( 18285 "Yikes, someone asked us to reconcile CE storage while " + userId 18286 + " was still locked; this would have caused massive data loss!"); 18287 } 18288 18289 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 18290 18291 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 18292 for (File file : files) { 18293 final String packageName = file.getName(); 18294 try { 18295 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18296 } catch (PackageManagerException e) { 18297 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18298 synchronized (mInstallLock) { 18299 destroyAppDataLI(volumeUuid, packageName, userId, 18300 StorageManager.FLAG_STORAGE_CE); 18301 } 18302 } 18303 } 18304 } 18305 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18306 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 18307 18308 final File[] files = FileUtils.listFilesOrEmpty(deDir); 18309 for (File file : files) { 18310 final String packageName = file.getName(); 18311 try { 18312 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18313 } catch (PackageManagerException e) { 18314 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18315 synchronized (mInstallLock) { 18316 destroyAppDataLI(volumeUuid, packageName, userId, 18317 StorageManager.FLAG_STORAGE_DE); 18318 } 18319 } 18320 } 18321 } 18322 18323 // Ensure that data directories are ready to roll for all packages 18324 // installed for this volume and user 18325 final List<PackageSetting> packages; 18326 synchronized (mPackages) { 18327 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18328 } 18329 int preparedCount = 0; 18330 for (PackageSetting ps : packages) { 18331 final String packageName = ps.name; 18332 if (ps.pkg == null) { 18333 Slog.w(TAG, "Odd, missing scanned package " + packageName); 18334 // TODO: might be due to legacy ASEC apps; we should circle back 18335 // and reconcile again once they're scanned 18336 continue; 18337 } 18338 18339 if (ps.getInstalled(userId)) { 18340 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 18341 18342 if (maybeMigrateAppData(volumeUuid, userId, ps.pkg)) { 18343 // We may have just shuffled around app data directories, so 18344 // prepare them one more time 18345 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 18346 } 18347 18348 preparedCount++; 18349 } 18350 } 18351 18352 if (restoreconNeeded) { 18353 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18354 SELinuxMMAC.setRestoreconDone(ceDir); 18355 } 18356 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18357 SELinuxMMAC.setRestoreconDone(deDir); 18358 } 18359 } 18360 18361 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 18362 + " packages; restoreconNeeded was " + restoreconNeeded); 18363 } 18364 18365 /** 18366 * Prepare app data for the given app just after it was installed or 18367 * upgraded. This method carefully only touches users that it's installed 18368 * for, and it forces a restorecon to handle any seinfo changes. 18369 * <p> 18370 * Verifies that directories exist and that ownership and labeling is 18371 * correct for all installed apps. If there is an ownership mismatch, it 18372 * will try recovering system apps by wiping data; third-party app data is 18373 * left intact. 18374 * <p> 18375 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 18376 */ 18377 private void prepareAppDataAfterInstall(PackageParser.Package pkg) { 18378 prepareAppDataAfterInstallInternal(pkg); 18379 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 18380 for (int i = 0; i < childCount; i++) { 18381 PackageParser.Package childPackage = pkg.childPackages.get(i); 18382 prepareAppDataAfterInstallInternal(childPackage); 18383 } 18384 } 18385 18386 private void prepareAppDataAfterInstallInternal(PackageParser.Package pkg) { 18387 final PackageSetting ps; 18388 synchronized (mPackages) { 18389 ps = mSettings.mPackages.get(pkg.packageName); 18390 mSettings.writeKernelMappingLPr(ps); 18391 } 18392 18393 final UserManager um = mContext.getSystemService(UserManager.class); 18394 for (UserInfo user : um.getUsers()) { 18395 final int flags; 18396 if (um.isUserUnlocked(user.id)) { 18397 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18398 } else if (um.isUserRunning(user.id)) { 18399 flags = StorageManager.FLAG_STORAGE_DE; 18400 } else { 18401 continue; 18402 } 18403 18404 if (ps.getInstalled(user.id)) { 18405 // Whenever an app changes, force a restorecon of its data 18406 // TODO: when user data is locked, mark that we're still dirty 18407 prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true); 18408 } 18409 } 18410 } 18411 18412 /** 18413 * Prepare app data for the given app. 18414 * <p> 18415 * Verifies that directories exist and that ownership and labeling is 18416 * correct for all installed apps. If there is an ownership mismatch, this 18417 * will try recovering system apps by wiping data; third-party app data is 18418 * left intact. 18419 */ 18420 private void prepareAppData(String volumeUuid, int userId, int flags, 18421 PackageParser.Package pkg, boolean restoreconNeeded) { 18422 if (DEBUG_APP_DATA) { 18423 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 18424 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 18425 } 18426 18427 final String packageName = pkg.packageName; 18428 final ApplicationInfo app = pkg.applicationInfo; 18429 final int appId = UserHandle.getAppId(app.uid); 18430 18431 Preconditions.checkNotNull(app.seinfo); 18432 18433 synchronized (mInstallLock) { 18434 try { 18435 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18436 appId, app.seinfo, app.targetSdkVersion); 18437 } catch (InstallerException e) { 18438 if (app.isSystemApp()) { 18439 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 18440 + ", but trying to recover: " + e); 18441 destroyAppDataLI(volumeUuid, packageName, userId, flags); 18442 try { 18443 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18444 appId, app.seinfo, app.targetSdkVersion); 18445 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 18446 } catch (InstallerException e2) { 18447 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 18448 } 18449 } else { 18450 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 18451 } 18452 } 18453 18454 if (restoreconNeeded) { 18455 restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo); 18456 } 18457 18458 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18459 // Create a native library symlink only if we have native libraries 18460 // and if the native libraries are 32 bit libraries. We do not provide 18461 // this symlink for 64 bit libraries. 18462 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 18463 final String nativeLibPath = app.nativeLibraryDir; 18464 try { 18465 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 18466 nativeLibPath, userId); 18467 } catch (InstallerException e) { 18468 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 18469 } 18470 } 18471 } 18472 } 18473 } 18474 18475 /** 18476 * For system apps on non-FBE devices, this method migrates any existing 18477 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 18478 * requested by the app. 18479 */ 18480 private boolean maybeMigrateAppData(String volumeUuid, int userId, PackageParser.Package pkg) { 18481 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 18482 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 18483 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 18484 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 18485 synchronized (mInstallLock) { 18486 try { 18487 mInstaller.migrateAppData(volumeUuid, pkg.packageName, userId, storageTarget); 18488 } catch (InstallerException e) { 18489 logCriticalInfo(Log.WARN, 18490 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 18491 } 18492 } 18493 return true; 18494 } else { 18495 return false; 18496 } 18497 } 18498 18499 private void unfreezePackage(String packageName) { 18500 synchronized (mPackages) { 18501 final PackageSetting ps = mSettings.mPackages.get(packageName); 18502 if (ps != null) { 18503 ps.frozen = false; 18504 } 18505 } 18506 } 18507 18508 @Override 18509 public int movePackage(final String packageName, final String volumeUuid) { 18510 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 18511 18512 final int moveId = mNextMoveId.getAndIncrement(); 18513 mHandler.post(new Runnable() { 18514 @Override 18515 public void run() { 18516 try { 18517 movePackageInternal(packageName, volumeUuid, moveId); 18518 } catch (PackageManagerException e) { 18519 Slog.w(TAG, "Failed to move " + packageName, e); 18520 mMoveCallbacks.notifyStatusChanged(moveId, 18521 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 18522 } 18523 } 18524 }); 18525 return moveId; 18526 } 18527 18528 private void movePackageInternal(final String packageName, final String volumeUuid, 18529 final int moveId) throws PackageManagerException { 18530 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 18531 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18532 final PackageManager pm = mContext.getPackageManager(); 18533 18534 final boolean currentAsec; 18535 final String currentVolumeUuid; 18536 final File codeFile; 18537 final String installerPackageName; 18538 final String packageAbiOverride; 18539 final int appId; 18540 final String seinfo; 18541 final String label; 18542 final int targetSdkVersion; 18543 18544 // reader 18545 synchronized (mPackages) { 18546 final PackageParser.Package pkg = mPackages.get(packageName); 18547 final PackageSetting ps = mSettings.mPackages.get(packageName); 18548 if (pkg == null || ps == null) { 18549 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 18550 } 18551 18552 if (pkg.applicationInfo.isSystemApp()) { 18553 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 18554 "Cannot move system application"); 18555 } 18556 18557 if (pkg.applicationInfo.isExternalAsec()) { 18558 currentAsec = true; 18559 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 18560 } else if (pkg.applicationInfo.isForwardLocked()) { 18561 currentAsec = true; 18562 currentVolumeUuid = "forward_locked"; 18563 } else { 18564 currentAsec = false; 18565 currentVolumeUuid = ps.volumeUuid; 18566 18567 final File probe = new File(pkg.codePath); 18568 final File probeOat = new File(probe, "oat"); 18569 if (!probe.isDirectory() || !probeOat.isDirectory()) { 18570 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18571 "Move only supported for modern cluster style installs"); 18572 } 18573 } 18574 18575 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 18576 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18577 "Package already moved to " + volumeUuid); 18578 } 18579 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 18580 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 18581 "Device admin cannot be moved"); 18582 } 18583 18584 if (ps.frozen) { 18585 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 18586 "Failed to move already frozen package"); 18587 } 18588 ps.frozen = true; 18589 18590 codeFile = new File(pkg.codePath); 18591 installerPackageName = ps.installerPackageName; 18592 packageAbiOverride = ps.cpuAbiOverrideString; 18593 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18594 seinfo = pkg.applicationInfo.seinfo; 18595 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 18596 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 18597 } 18598 18599 // Now that we're guarded by frozen state, kill app during move 18600 final long token = Binder.clearCallingIdentity(); 18601 try { 18602 killApplication(packageName, appId, "move pkg"); 18603 } finally { 18604 Binder.restoreCallingIdentity(token); 18605 } 18606 18607 final Bundle extras = new Bundle(); 18608 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 18609 extras.putString(Intent.EXTRA_TITLE, label); 18610 mMoveCallbacks.notifyCreated(moveId, extras); 18611 18612 int installFlags; 18613 final boolean moveCompleteApp; 18614 final File measurePath; 18615 18616 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 18617 installFlags = INSTALL_INTERNAL; 18618 moveCompleteApp = !currentAsec; 18619 measurePath = Environment.getDataAppDirectory(volumeUuid); 18620 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 18621 installFlags = INSTALL_EXTERNAL; 18622 moveCompleteApp = false; 18623 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 18624 } else { 18625 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 18626 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 18627 || !volume.isMountedWritable()) { 18628 unfreezePackage(packageName); 18629 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18630 "Move location not mounted private volume"); 18631 } 18632 18633 Preconditions.checkState(!currentAsec); 18634 18635 installFlags = INSTALL_INTERNAL; 18636 moveCompleteApp = true; 18637 measurePath = Environment.getDataAppDirectory(volumeUuid); 18638 } 18639 18640 final PackageStats stats = new PackageStats(null, -1); 18641 synchronized (mInstaller) { 18642 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 18643 unfreezePackage(packageName); 18644 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18645 "Failed to measure package size"); 18646 } 18647 } 18648 18649 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 18650 + stats.dataSize); 18651 18652 final long startFreeBytes = measurePath.getFreeSpace(); 18653 final long sizeBytes; 18654 if (moveCompleteApp) { 18655 sizeBytes = stats.codeSize + stats.dataSize; 18656 } else { 18657 sizeBytes = stats.codeSize; 18658 } 18659 18660 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 18661 unfreezePackage(packageName); 18662 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18663 "Not enough free space to move"); 18664 } 18665 18666 mMoveCallbacks.notifyStatusChanged(moveId, 10); 18667 18668 final CountDownLatch installedLatch = new CountDownLatch(1); 18669 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 18670 @Override 18671 public void onUserActionRequired(Intent intent) throws RemoteException { 18672 throw new IllegalStateException(); 18673 } 18674 18675 @Override 18676 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 18677 Bundle extras) throws RemoteException { 18678 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 18679 + PackageManager.installStatusToString(returnCode, msg)); 18680 18681 installedLatch.countDown(); 18682 18683 // Regardless of success or failure of the move operation, 18684 // always unfreeze the package 18685 unfreezePackage(packageName); 18686 18687 final int status = PackageManager.installStatusToPublicStatus(returnCode); 18688 switch (status) { 18689 case PackageInstaller.STATUS_SUCCESS: 18690 mMoveCallbacks.notifyStatusChanged(moveId, 18691 PackageManager.MOVE_SUCCEEDED); 18692 break; 18693 case PackageInstaller.STATUS_FAILURE_STORAGE: 18694 mMoveCallbacks.notifyStatusChanged(moveId, 18695 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 18696 break; 18697 default: 18698 mMoveCallbacks.notifyStatusChanged(moveId, 18699 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 18700 break; 18701 } 18702 } 18703 }; 18704 18705 final MoveInfo move; 18706 if (moveCompleteApp) { 18707 // Kick off a thread to report progress estimates 18708 new Thread() { 18709 @Override 18710 public void run() { 18711 while (true) { 18712 try { 18713 if (installedLatch.await(1, TimeUnit.SECONDS)) { 18714 break; 18715 } 18716 } catch (InterruptedException ignored) { 18717 } 18718 18719 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 18720 final int progress = 10 + (int) MathUtils.constrain( 18721 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 18722 mMoveCallbacks.notifyStatusChanged(moveId, progress); 18723 } 18724 } 18725 }.start(); 18726 18727 final String dataAppName = codeFile.getName(); 18728 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 18729 dataAppName, appId, seinfo, targetSdkVersion); 18730 } else { 18731 move = null; 18732 } 18733 18734 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 18735 18736 final Message msg = mHandler.obtainMessage(INIT_COPY); 18737 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 18738 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 18739 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 18740 packageAbiOverride, null); 18741 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 18742 msg.obj = params; 18743 18744 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 18745 System.identityHashCode(msg.obj)); 18746 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 18747 System.identityHashCode(msg.obj)); 18748 18749 mHandler.sendMessage(msg); 18750 } 18751 18752 @Override 18753 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 18754 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 18755 18756 final int realMoveId = mNextMoveId.getAndIncrement(); 18757 final Bundle extras = new Bundle(); 18758 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 18759 mMoveCallbacks.notifyCreated(realMoveId, extras); 18760 18761 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 18762 @Override 18763 public void onCreated(int moveId, Bundle extras) { 18764 // Ignored 18765 } 18766 18767 @Override 18768 public void onStatusChanged(int moveId, int status, long estMillis) { 18769 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 18770 } 18771 }; 18772 18773 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18774 storage.setPrimaryStorageUuid(volumeUuid, callback); 18775 return realMoveId; 18776 } 18777 18778 @Override 18779 public int getMoveStatus(int moveId) { 18780 mContext.enforceCallingOrSelfPermission( 18781 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18782 return mMoveCallbacks.mLastStatus.get(moveId); 18783 } 18784 18785 @Override 18786 public void registerMoveCallback(IPackageMoveObserver callback) { 18787 mContext.enforceCallingOrSelfPermission( 18788 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18789 mMoveCallbacks.register(callback); 18790 } 18791 18792 @Override 18793 public void unregisterMoveCallback(IPackageMoveObserver callback) { 18794 mContext.enforceCallingOrSelfPermission( 18795 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18796 mMoveCallbacks.unregister(callback); 18797 } 18798 18799 @Override 18800 public boolean setInstallLocation(int loc) { 18801 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 18802 null); 18803 if (getInstallLocation() == loc) { 18804 return true; 18805 } 18806 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 18807 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 18808 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 18809 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 18810 return true; 18811 } 18812 return false; 18813 } 18814 18815 @Override 18816 public int getInstallLocation() { 18817 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 18818 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 18819 PackageHelper.APP_INSTALL_AUTO); 18820 } 18821 18822 /** Called by UserManagerService */ 18823 void cleanUpUser(UserManagerService userManager, int userHandle) { 18824 synchronized (mPackages) { 18825 mDirtyUsers.remove(userHandle); 18826 mUserNeedsBadging.delete(userHandle); 18827 mSettings.removeUserLPw(userHandle); 18828 mPendingBroadcasts.remove(userHandle); 18829 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 18830 } 18831 synchronized (mInstallLock) { 18832 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18833 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18834 final String volumeUuid = vol.getFsUuid(); 18835 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 18836 try { 18837 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 18838 } catch (InstallerException e) { 18839 Slog.w(TAG, "Failed to remove user data", e); 18840 } 18841 } 18842 synchronized (mPackages) { 18843 removeUnusedPackagesLILPw(userManager, userHandle); 18844 } 18845 } 18846 } 18847 18848 /** 18849 * We're removing userHandle and would like to remove any downloaded packages 18850 * that are no longer in use by any other user. 18851 * @param userHandle the user being removed 18852 */ 18853 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 18854 final boolean DEBUG_CLEAN_APKS = false; 18855 int [] users = userManager.getUserIds(); 18856 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 18857 while (psit.hasNext()) { 18858 PackageSetting ps = psit.next(); 18859 if (ps.pkg == null) { 18860 continue; 18861 } 18862 final String packageName = ps.pkg.packageName; 18863 // Skip over if system app 18864 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 18865 continue; 18866 } 18867 if (DEBUG_CLEAN_APKS) { 18868 Slog.i(TAG, "Checking package " + packageName); 18869 } 18870 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 18871 if (keep) { 18872 if (DEBUG_CLEAN_APKS) { 18873 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 18874 } 18875 } else { 18876 for (int i = 0; i < users.length; i++) { 18877 if (users[i] != userHandle && ps.getInstalled(users[i])) { 18878 keep = true; 18879 if (DEBUG_CLEAN_APKS) { 18880 Slog.i(TAG, " Keeping package " + packageName + " for user " 18881 + users[i]); 18882 } 18883 break; 18884 } 18885 } 18886 } 18887 if (!keep) { 18888 if (DEBUG_CLEAN_APKS) { 18889 Slog.i(TAG, " Removing package " + packageName); 18890 } 18891 mHandler.post(new Runnable() { 18892 public void run() { 18893 deletePackageX(packageName, userHandle, 0); 18894 } //end run 18895 }); 18896 } 18897 } 18898 } 18899 18900 /** Called by UserManagerService */ 18901 void createNewUser(int userHandle) { 18902 synchronized (mInstallLock) { 18903 try { 18904 mInstaller.createUserConfig(userHandle); 18905 } catch (InstallerException e) { 18906 Slog.w(TAG, "Failed to create user config", e); 18907 } 18908 mSettings.createNewUserLI(this, mInstaller, userHandle); 18909 } 18910 synchronized (mPackages) { 18911 applyFactoryDefaultBrowserLPw(userHandle); 18912 primeDomainVerificationsLPw(userHandle); 18913 } 18914 } 18915 18916 void newUserCreated(final int userHandle) { 18917 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 18918 // If permission review for legacy apps is required, we represent 18919 // dagerous permissions for such apps as always granted runtime 18920 // permissions to keep per user flag state whether review is needed. 18921 // Hence, if a new user is added we have to propagate dangerous 18922 // permission grants for these legacy apps. 18923 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 18924 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 18925 | UPDATE_PERMISSIONS_REPLACE_ALL); 18926 } 18927 } 18928 18929 @Override 18930 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 18931 mContext.enforceCallingOrSelfPermission( 18932 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 18933 "Only package verification agents can read the verifier device identity"); 18934 18935 synchronized (mPackages) { 18936 return mSettings.getVerifierDeviceIdentityLPw(); 18937 } 18938 } 18939 18940 @Override 18941 public void setPermissionEnforced(String permission, boolean enforced) { 18942 // TODO: Now that we no longer change GID for storage, this should to away. 18943 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 18944 "setPermissionEnforced"); 18945 if (READ_EXTERNAL_STORAGE.equals(permission)) { 18946 synchronized (mPackages) { 18947 if (mSettings.mReadExternalStorageEnforced == null 18948 || mSettings.mReadExternalStorageEnforced != enforced) { 18949 mSettings.mReadExternalStorageEnforced = enforced; 18950 mSettings.writeLPr(); 18951 } 18952 } 18953 // kill any non-foreground processes so we restart them and 18954 // grant/revoke the GID. 18955 final IActivityManager am = ActivityManagerNative.getDefault(); 18956 if (am != null) { 18957 final long token = Binder.clearCallingIdentity(); 18958 try { 18959 am.killProcessesBelowForeground("setPermissionEnforcement"); 18960 } catch (RemoteException e) { 18961 } finally { 18962 Binder.restoreCallingIdentity(token); 18963 } 18964 } 18965 } else { 18966 throw new IllegalArgumentException("No selective enforcement for " + permission); 18967 } 18968 } 18969 18970 @Override 18971 @Deprecated 18972 public boolean isPermissionEnforced(String permission) { 18973 return true; 18974 } 18975 18976 @Override 18977 public boolean isStorageLow() { 18978 final long token = Binder.clearCallingIdentity(); 18979 try { 18980 final DeviceStorageMonitorInternal 18981 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 18982 if (dsm != null) { 18983 return dsm.isMemoryLow(); 18984 } else { 18985 return false; 18986 } 18987 } finally { 18988 Binder.restoreCallingIdentity(token); 18989 } 18990 } 18991 18992 @Override 18993 public IPackageInstaller getPackageInstaller() { 18994 return mInstallerService; 18995 } 18996 18997 private boolean userNeedsBadging(int userId) { 18998 int index = mUserNeedsBadging.indexOfKey(userId); 18999 if (index < 0) { 19000 final UserInfo userInfo; 19001 final long token = Binder.clearCallingIdentity(); 19002 try { 19003 userInfo = sUserManager.getUserInfo(userId); 19004 } finally { 19005 Binder.restoreCallingIdentity(token); 19006 } 19007 final boolean b; 19008 if (userInfo != null && userInfo.isManagedProfile()) { 19009 b = true; 19010 } else { 19011 b = false; 19012 } 19013 mUserNeedsBadging.put(userId, b); 19014 return b; 19015 } 19016 return mUserNeedsBadging.valueAt(index); 19017 } 19018 19019 @Override 19020 public KeySet getKeySetByAlias(String packageName, String alias) { 19021 if (packageName == null || alias == null) { 19022 return null; 19023 } 19024 synchronized(mPackages) { 19025 final PackageParser.Package pkg = mPackages.get(packageName); 19026 if (pkg == null) { 19027 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19028 throw new IllegalArgumentException("Unknown package: " + packageName); 19029 } 19030 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19031 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 19032 } 19033 } 19034 19035 @Override 19036 public KeySet getSigningKeySet(String packageName) { 19037 if (packageName == null) { 19038 return null; 19039 } 19040 synchronized(mPackages) { 19041 final PackageParser.Package pkg = mPackages.get(packageName); 19042 if (pkg == null) { 19043 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19044 throw new IllegalArgumentException("Unknown package: " + packageName); 19045 } 19046 if (pkg.applicationInfo.uid != Binder.getCallingUid() 19047 && Process.SYSTEM_UID != Binder.getCallingUid()) { 19048 throw new SecurityException("May not access signing KeySet of other apps."); 19049 } 19050 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19051 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 19052 } 19053 } 19054 19055 @Override 19056 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 19057 if (packageName == null || ks == null) { 19058 return false; 19059 } 19060 synchronized(mPackages) { 19061 final PackageParser.Package pkg = mPackages.get(packageName); 19062 if (pkg == null) { 19063 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19064 throw new IllegalArgumentException("Unknown package: " + packageName); 19065 } 19066 IBinder ksh = ks.getToken(); 19067 if (ksh instanceof KeySetHandle) { 19068 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19069 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 19070 } 19071 return false; 19072 } 19073 } 19074 19075 @Override 19076 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 19077 if (packageName == null || ks == null) { 19078 return false; 19079 } 19080 synchronized(mPackages) { 19081 final PackageParser.Package pkg = mPackages.get(packageName); 19082 if (pkg == null) { 19083 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19084 throw new IllegalArgumentException("Unknown package: " + packageName); 19085 } 19086 IBinder ksh = ks.getToken(); 19087 if (ksh instanceof KeySetHandle) { 19088 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19089 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 19090 } 19091 return false; 19092 } 19093 } 19094 19095 private void deletePackageIfUnusedLPr(final String packageName) { 19096 PackageSetting ps = mSettings.mPackages.get(packageName); 19097 if (ps == null) { 19098 return; 19099 } 19100 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 19101 // TODO Implement atomic delete if package is unused 19102 // It is currently possible that the package will be deleted even if it is installed 19103 // after this method returns. 19104 mHandler.post(new Runnable() { 19105 public void run() { 19106 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 19107 } 19108 }); 19109 } 19110 } 19111 19112 /** 19113 * Check and throw if the given before/after packages would be considered a 19114 * downgrade. 19115 */ 19116 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 19117 throws PackageManagerException { 19118 if (after.versionCode < before.mVersionCode) { 19119 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19120 "Update version code " + after.versionCode + " is older than current " 19121 + before.mVersionCode); 19122 } else if (after.versionCode == before.mVersionCode) { 19123 if (after.baseRevisionCode < before.baseRevisionCode) { 19124 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19125 "Update base revision code " + after.baseRevisionCode 19126 + " is older than current " + before.baseRevisionCode); 19127 } 19128 19129 if (!ArrayUtils.isEmpty(after.splitNames)) { 19130 for (int i = 0; i < after.splitNames.length; i++) { 19131 final String splitName = after.splitNames[i]; 19132 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 19133 if (j != -1) { 19134 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 19135 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19136 "Update split " + splitName + " revision code " 19137 + after.splitRevisionCodes[i] + " is older than current " 19138 + before.splitRevisionCodes[j]); 19139 } 19140 } 19141 } 19142 } 19143 } 19144 } 19145 19146 private static class MoveCallbacks extends Handler { 19147 private static final int MSG_CREATED = 1; 19148 private static final int MSG_STATUS_CHANGED = 2; 19149 19150 private final RemoteCallbackList<IPackageMoveObserver> 19151 mCallbacks = new RemoteCallbackList<>(); 19152 19153 private final SparseIntArray mLastStatus = new SparseIntArray(); 19154 19155 public MoveCallbacks(Looper looper) { 19156 super(looper); 19157 } 19158 19159 public void register(IPackageMoveObserver callback) { 19160 mCallbacks.register(callback); 19161 } 19162 19163 public void unregister(IPackageMoveObserver callback) { 19164 mCallbacks.unregister(callback); 19165 } 19166 19167 @Override 19168 public void handleMessage(Message msg) { 19169 final SomeArgs args = (SomeArgs) msg.obj; 19170 final int n = mCallbacks.beginBroadcast(); 19171 for (int i = 0; i < n; i++) { 19172 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 19173 try { 19174 invokeCallback(callback, msg.what, args); 19175 } catch (RemoteException ignored) { 19176 } 19177 } 19178 mCallbacks.finishBroadcast(); 19179 args.recycle(); 19180 } 19181 19182 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 19183 throws RemoteException { 19184 switch (what) { 19185 case MSG_CREATED: { 19186 callback.onCreated(args.argi1, (Bundle) args.arg2); 19187 break; 19188 } 19189 case MSG_STATUS_CHANGED: { 19190 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 19191 break; 19192 } 19193 } 19194 } 19195 19196 private void notifyCreated(int moveId, Bundle extras) { 19197 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 19198 19199 final SomeArgs args = SomeArgs.obtain(); 19200 args.argi1 = moveId; 19201 args.arg2 = extras; 19202 obtainMessage(MSG_CREATED, args).sendToTarget(); 19203 } 19204 19205 private void notifyStatusChanged(int moveId, int status) { 19206 notifyStatusChanged(moveId, status, -1); 19207 } 19208 19209 private void notifyStatusChanged(int moveId, int status, long estMillis) { 19210 Slog.v(TAG, "Move " + moveId + " status " + status); 19211 19212 final SomeArgs args = SomeArgs.obtain(); 19213 args.argi1 = moveId; 19214 args.argi2 = status; 19215 args.arg3 = estMillis; 19216 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 19217 19218 synchronized (mLastStatus) { 19219 mLastStatus.put(moveId, status); 19220 } 19221 } 19222 } 19223 19224 private final static class OnPermissionChangeListeners extends Handler { 19225 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 19226 19227 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 19228 new RemoteCallbackList<>(); 19229 19230 public OnPermissionChangeListeners(Looper looper) { 19231 super(looper); 19232 } 19233 19234 @Override 19235 public void handleMessage(Message msg) { 19236 switch (msg.what) { 19237 case MSG_ON_PERMISSIONS_CHANGED: { 19238 final int uid = msg.arg1; 19239 handleOnPermissionsChanged(uid); 19240 } break; 19241 } 19242 } 19243 19244 public void addListenerLocked(IOnPermissionsChangeListener listener) { 19245 mPermissionListeners.register(listener); 19246 19247 } 19248 19249 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 19250 mPermissionListeners.unregister(listener); 19251 } 19252 19253 public void onPermissionsChanged(int uid) { 19254 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 19255 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 19256 } 19257 } 19258 19259 private void handleOnPermissionsChanged(int uid) { 19260 final int count = mPermissionListeners.beginBroadcast(); 19261 try { 19262 for (int i = 0; i < count; i++) { 19263 IOnPermissionsChangeListener callback = mPermissionListeners 19264 .getBroadcastItem(i); 19265 try { 19266 callback.onPermissionsChanged(uid); 19267 } catch (RemoteException e) { 19268 Log.e(TAG, "Permission listener is dead", e); 19269 } 19270 } 19271 } finally { 19272 mPermissionListeners.finishBroadcast(); 19273 } 19274 } 19275 } 19276 19277 private class PackageManagerInternalImpl extends PackageManagerInternal { 19278 @Override 19279 public void setLocationPackagesProvider(PackagesProvider provider) { 19280 synchronized (mPackages) { 19281 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 19282 } 19283 } 19284 19285 @Override 19286 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 19287 synchronized (mPackages) { 19288 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 19289 } 19290 } 19291 19292 @Override 19293 public void setSmsAppPackagesProvider(PackagesProvider provider) { 19294 synchronized (mPackages) { 19295 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 19296 } 19297 } 19298 19299 @Override 19300 public void setDialerAppPackagesProvider(PackagesProvider provider) { 19301 synchronized (mPackages) { 19302 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 19303 } 19304 } 19305 19306 @Override 19307 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 19308 synchronized (mPackages) { 19309 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 19310 } 19311 } 19312 19313 @Override 19314 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 19315 synchronized (mPackages) { 19316 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 19317 } 19318 } 19319 19320 @Override 19321 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 19322 synchronized (mPackages) { 19323 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 19324 packageName, userId); 19325 } 19326 } 19327 19328 @Override 19329 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 19330 synchronized (mPackages) { 19331 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 19332 packageName, userId); 19333 } 19334 } 19335 19336 @Override 19337 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 19338 synchronized (mPackages) { 19339 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 19340 packageName, userId); 19341 } 19342 } 19343 19344 @Override 19345 public void setKeepUninstalledPackages(final List<String> packageList) { 19346 Preconditions.checkNotNull(packageList); 19347 List<String> removedFromList = null; 19348 synchronized (mPackages) { 19349 if (mKeepUninstalledPackages != null) { 19350 final int packagesCount = mKeepUninstalledPackages.size(); 19351 for (int i = 0; i < packagesCount; i++) { 19352 String oldPackage = mKeepUninstalledPackages.get(i); 19353 if (packageList != null && packageList.contains(oldPackage)) { 19354 continue; 19355 } 19356 if (removedFromList == null) { 19357 removedFromList = new ArrayList<>(); 19358 } 19359 removedFromList.add(oldPackage); 19360 } 19361 } 19362 mKeepUninstalledPackages = new ArrayList<>(packageList); 19363 if (removedFromList != null) { 19364 final int removedCount = removedFromList.size(); 19365 for (int i = 0; i < removedCount; i++) { 19366 deletePackageIfUnusedLPr(removedFromList.get(i)); 19367 } 19368 } 19369 } 19370 } 19371 19372 @Override 19373 public boolean isPermissionsReviewRequired(String packageName, int userId) { 19374 synchronized (mPackages) { 19375 // If we do not support permission review, done. 19376 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 19377 return false; 19378 } 19379 19380 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 19381 if (packageSetting == null) { 19382 return false; 19383 } 19384 19385 // Permission review applies only to apps not supporting the new permission model. 19386 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 19387 return false; 19388 } 19389 19390 // Legacy apps have the permission and get user consent on launch. 19391 PermissionsState permissionsState = packageSetting.getPermissionsState(); 19392 return permissionsState.isPermissionReviewRequired(userId); 19393 } 19394 } 19395 19396 @Override 19397 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 19398 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 19399 } 19400 19401 @Override 19402 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 19403 int userId) { 19404 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 19405 } 19406 } 19407 19408 @Override 19409 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 19410 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 19411 synchronized (mPackages) { 19412 final long identity = Binder.clearCallingIdentity(); 19413 try { 19414 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 19415 packageNames, userId); 19416 } finally { 19417 Binder.restoreCallingIdentity(identity); 19418 } 19419 } 19420 } 19421 19422 private static void enforceSystemOrPhoneCaller(String tag) { 19423 int callingUid = Binder.getCallingUid(); 19424 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 19425 throw new SecurityException( 19426 "Cannot call " + tag + " from UID " + callingUid); 19427 } 19428 } 19429 19430 boolean isHistoricalPackageUsageAvailable() { 19431 return mPackageUsage.isHistoricalPackageUsageAvailable(); 19432 } 19433 19434 /** 19435 * Return a <b>copy</b> of the collection of packages known to the package manager. 19436 * @return A copy of the values of mPackages. 19437 */ 19438 Collection<PackageParser.Package> getPackages() { 19439 synchronized (mPackages) { 19440 return new ArrayList<>(mPackages.values()); 19441 } 19442 } 19443} 19444