PackageManagerService.java revision 4f858aaa5a7ef493e79e6d35a8d526f5d8de97e9
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_DISABLED_COMPONENTS; 65import static android.content.pm.PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE; 66import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 67import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 68import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 69import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 70import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 71import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 72import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 73import static android.content.pm.PackageManager.PERMISSION_DENIED; 74import static android.content.pm.PackageManager.PERMISSION_GRANTED; 75import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 76import static android.content.pm.PackageParser.isApkFile; 77import static android.os.Process.PACKAGE_INFO_GID; 78import static android.os.Process.SYSTEM_UID; 79import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 80import static android.system.OsConstants.O_CREAT; 81import static android.system.OsConstants.O_RDWR; 82 83import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 84import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 85import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 86import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 87import static com.android.internal.util.ArrayUtils.appendInt; 88import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 89import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 90import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 91import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 92import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 93import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 94import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 95import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 96import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 97 98import android.Manifest; 99import android.annotation.NonNull; 100import android.annotation.Nullable; 101import android.app.ActivityManager; 102import android.app.ActivityManagerNative; 103import android.app.IActivityManager; 104import android.app.admin.IDevicePolicyManager; 105import android.app.backup.IBackupManager; 106import android.content.BroadcastReceiver; 107import android.content.ComponentName; 108import android.content.Context; 109import android.content.IIntentReceiver; 110import android.content.Intent; 111import android.content.IntentFilter; 112import android.content.IntentSender; 113import android.content.IntentSender.SendIntentException; 114import android.content.ServiceConnection; 115import android.content.pm.ActivityInfo; 116import android.content.pm.ApplicationInfo; 117import android.content.pm.AppsQueryHelper; 118import android.content.pm.ComponentInfo; 119import android.content.pm.EphemeralApplicationInfo; 120import android.content.pm.EphemeralResolveInfo; 121import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 122import android.content.pm.FeatureInfo; 123import android.content.pm.IOnPermissionsChangeListener; 124import android.content.pm.IPackageDataObserver; 125import android.content.pm.IPackageDeleteObserver; 126import android.content.pm.IPackageDeleteObserver2; 127import android.content.pm.IPackageInstallObserver2; 128import android.content.pm.IPackageInstaller; 129import android.content.pm.IPackageManager; 130import android.content.pm.IPackageMoveObserver; 131import android.content.pm.IPackageStatsObserver; 132import android.content.pm.InstrumentationInfo; 133import android.content.pm.IntentFilterVerificationInfo; 134import android.content.pm.KeySet; 135import android.content.pm.PackageCleanItem; 136import android.content.pm.PackageInfo; 137import android.content.pm.PackageInfoLite; 138import android.content.pm.PackageInstaller; 139import android.content.pm.PackageManager; 140import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 141import android.content.pm.PackageManagerInternal; 142import android.content.pm.PackageParser; 143import android.content.pm.PackageParser.ActivityIntentInfo; 144import android.content.pm.PackageParser.PackageLite; 145import android.content.pm.PackageParser.PackageParserException; 146import android.content.pm.PackageStats; 147import android.content.pm.PackageUserState; 148import android.content.pm.ParceledListSlice; 149import android.content.pm.PermissionGroupInfo; 150import android.content.pm.PermissionInfo; 151import android.content.pm.ProviderInfo; 152import android.content.pm.ResolveInfo; 153import android.content.pm.ServiceInfo; 154import android.content.pm.Signature; 155import android.content.pm.UserInfo; 156import android.content.pm.VerifierDeviceIdentity; 157import android.content.pm.VerifierInfo; 158import android.content.res.Resources; 159import android.graphics.Bitmap; 160import android.hardware.display.DisplayManager; 161import android.net.Uri; 162import android.os.Binder; 163import android.os.Build; 164import android.os.Bundle; 165import android.os.Debug; 166import android.os.Environment; 167import android.os.Environment.UserEnvironment; 168import android.os.FileUtils; 169import android.os.Handler; 170import android.os.IBinder; 171import android.os.Looper; 172import android.os.Message; 173import android.os.Parcel; 174import android.os.ParcelFileDescriptor; 175import android.os.Parcelable; 176import android.os.Process; 177import android.os.RemoteCallbackList; 178import android.os.RemoteException; 179import android.os.ResultReceiver; 180import android.os.SELinux; 181import android.os.ServiceManager; 182import android.os.SystemClock; 183import android.os.SystemProperties; 184import android.os.Trace; 185import android.os.UserHandle; 186import android.os.UserManager; 187import android.os.storage.IMountService; 188import android.os.storage.MountServiceInternal; 189import android.os.storage.StorageEventListener; 190import android.os.storage.StorageManager; 191import android.os.storage.VolumeInfo; 192import android.os.storage.VolumeRecord; 193import android.security.KeyStore; 194import android.security.SystemKeyStore; 195import android.system.ErrnoException; 196import android.system.Os; 197import android.text.TextUtils; 198import android.text.format.DateUtils; 199import android.util.ArrayMap; 200import android.util.ArraySet; 201import android.util.AtomicFile; 202import android.util.DisplayMetrics; 203import android.util.EventLog; 204import android.util.ExceptionUtils; 205import android.util.Log; 206import android.util.LogPrinter; 207import android.util.MathUtils; 208import android.util.PrintStreamPrinter; 209import android.util.Slog; 210import android.util.SparseArray; 211import android.util.SparseBooleanArray; 212import android.util.SparseIntArray; 213import android.util.Xml; 214import android.view.Display; 215 216import com.android.internal.R; 217import com.android.internal.annotations.GuardedBy; 218import com.android.internal.app.IMediaContainerService; 219import com.android.internal.app.ResolverActivity; 220import com.android.internal.content.NativeLibraryHelper; 221import com.android.internal.content.PackageHelper; 222import com.android.internal.os.IParcelFileDescriptorFactory; 223import com.android.internal.os.InstallerConnection.InstallerException; 224import com.android.internal.os.SomeArgs; 225import com.android.internal.os.Zygote; 226import com.android.internal.util.ArrayUtils; 227import com.android.internal.util.FastPrintWriter; 228import com.android.internal.util.FastXmlSerializer; 229import com.android.internal.util.IndentingPrintWriter; 230import com.android.internal.util.Preconditions; 231import com.android.internal.util.XmlUtils; 232import com.android.server.EventLogTags; 233import com.android.server.FgThread; 234import com.android.server.IntentResolver; 235import com.android.server.LocalServices; 236import com.android.server.ServiceThread; 237import com.android.server.SystemConfig; 238import com.android.server.Watchdog; 239import com.android.server.pm.PermissionsState.PermissionState; 240import com.android.server.pm.Settings.DatabaseVersion; 241import com.android.server.pm.Settings.VersionInfo; 242import com.android.server.storage.DeviceStorageMonitorInternal; 243 244import dalvik.system.DexFile; 245import dalvik.system.VMRuntime; 246 247import libcore.io.IoUtils; 248import libcore.util.EmptyArray; 249 250import org.xmlpull.v1.XmlPullParser; 251import org.xmlpull.v1.XmlPullParserException; 252import org.xmlpull.v1.XmlSerializer; 253 254import java.io.BufferedInputStream; 255import java.io.BufferedOutputStream; 256import java.io.BufferedReader; 257import java.io.ByteArrayInputStream; 258import java.io.ByteArrayOutputStream; 259import java.io.File; 260import java.io.FileDescriptor; 261import java.io.FileNotFoundException; 262import java.io.FileOutputStream; 263import java.io.FileReader; 264import java.io.FilenameFilter; 265import java.io.IOException; 266import java.io.InputStream; 267import java.io.PrintWriter; 268import java.nio.charset.StandardCharsets; 269import java.security.MessageDigest; 270import java.security.NoSuchAlgorithmException; 271import java.security.PublicKey; 272import java.security.cert.CertificateEncodingException; 273import java.security.cert.CertificateException; 274import java.text.SimpleDateFormat; 275import java.util.ArrayList; 276import java.util.Arrays; 277import java.util.Collection; 278import java.util.Collections; 279import java.util.Comparator; 280import java.util.Date; 281import java.util.HashSet; 282import java.util.Iterator; 283import java.util.List; 284import java.util.Map; 285import java.util.Objects; 286import java.util.Set; 287import java.util.concurrent.CountDownLatch; 288import java.util.concurrent.TimeUnit; 289import java.util.concurrent.atomic.AtomicBoolean; 290import java.util.concurrent.atomic.AtomicInteger; 291import java.util.concurrent.atomic.AtomicLong; 292 293/** 294 * Keep track of all those .apks everywhere. 295 * 296 * This is very central to the platform's security; please run the unit 297 * tests whenever making modifications here: 298 * 299runtest -c android.content.pm.PackageManagerTests frameworks-core 300 * 301 * {@hide} 302 */ 303public class PackageManagerService extends IPackageManager.Stub { 304 static final String TAG = "PackageManager"; 305 static final boolean DEBUG_SETTINGS = false; 306 static final boolean DEBUG_PREFERRED = false; 307 static final boolean DEBUG_UPGRADE = false; 308 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 309 private static final boolean DEBUG_BACKUP = false; 310 private static final boolean DEBUG_INSTALL = false; 311 private static final boolean DEBUG_REMOVE = false; 312 private static final boolean DEBUG_BROADCASTS = false; 313 private static final boolean DEBUG_SHOW_INFO = false; 314 private static final boolean DEBUG_PACKAGE_INFO = false; 315 private static final boolean DEBUG_INTENT_MATCHING = false; 316 private static final boolean DEBUG_PACKAGE_SCANNING = false; 317 private static final boolean DEBUG_VERIFY = false; 318 319 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 320 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 321 // user, but by default initialize to this. 322 static final boolean DEBUG_DEXOPT = false; 323 324 private static final boolean DEBUG_ABI_SELECTION = false; 325 private static final boolean DEBUG_EPHEMERAL = false; 326 private static final boolean DEBUG_TRIAGED_MISSING = false; 327 private static final boolean DEBUG_APP_DATA = false; 328 329 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 330 331 private static final boolean DISABLE_EPHEMERAL_APPS = true; 332 333 private static final int RADIO_UID = Process.PHONE_UID; 334 private static final int LOG_UID = Process.LOG_UID; 335 private static final int NFC_UID = Process.NFC_UID; 336 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 337 private static final int SHELL_UID = Process.SHELL_UID; 338 339 // Cap the size of permission trees that 3rd party apps can define 340 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 341 342 // Suffix used during package installation when copying/moving 343 // package apks to install directory. 344 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 345 346 static final int SCAN_NO_DEX = 1<<1; 347 static final int SCAN_FORCE_DEX = 1<<2; 348 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 349 static final int SCAN_NEW_INSTALL = 1<<4; 350 static final int SCAN_NO_PATHS = 1<<5; 351 static final int SCAN_UPDATE_TIME = 1<<6; 352 static final int SCAN_DEFER_DEX = 1<<7; 353 static final int SCAN_BOOTING = 1<<8; 354 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 355 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 356 static final int SCAN_REPLACING = 1<<11; 357 static final int SCAN_REQUIRE_KNOWN = 1<<12; 358 static final int SCAN_MOVE = 1<<13; 359 static final int SCAN_INITIAL = 1<<14; 360 static final int SCAN_CHECK_ONLY = 1<<15; 361 362 static final int REMOVE_CHATTY = 1<<16; 363 364 private static final int[] EMPTY_INT_ARRAY = new int[0]; 365 366 /** 367 * Timeout (in milliseconds) after which the watchdog should declare that 368 * our handler thread is wedged. The usual default for such things is one 369 * minute but we sometimes do very lengthy I/O operations on this thread, 370 * such as installing multi-gigabyte applications, so ours needs to be longer. 371 */ 372 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 373 374 /** 375 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 376 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 377 * settings entry if available, otherwise we use the hardcoded default. If it's been 378 * more than this long since the last fstrim, we force one during the boot sequence. 379 * 380 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 381 * one gets run at the next available charging+idle time. This final mandatory 382 * no-fstrim check kicks in only of the other scheduling criteria is never met. 383 */ 384 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 385 386 /** 387 * Whether verification is enabled by default. 388 */ 389 private static final boolean DEFAULT_VERIFY_ENABLE = true; 390 391 /** 392 * The default maximum time to wait for the verification agent to return in 393 * milliseconds. 394 */ 395 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 396 397 /** 398 * The default response for package verification timeout. 399 * 400 * This can be either PackageManager.VERIFICATION_ALLOW or 401 * PackageManager.VERIFICATION_REJECT. 402 */ 403 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 404 405 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 406 407 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 408 DEFAULT_CONTAINER_PACKAGE, 409 "com.android.defcontainer.DefaultContainerService"); 410 411 private static final String KILL_APP_REASON_GIDS_CHANGED = 412 "permission grant or revoke changed gids"; 413 414 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 415 "permissions revoked"; 416 417 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 418 419 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 420 421 /** Permission grant: not grant the permission. */ 422 private static final int GRANT_DENIED = 1; 423 424 /** Permission grant: grant the permission as an install permission. */ 425 private static final int GRANT_INSTALL = 2; 426 427 /** Permission grant: grant the permission as a runtime one. */ 428 private static final int GRANT_RUNTIME = 3; 429 430 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 431 private static final int GRANT_UPGRADE = 4; 432 433 /** Canonical intent used to identify what counts as a "web browser" app */ 434 private static final Intent sBrowserIntent; 435 static { 436 sBrowserIntent = new Intent(); 437 sBrowserIntent.setAction(Intent.ACTION_VIEW); 438 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 439 sBrowserIntent.setData(Uri.parse("http:")); 440 } 441 442 final ServiceThread mHandlerThread; 443 444 final PackageHandler mHandler; 445 446 /** 447 * Messages for {@link #mHandler} that need to wait for system ready before 448 * being dispatched. 449 */ 450 private ArrayList<Message> mPostSystemReadyMessages; 451 452 final int mSdkVersion = Build.VERSION.SDK_INT; 453 454 final Context mContext; 455 final boolean mFactoryTest; 456 final boolean mOnlyCore; 457 final DisplayMetrics mMetrics; 458 final int mDefParseFlags; 459 final String[] mSeparateProcesses; 460 final boolean mIsUpgrade; 461 462 /** The location for ASEC container files on internal storage. */ 463 final String mAsecInternalPath; 464 465 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 466 // LOCK HELD. Can be called with mInstallLock held. 467 @GuardedBy("mInstallLock") 468 final Installer mInstaller; 469 470 /** Directory where installed third-party apps stored */ 471 final File mAppInstallDir; 472 final File mEphemeralInstallDir; 473 474 /** 475 * Directory to which applications installed internally have their 476 * 32 bit native libraries copied. 477 */ 478 private File mAppLib32InstallDir; 479 480 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 481 // apps. 482 final File mDrmAppPrivateInstallDir; 483 484 // ---------------------------------------------------------------- 485 486 // Lock for state used when installing and doing other long running 487 // operations. Methods that must be called with this lock held have 488 // the suffix "LI". 489 final Object mInstallLock = new Object(); 490 491 // ---------------------------------------------------------------- 492 493 // Keys are String (package name), values are Package. This also serves 494 // as the lock for the global state. Methods that must be called with 495 // this lock held have the prefix "LP". 496 @GuardedBy("mPackages") 497 final ArrayMap<String, PackageParser.Package> mPackages = 498 new ArrayMap<String, PackageParser.Package>(); 499 500 // Tracks available target package names -> overlay package paths. 501 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 502 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 503 504 /** 505 * Tracks new system packages [received in an OTA] that we expect to 506 * find updated user-installed versions. Keys are package name, values 507 * are package location. 508 */ 509 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 510 511 /** 512 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 513 */ 514 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 515 /** 516 * Whether or not system app permissions should be promoted from install to runtime. 517 */ 518 boolean mPromoteSystemApps; 519 520 final Settings mSettings; 521 boolean mRestoredSettings; 522 523 // System configuration read by SystemConfig. 524 final int[] mGlobalGids; 525 final SparseArray<ArraySet<String>> mSystemPermissions; 526 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 527 528 // If mac_permissions.xml was found for seinfo labeling. 529 boolean mFoundPolicyFile; 530 531 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 532 533 public static final class SharedLibraryEntry { 534 public final String path; 535 public final String apk; 536 537 SharedLibraryEntry(String _path, String _apk) { 538 path = _path; 539 apk = _apk; 540 } 541 } 542 543 // Currently known shared libraries. 544 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 545 new ArrayMap<String, SharedLibraryEntry>(); 546 547 // All available activities, for your resolving pleasure. 548 final ActivityIntentResolver mActivities = 549 new ActivityIntentResolver(); 550 551 // All available receivers, for your resolving pleasure. 552 final ActivityIntentResolver mReceivers = 553 new ActivityIntentResolver(); 554 555 // All available services, for your resolving pleasure. 556 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 557 558 // All available providers, for your resolving pleasure. 559 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 560 561 // Mapping from provider base names (first directory in content URI codePath) 562 // to the provider information. 563 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 564 new ArrayMap<String, PackageParser.Provider>(); 565 566 // Mapping from instrumentation class names to info about them. 567 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 568 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 569 570 // Mapping from permission names to info about them. 571 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 572 new ArrayMap<String, PackageParser.PermissionGroup>(); 573 574 // Packages whose data we have transfered into another package, thus 575 // should no longer exist. 576 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 577 578 // Broadcast actions that are only available to the system. 579 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 580 581 /** List of packages waiting for verification. */ 582 final SparseArray<PackageVerificationState> mPendingVerification 583 = new SparseArray<PackageVerificationState>(); 584 585 /** Set of packages associated with each app op permission. */ 586 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 587 588 final PackageInstallerService mInstallerService; 589 590 private final PackageDexOptimizer mPackageDexOptimizer; 591 592 private AtomicInteger mNextMoveId = new AtomicInteger(); 593 private final MoveCallbacks mMoveCallbacks; 594 595 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 596 597 // Cache of users who need badging. 598 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 599 600 /** Token for keys in mPendingVerification. */ 601 private int mPendingVerificationToken = 0; 602 603 volatile boolean mSystemReady; 604 volatile boolean mSafeMode; 605 volatile boolean mHasSystemUidErrors; 606 607 ApplicationInfo mAndroidApplication; 608 final ActivityInfo mResolveActivity = new ActivityInfo(); 609 final ResolveInfo mResolveInfo = new ResolveInfo(); 610 ComponentName mResolveComponentName; 611 PackageParser.Package mPlatformPackage; 612 ComponentName mCustomResolverComponentName; 613 614 boolean mResolverReplaced = false; 615 616 private final @Nullable ComponentName mIntentFilterVerifierComponent; 617 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 618 619 private int mIntentFilterVerificationToken = 0; 620 621 /** Component that knows whether or not an ephemeral application exists */ 622 final ComponentName mEphemeralResolverComponent; 623 /** The service connection to the ephemeral resolver */ 624 final EphemeralResolverConnection mEphemeralResolverConnection; 625 626 /** Component used to install ephemeral applications */ 627 final ComponentName mEphemeralInstallerComponent; 628 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 629 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 630 631 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 632 = new SparseArray<IntentFilterVerificationState>(); 633 634 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 635 new DefaultPermissionGrantPolicy(this); 636 637 // List of packages names to keep cached, even if they are uninstalled for all users 638 private List<String> mKeepUninstalledPackages; 639 640 private boolean mUseJitProfiles = 641 SystemProperties.getBoolean("dalvik.vm.usejitprofiles", false); 642 643 private static class IFVerificationParams { 644 PackageParser.Package pkg; 645 boolean replacing; 646 int userId; 647 int verifierUid; 648 649 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 650 int _userId, int _verifierUid) { 651 pkg = _pkg; 652 replacing = _replacing; 653 userId = _userId; 654 replacing = _replacing; 655 verifierUid = _verifierUid; 656 } 657 } 658 659 private interface IntentFilterVerifier<T extends IntentFilter> { 660 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 661 T filter, String packageName); 662 void startVerifications(int userId); 663 void receiveVerificationResponse(int verificationId); 664 } 665 666 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 667 private Context mContext; 668 private ComponentName mIntentFilterVerifierComponent; 669 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 670 671 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 672 mContext = context; 673 mIntentFilterVerifierComponent = verifierComponent; 674 } 675 676 private String getDefaultScheme() { 677 return IntentFilter.SCHEME_HTTPS; 678 } 679 680 @Override 681 public void startVerifications(int userId) { 682 // Launch verifications requests 683 int count = mCurrentIntentFilterVerifications.size(); 684 for (int n=0; n<count; n++) { 685 int verificationId = mCurrentIntentFilterVerifications.get(n); 686 final IntentFilterVerificationState ivs = 687 mIntentFilterVerificationStates.get(verificationId); 688 689 String packageName = ivs.getPackageName(); 690 691 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 692 final int filterCount = filters.size(); 693 ArraySet<String> domainsSet = new ArraySet<>(); 694 for (int m=0; m<filterCount; m++) { 695 PackageParser.ActivityIntentInfo filter = filters.get(m); 696 domainsSet.addAll(filter.getHostsList()); 697 } 698 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 699 synchronized (mPackages) { 700 if (mSettings.createIntentFilterVerificationIfNeededLPw( 701 packageName, domainsList) != null) { 702 scheduleWriteSettingsLocked(); 703 } 704 } 705 sendVerificationRequest(userId, verificationId, ivs); 706 } 707 mCurrentIntentFilterVerifications.clear(); 708 } 709 710 private void sendVerificationRequest(int userId, int verificationId, 711 IntentFilterVerificationState ivs) { 712 713 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 714 verificationIntent.putExtra( 715 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 716 verificationId); 717 verificationIntent.putExtra( 718 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 719 getDefaultScheme()); 720 verificationIntent.putExtra( 721 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 722 ivs.getHostsString()); 723 verificationIntent.putExtra( 724 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 725 ivs.getPackageName()); 726 verificationIntent.setComponent(mIntentFilterVerifierComponent); 727 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 728 729 UserHandle user = new UserHandle(userId); 730 mContext.sendBroadcastAsUser(verificationIntent, user); 731 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 732 "Sending IntentFilter verification broadcast"); 733 } 734 735 public void receiveVerificationResponse(int verificationId) { 736 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 737 738 final boolean verified = ivs.isVerified(); 739 740 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 741 final int count = filters.size(); 742 if (DEBUG_DOMAIN_VERIFICATION) { 743 Slog.i(TAG, "Received verification response " + verificationId 744 + " for " + count + " filters, verified=" + verified); 745 } 746 for (int n=0; n<count; n++) { 747 PackageParser.ActivityIntentInfo filter = filters.get(n); 748 filter.setVerified(verified); 749 750 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 751 + " verified with result:" + verified + " and hosts:" 752 + ivs.getHostsString()); 753 } 754 755 mIntentFilterVerificationStates.remove(verificationId); 756 757 final String packageName = ivs.getPackageName(); 758 IntentFilterVerificationInfo ivi = null; 759 760 synchronized (mPackages) { 761 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 762 } 763 if (ivi == null) { 764 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 765 + verificationId + " packageName:" + packageName); 766 return; 767 } 768 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 769 "Updating IntentFilterVerificationInfo for package " + packageName 770 +" verificationId:" + verificationId); 771 772 synchronized (mPackages) { 773 if (verified) { 774 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 775 } else { 776 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 777 } 778 scheduleWriteSettingsLocked(); 779 780 final int userId = ivs.getUserId(); 781 if (userId != UserHandle.USER_ALL) { 782 final int userStatus = 783 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 784 785 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 786 boolean needUpdate = false; 787 788 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 789 // already been set by the User thru the Disambiguation dialog 790 switch (userStatus) { 791 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 792 if (verified) { 793 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 794 } else { 795 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 796 } 797 needUpdate = true; 798 break; 799 800 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 801 if (verified) { 802 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 803 needUpdate = true; 804 } 805 break; 806 807 default: 808 // Nothing to do 809 } 810 811 if (needUpdate) { 812 mSettings.updateIntentFilterVerificationStatusLPw( 813 packageName, updatedStatus, userId); 814 scheduleWritePackageRestrictionsLocked(userId); 815 } 816 } 817 } 818 } 819 820 @Override 821 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 822 ActivityIntentInfo filter, String packageName) { 823 if (!hasValidDomains(filter)) { 824 return false; 825 } 826 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 827 if (ivs == null) { 828 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 829 packageName); 830 } 831 if (DEBUG_DOMAIN_VERIFICATION) { 832 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 833 } 834 ivs.addFilter(filter); 835 return true; 836 } 837 838 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 839 int userId, int verificationId, String packageName) { 840 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 841 verifierUid, userId, packageName); 842 ivs.setPendingState(); 843 synchronized (mPackages) { 844 mIntentFilterVerificationStates.append(verificationId, ivs); 845 mCurrentIntentFilterVerifications.add(verificationId); 846 } 847 return ivs; 848 } 849 } 850 851 private static boolean hasValidDomains(ActivityIntentInfo filter) { 852 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 853 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 854 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 855 } 856 857 // Set of pending broadcasts for aggregating enable/disable of components. 858 static class PendingPackageBroadcasts { 859 // for each user id, a map of <package name -> components within that package> 860 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 861 862 public PendingPackageBroadcasts() { 863 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 864 } 865 866 public ArrayList<String> get(int userId, String packageName) { 867 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 868 return packages.get(packageName); 869 } 870 871 public void put(int userId, String packageName, ArrayList<String> components) { 872 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 873 packages.put(packageName, components); 874 } 875 876 public void remove(int userId, String packageName) { 877 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 878 if (packages != null) { 879 packages.remove(packageName); 880 } 881 } 882 883 public void remove(int userId) { 884 mUidMap.remove(userId); 885 } 886 887 public int userIdCount() { 888 return mUidMap.size(); 889 } 890 891 public int userIdAt(int n) { 892 return mUidMap.keyAt(n); 893 } 894 895 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 896 return mUidMap.get(userId); 897 } 898 899 public int size() { 900 // total number of pending broadcast entries across all userIds 901 int num = 0; 902 for (int i = 0; i< mUidMap.size(); i++) { 903 num += mUidMap.valueAt(i).size(); 904 } 905 return num; 906 } 907 908 public void clear() { 909 mUidMap.clear(); 910 } 911 912 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 913 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 914 if (map == null) { 915 map = new ArrayMap<String, ArrayList<String>>(); 916 mUidMap.put(userId, map); 917 } 918 return map; 919 } 920 } 921 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 922 923 // Service Connection to remote media container service to copy 924 // package uri's from external media onto secure containers 925 // or internal storage. 926 private IMediaContainerService mContainerService = null; 927 928 static final int SEND_PENDING_BROADCAST = 1; 929 static final int MCS_BOUND = 3; 930 static final int END_COPY = 4; 931 static final int INIT_COPY = 5; 932 static final int MCS_UNBIND = 6; 933 static final int START_CLEANING_PACKAGE = 7; 934 static final int FIND_INSTALL_LOC = 8; 935 static final int POST_INSTALL = 9; 936 static final int MCS_RECONNECT = 10; 937 static final int MCS_GIVE_UP = 11; 938 static final int UPDATED_MEDIA_STATUS = 12; 939 static final int WRITE_SETTINGS = 13; 940 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 941 static final int PACKAGE_VERIFIED = 15; 942 static final int CHECK_PENDING_VERIFICATION = 16; 943 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 944 static final int INTENT_FILTER_VERIFIED = 18; 945 946 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 947 948 // Delay time in millisecs 949 static final int BROADCAST_DELAY = 10 * 1000; 950 951 static UserManagerService sUserManager; 952 953 // Stores a list of users whose package restrictions file needs to be updated 954 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 955 956 final private DefaultContainerConnection mDefContainerConn = 957 new DefaultContainerConnection(); 958 class DefaultContainerConnection implements ServiceConnection { 959 public void onServiceConnected(ComponentName name, IBinder service) { 960 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 961 IMediaContainerService imcs = 962 IMediaContainerService.Stub.asInterface(service); 963 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 964 } 965 966 public void onServiceDisconnected(ComponentName name) { 967 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 968 } 969 } 970 971 // Recordkeeping of restore-after-install operations that are currently in flight 972 // between the Package Manager and the Backup Manager 973 static class PostInstallData { 974 public InstallArgs args; 975 public PackageInstalledInfo res; 976 977 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 978 args = _a; 979 res = _r; 980 } 981 } 982 983 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 984 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 985 986 // XML tags for backup/restore of various bits of state 987 private static final String TAG_PREFERRED_BACKUP = "pa"; 988 private static final String TAG_DEFAULT_APPS = "da"; 989 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 990 991 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 992 private static final String TAG_ALL_GRANTS = "rt-grants"; 993 private static final String TAG_GRANT = "grant"; 994 private static final String ATTR_PACKAGE_NAME = "pkg"; 995 996 private static final String TAG_PERMISSION = "perm"; 997 private static final String ATTR_PERMISSION_NAME = "name"; 998 private static final String ATTR_IS_GRANTED = "g"; 999 private static final String ATTR_USER_SET = "set"; 1000 private static final String ATTR_USER_FIXED = "fixed"; 1001 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1002 1003 // System/policy permission grants are not backed up 1004 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1005 FLAG_PERMISSION_POLICY_FIXED 1006 | FLAG_PERMISSION_SYSTEM_FIXED 1007 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1008 1009 // And we back up these user-adjusted states 1010 private static final int USER_RUNTIME_GRANT_MASK = 1011 FLAG_PERMISSION_USER_SET 1012 | FLAG_PERMISSION_USER_FIXED 1013 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1014 1015 final @Nullable String mRequiredVerifierPackage; 1016 final @Nullable String mRequiredInstallerPackage; 1017 1018 private final PackageUsage mPackageUsage = new PackageUsage(); 1019 1020 private class PackageUsage { 1021 private static final int WRITE_INTERVAL 1022 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1023 1024 private final Object mFileLock = new Object(); 1025 private final AtomicLong mLastWritten = new AtomicLong(0); 1026 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1027 1028 private boolean mIsHistoricalPackageUsageAvailable = true; 1029 1030 boolean isHistoricalPackageUsageAvailable() { 1031 return mIsHistoricalPackageUsageAvailable; 1032 } 1033 1034 void write(boolean force) { 1035 if (force) { 1036 writeInternal(); 1037 return; 1038 } 1039 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1040 && !DEBUG_DEXOPT) { 1041 return; 1042 } 1043 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1044 new Thread("PackageUsage_DiskWriter") { 1045 @Override 1046 public void run() { 1047 try { 1048 writeInternal(); 1049 } finally { 1050 mBackgroundWriteRunning.set(false); 1051 } 1052 } 1053 }.start(); 1054 } 1055 } 1056 1057 private void writeInternal() { 1058 synchronized (mPackages) { 1059 synchronized (mFileLock) { 1060 AtomicFile file = getFile(); 1061 FileOutputStream f = null; 1062 try { 1063 f = file.startWrite(); 1064 BufferedOutputStream out = new BufferedOutputStream(f); 1065 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1066 StringBuilder sb = new StringBuilder(); 1067 for (PackageParser.Package pkg : mPackages.values()) { 1068 if (pkg.mLastPackageUsageTimeInMills == 0) { 1069 continue; 1070 } 1071 sb.setLength(0); 1072 sb.append(pkg.packageName); 1073 sb.append(' '); 1074 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1075 sb.append('\n'); 1076 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1077 } 1078 out.flush(); 1079 file.finishWrite(f); 1080 } catch (IOException e) { 1081 if (f != null) { 1082 file.failWrite(f); 1083 } 1084 Log.e(TAG, "Failed to write package usage times", e); 1085 } 1086 } 1087 } 1088 mLastWritten.set(SystemClock.elapsedRealtime()); 1089 } 1090 1091 void readLP() { 1092 synchronized (mFileLock) { 1093 AtomicFile file = getFile(); 1094 BufferedInputStream in = null; 1095 try { 1096 in = new BufferedInputStream(file.openRead()); 1097 StringBuffer sb = new StringBuffer(); 1098 while (true) { 1099 String packageName = readToken(in, sb, ' '); 1100 if (packageName == null) { 1101 break; 1102 } 1103 String timeInMillisString = readToken(in, sb, '\n'); 1104 if (timeInMillisString == null) { 1105 throw new IOException("Failed to find last usage time for package " 1106 + packageName); 1107 } 1108 PackageParser.Package pkg = mPackages.get(packageName); 1109 if (pkg == null) { 1110 continue; 1111 } 1112 long timeInMillis; 1113 try { 1114 timeInMillis = Long.parseLong(timeInMillisString); 1115 } catch (NumberFormatException e) { 1116 throw new IOException("Failed to parse " + timeInMillisString 1117 + " as a long.", e); 1118 } 1119 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1120 } 1121 } catch (FileNotFoundException expected) { 1122 mIsHistoricalPackageUsageAvailable = false; 1123 } catch (IOException e) { 1124 Log.w(TAG, "Failed to read package usage times", e); 1125 } finally { 1126 IoUtils.closeQuietly(in); 1127 } 1128 } 1129 mLastWritten.set(SystemClock.elapsedRealtime()); 1130 } 1131 1132 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1133 throws IOException { 1134 sb.setLength(0); 1135 while (true) { 1136 int ch = in.read(); 1137 if (ch == -1) { 1138 if (sb.length() == 0) { 1139 return null; 1140 } 1141 throw new IOException("Unexpected EOF"); 1142 } 1143 if (ch == endOfToken) { 1144 return sb.toString(); 1145 } 1146 sb.append((char)ch); 1147 } 1148 } 1149 1150 private AtomicFile getFile() { 1151 File dataDir = Environment.getDataDirectory(); 1152 File systemDir = new File(dataDir, "system"); 1153 File fname = new File(systemDir, "package-usage.list"); 1154 return new AtomicFile(fname); 1155 } 1156 } 1157 1158 class PackageHandler extends Handler { 1159 private boolean mBound = false; 1160 final ArrayList<HandlerParams> mPendingInstalls = 1161 new ArrayList<HandlerParams>(); 1162 1163 private boolean connectToService() { 1164 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1165 " DefaultContainerService"); 1166 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1167 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1168 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1169 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1170 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1171 mBound = true; 1172 return true; 1173 } 1174 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1175 return false; 1176 } 1177 1178 private void disconnectService() { 1179 mContainerService = null; 1180 mBound = false; 1181 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1182 mContext.unbindService(mDefContainerConn); 1183 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1184 } 1185 1186 PackageHandler(Looper looper) { 1187 super(looper); 1188 } 1189 1190 public void handleMessage(Message msg) { 1191 try { 1192 doHandleMessage(msg); 1193 } finally { 1194 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1195 } 1196 } 1197 1198 void doHandleMessage(Message msg) { 1199 switch (msg.what) { 1200 case INIT_COPY: { 1201 HandlerParams params = (HandlerParams) msg.obj; 1202 int idx = mPendingInstalls.size(); 1203 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1204 // If a bind was already initiated we dont really 1205 // need to do anything. The pending install 1206 // will be processed later on. 1207 if (!mBound) { 1208 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1209 System.identityHashCode(mHandler)); 1210 // If this is the only one pending we might 1211 // have to bind to the service again. 1212 if (!connectToService()) { 1213 Slog.e(TAG, "Failed to bind to media container service"); 1214 params.serviceError(); 1215 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1216 System.identityHashCode(mHandler)); 1217 if (params.traceMethod != null) { 1218 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1219 params.traceCookie); 1220 } 1221 return; 1222 } else { 1223 // Once we bind to the service, the first 1224 // pending request will be processed. 1225 mPendingInstalls.add(idx, params); 1226 } 1227 } else { 1228 mPendingInstalls.add(idx, params); 1229 // Already bound to the service. Just make 1230 // sure we trigger off processing the first request. 1231 if (idx == 0) { 1232 mHandler.sendEmptyMessage(MCS_BOUND); 1233 } 1234 } 1235 break; 1236 } 1237 case MCS_BOUND: { 1238 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1239 if (msg.obj != null) { 1240 mContainerService = (IMediaContainerService) msg.obj; 1241 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1242 System.identityHashCode(mHandler)); 1243 } 1244 if (mContainerService == null) { 1245 if (!mBound) { 1246 // Something seriously wrong since we are not bound and we are not 1247 // waiting for connection. Bail out. 1248 Slog.e(TAG, "Cannot bind to media container service"); 1249 for (HandlerParams params : mPendingInstalls) { 1250 // Indicate service bind error 1251 params.serviceError(); 1252 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1253 System.identityHashCode(params)); 1254 if (params.traceMethod != null) { 1255 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1256 params.traceMethod, params.traceCookie); 1257 } 1258 return; 1259 } 1260 mPendingInstalls.clear(); 1261 } else { 1262 Slog.w(TAG, "Waiting to connect to media container service"); 1263 } 1264 } else if (mPendingInstalls.size() > 0) { 1265 HandlerParams params = mPendingInstalls.get(0); 1266 if (params != null) { 1267 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1268 System.identityHashCode(params)); 1269 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1270 if (params.startCopy()) { 1271 // We are done... look for more work or to 1272 // go idle. 1273 if (DEBUG_SD_INSTALL) Log.i(TAG, 1274 "Checking for more work or unbind..."); 1275 // Delete pending install 1276 if (mPendingInstalls.size() > 0) { 1277 mPendingInstalls.remove(0); 1278 } 1279 if (mPendingInstalls.size() == 0) { 1280 if (mBound) { 1281 if (DEBUG_SD_INSTALL) Log.i(TAG, 1282 "Posting delayed MCS_UNBIND"); 1283 removeMessages(MCS_UNBIND); 1284 Message ubmsg = obtainMessage(MCS_UNBIND); 1285 // Unbind after a little delay, to avoid 1286 // continual thrashing. 1287 sendMessageDelayed(ubmsg, 10000); 1288 } 1289 } else { 1290 // There are more pending requests in queue. 1291 // Just post MCS_BOUND message to trigger processing 1292 // of next pending install. 1293 if (DEBUG_SD_INSTALL) Log.i(TAG, 1294 "Posting MCS_BOUND for next work"); 1295 mHandler.sendEmptyMessage(MCS_BOUND); 1296 } 1297 } 1298 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1299 } 1300 } else { 1301 // Should never happen ideally. 1302 Slog.w(TAG, "Empty queue"); 1303 } 1304 break; 1305 } 1306 case MCS_RECONNECT: { 1307 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1308 if (mPendingInstalls.size() > 0) { 1309 if (mBound) { 1310 disconnectService(); 1311 } 1312 if (!connectToService()) { 1313 Slog.e(TAG, "Failed to bind to media container service"); 1314 for (HandlerParams params : mPendingInstalls) { 1315 // Indicate service bind error 1316 params.serviceError(); 1317 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1318 System.identityHashCode(params)); 1319 } 1320 mPendingInstalls.clear(); 1321 } 1322 } 1323 break; 1324 } 1325 case MCS_UNBIND: { 1326 // If there is no actual work left, then time to unbind. 1327 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1328 1329 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1330 if (mBound) { 1331 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1332 1333 disconnectService(); 1334 } 1335 } else if (mPendingInstalls.size() > 0) { 1336 // There are more pending requests in queue. 1337 // Just post MCS_BOUND message to trigger processing 1338 // of next pending install. 1339 mHandler.sendEmptyMessage(MCS_BOUND); 1340 } 1341 1342 break; 1343 } 1344 case MCS_GIVE_UP: { 1345 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1346 HandlerParams params = mPendingInstalls.remove(0); 1347 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1348 System.identityHashCode(params)); 1349 break; 1350 } 1351 case SEND_PENDING_BROADCAST: { 1352 String packages[]; 1353 ArrayList<String> components[]; 1354 int size = 0; 1355 int uids[]; 1356 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1357 synchronized (mPackages) { 1358 if (mPendingBroadcasts == null) { 1359 return; 1360 } 1361 size = mPendingBroadcasts.size(); 1362 if (size <= 0) { 1363 // Nothing to be done. Just return 1364 return; 1365 } 1366 packages = new String[size]; 1367 components = new ArrayList[size]; 1368 uids = new int[size]; 1369 int i = 0; // filling out the above arrays 1370 1371 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1372 int packageUserId = mPendingBroadcasts.userIdAt(n); 1373 Iterator<Map.Entry<String, ArrayList<String>>> it 1374 = mPendingBroadcasts.packagesForUserId(packageUserId) 1375 .entrySet().iterator(); 1376 while (it.hasNext() && i < size) { 1377 Map.Entry<String, ArrayList<String>> ent = it.next(); 1378 packages[i] = ent.getKey(); 1379 components[i] = ent.getValue(); 1380 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1381 uids[i] = (ps != null) 1382 ? UserHandle.getUid(packageUserId, ps.appId) 1383 : -1; 1384 i++; 1385 } 1386 } 1387 size = i; 1388 mPendingBroadcasts.clear(); 1389 } 1390 // Send broadcasts 1391 for (int i = 0; i < size; i++) { 1392 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1393 } 1394 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1395 break; 1396 } 1397 case START_CLEANING_PACKAGE: { 1398 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1399 final String packageName = (String)msg.obj; 1400 final int userId = msg.arg1; 1401 final boolean andCode = msg.arg2 != 0; 1402 synchronized (mPackages) { 1403 if (userId == UserHandle.USER_ALL) { 1404 int[] users = sUserManager.getUserIds(); 1405 for (int user : users) { 1406 mSettings.addPackageToCleanLPw( 1407 new PackageCleanItem(user, packageName, andCode)); 1408 } 1409 } else { 1410 mSettings.addPackageToCleanLPw( 1411 new PackageCleanItem(userId, packageName, andCode)); 1412 } 1413 } 1414 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1415 startCleaningPackages(); 1416 } break; 1417 case POST_INSTALL: { 1418 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1419 1420 PostInstallData data = mRunningInstalls.get(msg.arg1); 1421 mRunningInstalls.delete(msg.arg1); 1422 1423 if (data != null) { 1424 InstallArgs args = data.args; 1425 PackageInstalledInfo parentRes = data.res; 1426 1427 final boolean grantPermissions = (args.installFlags 1428 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1429 final String[] grantedPermissions = args.installGrantPermissions; 1430 1431 // Handle the parent package 1432 handlePackagePostInstall(parentRes, grantPermissions, grantedPermissions, 1433 args.observer); 1434 1435 // Handle the child packages 1436 final int childCount = (parentRes.addedChildPackages != null) 1437 ? parentRes.addedChildPackages.size() : 0; 1438 for (int i = 0; i < childCount; i++) { 1439 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1440 handlePackagePostInstall(childRes, grantPermissions, grantedPermissions, 1441 args.observer); 1442 } 1443 1444 // Log tracing if needed 1445 if (args.traceMethod != null) { 1446 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1447 args.traceCookie); 1448 } 1449 } else { 1450 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1451 } 1452 1453 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1454 } break; 1455 case UPDATED_MEDIA_STATUS: { 1456 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1457 boolean reportStatus = msg.arg1 == 1; 1458 boolean doGc = msg.arg2 == 1; 1459 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1460 if (doGc) { 1461 // Force a gc to clear up stale containers. 1462 Runtime.getRuntime().gc(); 1463 } 1464 if (msg.obj != null) { 1465 @SuppressWarnings("unchecked") 1466 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1467 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1468 // Unload containers 1469 unloadAllContainers(args); 1470 } 1471 if (reportStatus) { 1472 try { 1473 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1474 PackageHelper.getMountService().finishMediaUpdate(); 1475 } catch (RemoteException e) { 1476 Log.e(TAG, "MountService not running?"); 1477 } 1478 } 1479 } break; 1480 case WRITE_SETTINGS: { 1481 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1482 synchronized (mPackages) { 1483 removeMessages(WRITE_SETTINGS); 1484 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1485 mSettings.writeLPr(); 1486 mDirtyUsers.clear(); 1487 } 1488 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1489 } break; 1490 case WRITE_PACKAGE_RESTRICTIONS: { 1491 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1492 synchronized (mPackages) { 1493 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1494 for (int userId : mDirtyUsers) { 1495 mSettings.writePackageRestrictionsLPr(userId); 1496 } 1497 mDirtyUsers.clear(); 1498 } 1499 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1500 } break; 1501 case CHECK_PENDING_VERIFICATION: { 1502 final int verificationId = msg.arg1; 1503 final PackageVerificationState state = mPendingVerification.get(verificationId); 1504 1505 if ((state != null) && !state.timeoutExtended()) { 1506 final InstallArgs args = state.getInstallArgs(); 1507 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1508 1509 Slog.i(TAG, "Verification timed out for " + originUri); 1510 mPendingVerification.remove(verificationId); 1511 1512 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1513 1514 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1515 Slog.i(TAG, "Continuing with installation of " + originUri); 1516 state.setVerifierResponse(Binder.getCallingUid(), 1517 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1518 broadcastPackageVerified(verificationId, originUri, 1519 PackageManager.VERIFICATION_ALLOW, 1520 state.getInstallArgs().getUser()); 1521 try { 1522 ret = args.copyApk(mContainerService, true); 1523 } catch (RemoteException e) { 1524 Slog.e(TAG, "Could not contact the ContainerService"); 1525 } 1526 } else { 1527 broadcastPackageVerified(verificationId, originUri, 1528 PackageManager.VERIFICATION_REJECT, 1529 state.getInstallArgs().getUser()); 1530 } 1531 1532 Trace.asyncTraceEnd( 1533 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1534 1535 processPendingInstall(args, ret); 1536 mHandler.sendEmptyMessage(MCS_UNBIND); 1537 } 1538 break; 1539 } 1540 case PACKAGE_VERIFIED: { 1541 final int verificationId = msg.arg1; 1542 1543 final PackageVerificationState state = mPendingVerification.get(verificationId); 1544 if (state == null) { 1545 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1546 break; 1547 } 1548 1549 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1550 1551 state.setVerifierResponse(response.callerUid, response.code); 1552 1553 if (state.isVerificationComplete()) { 1554 mPendingVerification.remove(verificationId); 1555 1556 final InstallArgs args = state.getInstallArgs(); 1557 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1558 1559 int ret; 1560 if (state.isInstallAllowed()) { 1561 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1562 broadcastPackageVerified(verificationId, originUri, 1563 response.code, state.getInstallArgs().getUser()); 1564 try { 1565 ret = args.copyApk(mContainerService, true); 1566 } catch (RemoteException e) { 1567 Slog.e(TAG, "Could not contact the ContainerService"); 1568 } 1569 } else { 1570 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1571 } 1572 1573 Trace.asyncTraceEnd( 1574 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1575 1576 processPendingInstall(args, ret); 1577 mHandler.sendEmptyMessage(MCS_UNBIND); 1578 } 1579 1580 break; 1581 } 1582 case START_INTENT_FILTER_VERIFICATIONS: { 1583 IFVerificationParams params = (IFVerificationParams) msg.obj; 1584 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1585 params.replacing, params.pkg); 1586 break; 1587 } 1588 case INTENT_FILTER_VERIFIED: { 1589 final int verificationId = msg.arg1; 1590 1591 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1592 verificationId); 1593 if (state == null) { 1594 Slog.w(TAG, "Invalid IntentFilter verification token " 1595 + verificationId + " received"); 1596 break; 1597 } 1598 1599 final int userId = state.getUserId(); 1600 1601 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1602 "Processing IntentFilter verification with token:" 1603 + verificationId + " and userId:" + userId); 1604 1605 final IntentFilterVerificationResponse response = 1606 (IntentFilterVerificationResponse) msg.obj; 1607 1608 state.setVerifierResponse(response.callerUid, response.code); 1609 1610 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1611 "IntentFilter verification with token:" + verificationId 1612 + " and userId:" + userId 1613 + " is settings verifier response with response code:" 1614 + response.code); 1615 1616 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1617 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1618 + response.getFailedDomainsString()); 1619 } 1620 1621 if (state.isVerificationComplete()) { 1622 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1623 } else { 1624 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1625 "IntentFilter verification with token:" + verificationId 1626 + " was not said to be complete"); 1627 } 1628 1629 break; 1630 } 1631 } 1632 } 1633 } 1634 1635 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1636 String[] grantedPermissions, IPackageInstallObserver2 installObserver) { 1637 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1638 // Send the removed broadcasts 1639 if (res.removedInfo != null) { 1640 res.removedInfo.sendPackageRemovedBroadcasts(); 1641 } 1642 1643 // Now that we successfully installed the package, grant runtime 1644 // permissions if requested before broadcasting the install. 1645 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1646 >= Build.VERSION_CODES.M) { 1647 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1648 } 1649 1650 final boolean update = res.removedInfo != null 1651 && res.removedInfo.removedPackage != null; 1652 1653 // If this is the first time we have child packages for a disabled privileged 1654 // app that had no children, we grant requested runtime permissions to the new 1655 // children if the parent on the system image had them already granted. 1656 if (res.pkg.parentPackage != null) { 1657 synchronized (mPackages) { 1658 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1659 } 1660 } 1661 1662 synchronized (mPackages) { 1663 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1664 } 1665 1666 final String packageName = res.pkg.applicationInfo.packageName; 1667 Bundle extras = new Bundle(1); 1668 extras.putInt(Intent.EXTRA_UID, res.uid); 1669 1670 // Determine the set of users who are adding this package for 1671 // the first time vs. those who are seeing an update. 1672 int[] firstUsers = EMPTY_INT_ARRAY; 1673 int[] updateUsers = EMPTY_INT_ARRAY; 1674 if (res.origUsers == null || res.origUsers.length == 0) { 1675 firstUsers = res.newUsers; 1676 } else { 1677 for (int newUser : res.newUsers) { 1678 boolean isNew = true; 1679 for (int origUser : res.origUsers) { 1680 if (origUser == newUser) { 1681 isNew = false; 1682 break; 1683 } 1684 } 1685 if (isNew) { 1686 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1687 } else { 1688 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1689 } 1690 } 1691 } 1692 1693 // Send installed broadcasts if the install/update is not ephemeral 1694 if (!isEphemeral(res.pkg)) { 1695 // Send added for users that see the package for the first time 1696 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1697 extras, 0 /*flags*/, null /*targetPackage*/, 1698 null /*finishedReceiver*/, firstUsers); 1699 1700 // Send added for users that don't see the package for the first time 1701 if (update) { 1702 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1703 } 1704 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1705 extras, 0 /*flags*/, null /*targetPackage*/, 1706 null /*finishedReceiver*/, updateUsers); 1707 1708 // Send replaced for users that don't see the package for the first time 1709 if (update) { 1710 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1711 packageName, extras, 0 /*flags*/, 1712 null /*targetPackage*/, null /*finishedReceiver*/, 1713 updateUsers); 1714 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1715 null /*package*/, null /*extras*/, 0 /*flags*/, 1716 packageName /*targetPackage*/, 1717 null /*finishedReceiver*/, updateUsers); 1718 } 1719 1720 // Send broadcast package appeared if forward locked/external for all users 1721 // treat asec-hosted packages like removable media on upgrade 1722 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1723 if (DEBUG_INSTALL) { 1724 Slog.i(TAG, "upgrading pkg " + res.pkg 1725 + " is ASEC-hosted -> AVAILABLE"); 1726 } 1727 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1728 ArrayList<String> pkgList = new ArrayList<>(1); 1729 pkgList.add(packageName); 1730 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1731 } 1732 } 1733 1734 // Work that needs to happen on first install within each user 1735 if (firstUsers != null && firstUsers.length > 0) { 1736 synchronized (mPackages) { 1737 for (int userId : firstUsers) { 1738 // If this app is a browser and it's newly-installed for some 1739 // users, clear any default-browser state in those users. The 1740 // app's nature doesn't depend on the user, so we can just check 1741 // its browser nature in any user and generalize. 1742 if (packageIsBrowser(packageName, userId)) { 1743 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1744 } 1745 1746 // We may also need to apply pending (restored) runtime 1747 // permission grants within these users. 1748 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1749 } 1750 } 1751 } 1752 1753 // Log current value of "unknown sources" setting 1754 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1755 getUnknownSourcesSettings()); 1756 1757 // Force a gc to clear up things 1758 Runtime.getRuntime().gc(); 1759 1760 // Remove the replaced package's older resources safely now 1761 // We delete after a gc for applications on sdcard. 1762 if (res.removedInfo != null && res.removedInfo.args != null) { 1763 synchronized (mInstallLock) { 1764 res.removedInfo.args.doPostDeleteLI(true); 1765 } 1766 } 1767 } 1768 1769 // If someone is watching installs - notify them 1770 if (installObserver != null) { 1771 try { 1772 Bundle extras = extrasForInstallResult(res); 1773 installObserver.onPackageInstalled(res.name, res.returnCode, 1774 res.returnMsg, extras); 1775 } catch (RemoteException e) { 1776 Slog.i(TAG, "Observer no longer exists."); 1777 } 1778 } 1779 } 1780 1781 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1782 PackageParser.Package pkg) { 1783 if (pkg.parentPackage == null) { 1784 return; 1785 } 1786 if (pkg.requestedPermissions == null) { 1787 return; 1788 } 1789 final PackageSetting disabledSysParentPs = mSettings 1790 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1791 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1792 || !disabledSysParentPs.isPrivileged() 1793 || (disabledSysParentPs.childPackageNames != null 1794 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1795 return; 1796 } 1797 final int[] allUserIds = sUserManager.getUserIds(); 1798 final int permCount = pkg.requestedPermissions.size(); 1799 for (int i = 0; i < permCount; i++) { 1800 String permission = pkg.requestedPermissions.get(i); 1801 BasePermission bp = mSettings.mPermissions.get(permission); 1802 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1803 continue; 1804 } 1805 for (int userId : allUserIds) { 1806 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1807 permission, userId)) { 1808 grantRuntimePermission(pkg.packageName, permission, userId); 1809 } 1810 } 1811 } 1812 } 1813 1814 private StorageEventListener mStorageListener = new StorageEventListener() { 1815 @Override 1816 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1817 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1818 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1819 final String volumeUuid = vol.getFsUuid(); 1820 1821 // Clean up any users or apps that were removed or recreated 1822 // while this volume was missing 1823 reconcileUsers(volumeUuid); 1824 reconcileApps(volumeUuid); 1825 1826 // Clean up any install sessions that expired or were 1827 // cancelled while this volume was missing 1828 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1829 1830 loadPrivatePackages(vol); 1831 1832 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1833 unloadPrivatePackages(vol); 1834 } 1835 } 1836 1837 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1838 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1839 updateExternalMediaStatus(true, false); 1840 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1841 updateExternalMediaStatus(false, false); 1842 } 1843 } 1844 } 1845 1846 @Override 1847 public void onVolumeForgotten(String fsUuid) { 1848 if (TextUtils.isEmpty(fsUuid)) { 1849 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1850 return; 1851 } 1852 1853 // Remove any apps installed on the forgotten volume 1854 synchronized (mPackages) { 1855 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1856 for (PackageSetting ps : packages) { 1857 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1858 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1859 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1860 } 1861 1862 mSettings.onVolumeForgotten(fsUuid); 1863 mSettings.writeLPr(); 1864 } 1865 } 1866 }; 1867 1868 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1869 String[] grantedPermissions) { 1870 for (int userId : userIds) { 1871 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1872 } 1873 1874 // We could have touched GID membership, so flush out packages.list 1875 synchronized (mPackages) { 1876 mSettings.writePackageListLPr(); 1877 } 1878 } 1879 1880 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1881 String[] grantedPermissions) { 1882 SettingBase sb = (SettingBase) pkg.mExtras; 1883 if (sb == null) { 1884 return; 1885 } 1886 1887 PermissionsState permissionsState = sb.getPermissionsState(); 1888 1889 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1890 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1891 1892 synchronized (mPackages) { 1893 for (String permission : pkg.requestedPermissions) { 1894 BasePermission bp = mSettings.mPermissions.get(permission); 1895 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1896 && (grantedPermissions == null 1897 || ArrayUtils.contains(grantedPermissions, permission))) { 1898 final int flags = permissionsState.getPermissionFlags(permission, userId); 1899 // Installer cannot change immutable permissions. 1900 if ((flags & immutableFlags) == 0) { 1901 grantRuntimePermission(pkg.packageName, permission, userId); 1902 } 1903 } 1904 } 1905 } 1906 } 1907 1908 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1909 Bundle extras = null; 1910 switch (res.returnCode) { 1911 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1912 extras = new Bundle(); 1913 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1914 res.origPermission); 1915 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1916 res.origPackage); 1917 break; 1918 } 1919 case PackageManager.INSTALL_SUCCEEDED: { 1920 extras = new Bundle(); 1921 extras.putBoolean(Intent.EXTRA_REPLACING, 1922 res.removedInfo != null && res.removedInfo.removedPackage != null); 1923 break; 1924 } 1925 } 1926 return extras; 1927 } 1928 1929 void scheduleWriteSettingsLocked() { 1930 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1931 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1932 } 1933 } 1934 1935 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 1936 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 1937 scheduleWritePackageRestrictionsLocked(userId); 1938 } 1939 1940 void scheduleWritePackageRestrictionsLocked(int userId) { 1941 final int[] userIds = (userId == UserHandle.USER_ALL) 1942 ? sUserManager.getUserIds() : new int[]{userId}; 1943 for (int nextUserId : userIds) { 1944 if (!sUserManager.exists(nextUserId)) return; 1945 mDirtyUsers.add(nextUserId); 1946 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1947 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1948 } 1949 } 1950 } 1951 1952 public static PackageManagerService main(Context context, Installer installer, 1953 boolean factoryTest, boolean onlyCore) { 1954 PackageManagerService m = new PackageManagerService(context, installer, 1955 factoryTest, onlyCore); 1956 m.enableSystemUserPackages(); 1957 ServiceManager.addService("package", m); 1958 return m; 1959 } 1960 1961 private void enableSystemUserPackages() { 1962 if (!UserManager.isSplitSystemUser()) { 1963 return; 1964 } 1965 // For system user, enable apps based on the following conditions: 1966 // - app is whitelisted or belong to one of these groups: 1967 // -- system app which has no launcher icons 1968 // -- system app which has INTERACT_ACROSS_USERS permission 1969 // -- system IME app 1970 // - app is not in the blacklist 1971 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 1972 Set<String> enableApps = new ArraySet<>(); 1973 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 1974 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 1975 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 1976 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 1977 enableApps.addAll(wlApps); 1978 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 1979 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 1980 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 1981 enableApps.removeAll(blApps); 1982 Log.i(TAG, "Applications installed for system user: " + enableApps); 1983 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 1984 UserHandle.SYSTEM); 1985 final int allAppsSize = allAps.size(); 1986 synchronized (mPackages) { 1987 for (int i = 0; i < allAppsSize; i++) { 1988 String pName = allAps.get(i); 1989 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 1990 // Should not happen, but we shouldn't be failing if it does 1991 if (pkgSetting == null) { 1992 continue; 1993 } 1994 boolean install = enableApps.contains(pName); 1995 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 1996 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 1997 + " for system user"); 1998 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 1999 } 2000 } 2001 } 2002 } 2003 2004 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2005 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2006 Context.DISPLAY_SERVICE); 2007 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2008 } 2009 2010 public PackageManagerService(Context context, Installer installer, 2011 boolean factoryTest, boolean onlyCore) { 2012 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2013 SystemClock.uptimeMillis()); 2014 2015 if (mSdkVersion <= 0) { 2016 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2017 } 2018 2019 mContext = context; 2020 mFactoryTest = factoryTest; 2021 mOnlyCore = onlyCore; 2022 mMetrics = new DisplayMetrics(); 2023 mSettings = new Settings(mPackages); 2024 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2025 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2026 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2027 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2028 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2029 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2030 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2031 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2032 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2033 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2034 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2035 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2036 2037 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2038 if (separateProcesses != null && separateProcesses.length() > 0) { 2039 if ("*".equals(separateProcesses)) { 2040 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2041 mSeparateProcesses = null; 2042 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2043 } else { 2044 mDefParseFlags = 0; 2045 mSeparateProcesses = separateProcesses.split(","); 2046 Slog.w(TAG, "Running with debug.separate_processes: " 2047 + separateProcesses); 2048 } 2049 } else { 2050 mDefParseFlags = 0; 2051 mSeparateProcesses = null; 2052 } 2053 2054 mInstaller = installer; 2055 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2056 "*dexopt*"); 2057 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2058 2059 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2060 FgThread.get().getLooper()); 2061 2062 getDefaultDisplayMetrics(context, mMetrics); 2063 2064 SystemConfig systemConfig = SystemConfig.getInstance(); 2065 mGlobalGids = systemConfig.getGlobalGids(); 2066 mSystemPermissions = systemConfig.getSystemPermissions(); 2067 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2068 2069 synchronized (mInstallLock) { 2070 // writer 2071 synchronized (mPackages) { 2072 mHandlerThread = new ServiceThread(TAG, 2073 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2074 mHandlerThread.start(); 2075 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2076 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2077 2078 File dataDir = Environment.getDataDirectory(); 2079 mAppInstallDir = new File(dataDir, "app"); 2080 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2081 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2082 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2083 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2084 2085 sUserManager = new UserManagerService(context, this, mPackages); 2086 2087 // Propagate permission configuration in to package manager. 2088 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2089 = systemConfig.getPermissions(); 2090 for (int i=0; i<permConfig.size(); i++) { 2091 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2092 BasePermission bp = mSettings.mPermissions.get(perm.name); 2093 if (bp == null) { 2094 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2095 mSettings.mPermissions.put(perm.name, bp); 2096 } 2097 if (perm.gids != null) { 2098 bp.setGids(perm.gids, perm.perUser); 2099 } 2100 } 2101 2102 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2103 for (int i=0; i<libConfig.size(); i++) { 2104 mSharedLibraries.put(libConfig.keyAt(i), 2105 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2106 } 2107 2108 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2109 2110 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2111 2112 String customResolverActivity = Resources.getSystem().getString( 2113 R.string.config_customResolverActivity); 2114 if (TextUtils.isEmpty(customResolverActivity)) { 2115 customResolverActivity = null; 2116 } else { 2117 mCustomResolverComponentName = ComponentName.unflattenFromString( 2118 customResolverActivity); 2119 } 2120 2121 long startTime = SystemClock.uptimeMillis(); 2122 2123 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2124 startTime); 2125 2126 // Set flag to monitor and not change apk file paths when 2127 // scanning install directories. 2128 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2129 2130 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2131 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2132 2133 if (bootClassPath == null) { 2134 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2135 } 2136 2137 if (systemServerClassPath == null) { 2138 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2139 } 2140 2141 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2142 final String[] dexCodeInstructionSets = 2143 getDexCodeInstructionSets( 2144 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2145 2146 /** 2147 * Ensure all external libraries have had dexopt run on them. 2148 */ 2149 if (mSharedLibraries.size() > 0) { 2150 // NOTE: For now, we're compiling these system "shared libraries" 2151 // (and framework jars) into all available architectures. It's possible 2152 // to compile them only when we come across an app that uses them (there's 2153 // already logic for that in scanPackageLI) but that adds some complexity. 2154 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2155 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2156 final String lib = libEntry.path; 2157 if (lib == null) { 2158 continue; 2159 } 2160 2161 try { 2162 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 2163 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2164 // Shared libraries do not have profiles so we perform a full 2165 // AOT compilation. 2166 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2167 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2168 StorageManager.UUID_PRIVATE_INTERNAL, 2169 false /*useProfiles*/); 2170 } 2171 } catch (FileNotFoundException e) { 2172 Slog.w(TAG, "Library not found: " + lib); 2173 } catch (IOException | InstallerException e) { 2174 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2175 + e.getMessage()); 2176 } 2177 } 2178 } 2179 } 2180 2181 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2182 2183 final VersionInfo ver = mSettings.getInternalVersion(); 2184 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2185 // when upgrading from pre-M, promote system app permissions from install to runtime 2186 mPromoteSystemApps = 2187 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2188 2189 // save off the names of pre-existing system packages prior to scanning; we don't 2190 // want to automatically grant runtime permissions for new system apps 2191 if (mPromoteSystemApps) { 2192 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2193 while (pkgSettingIter.hasNext()) { 2194 PackageSetting ps = pkgSettingIter.next(); 2195 if (isSystemApp(ps)) { 2196 mExistingSystemPackages.add(ps.name); 2197 } 2198 } 2199 } 2200 2201 // Collect vendor overlay packages. 2202 // (Do this before scanning any apps.) 2203 // For security and version matching reason, only consider 2204 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2205 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2206 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2207 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2208 2209 // Find base frameworks (resource packages without code). 2210 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2211 | PackageParser.PARSE_IS_SYSTEM_DIR 2212 | PackageParser.PARSE_IS_PRIVILEGED, 2213 scanFlags | SCAN_NO_DEX, 0); 2214 2215 // Collected privileged system packages. 2216 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2217 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2218 | PackageParser.PARSE_IS_SYSTEM_DIR 2219 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2220 2221 // Collect ordinary system packages. 2222 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2223 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2224 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2225 2226 // Collect all vendor packages. 2227 File vendorAppDir = new File("/vendor/app"); 2228 try { 2229 vendorAppDir = vendorAppDir.getCanonicalFile(); 2230 } catch (IOException e) { 2231 // failed to look up canonical path, continue with original one 2232 } 2233 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2234 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2235 2236 // Collect all OEM packages. 2237 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2238 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2239 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2240 2241 // Prune any system packages that no longer exist. 2242 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2243 if (!mOnlyCore) { 2244 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2245 while (psit.hasNext()) { 2246 PackageSetting ps = psit.next(); 2247 2248 /* 2249 * If this is not a system app, it can't be a 2250 * disable system app. 2251 */ 2252 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2253 continue; 2254 } 2255 2256 /* 2257 * If the package is scanned, it's not erased. 2258 */ 2259 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2260 if (scannedPkg != null) { 2261 /* 2262 * If the system app is both scanned and in the 2263 * disabled packages list, then it must have been 2264 * added via OTA. Remove it from the currently 2265 * scanned package so the previously user-installed 2266 * application can be scanned. 2267 */ 2268 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2269 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2270 + ps.name + "; removing system app. Last known codePath=" 2271 + ps.codePathString + ", installStatus=" + ps.installStatus 2272 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2273 + scannedPkg.mVersionCode); 2274 removePackageLI(scannedPkg, true); 2275 mExpectingBetter.put(ps.name, ps.codePath); 2276 } 2277 2278 continue; 2279 } 2280 2281 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2282 psit.remove(); 2283 logCriticalInfo(Log.WARN, "System package " + ps.name 2284 + " no longer exists; wiping its data"); 2285 removeDataDirsLI(null, ps.name); 2286 } else { 2287 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2288 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2289 possiblyDeletedUpdatedSystemApps.add(ps.name); 2290 } 2291 } 2292 } 2293 } 2294 2295 //look for any incomplete package installations 2296 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2297 //clean up list 2298 for(int i = 0; i < deletePkgsList.size(); i++) { 2299 //clean up here 2300 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2301 } 2302 //delete tmp files 2303 deleteTempPackageFiles(); 2304 2305 // Remove any shared userIDs that have no associated packages 2306 mSettings.pruneSharedUsersLPw(); 2307 2308 if (!mOnlyCore) { 2309 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2310 SystemClock.uptimeMillis()); 2311 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2312 2313 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2314 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2315 2316 scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL, 2317 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2318 2319 /** 2320 * Remove disable package settings for any updated system 2321 * apps that were removed via an OTA. If they're not a 2322 * previously-updated app, remove them completely. 2323 * Otherwise, just revoke their system-level permissions. 2324 */ 2325 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2326 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2327 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2328 2329 String msg; 2330 if (deletedPkg == null) { 2331 msg = "Updated system package " + deletedAppName 2332 + " no longer exists; wiping its data"; 2333 removeDataDirsLI(null, deletedAppName); 2334 } else { 2335 msg = "Updated system app + " + deletedAppName 2336 + " no longer present; removing system privileges for " 2337 + deletedAppName; 2338 2339 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2340 2341 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2342 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2343 } 2344 logCriticalInfo(Log.WARN, msg); 2345 } 2346 2347 /** 2348 * Make sure all system apps that we expected to appear on 2349 * the userdata partition actually showed up. If they never 2350 * appeared, crawl back and revive the system version. 2351 */ 2352 for (int i = 0; i < mExpectingBetter.size(); i++) { 2353 final String packageName = mExpectingBetter.keyAt(i); 2354 if (!mPackages.containsKey(packageName)) { 2355 final File scanFile = mExpectingBetter.valueAt(i); 2356 2357 logCriticalInfo(Log.WARN, "Expected better " + packageName 2358 + " but never showed up; reverting to system"); 2359 2360 final int reparseFlags; 2361 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2362 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2363 | PackageParser.PARSE_IS_SYSTEM_DIR 2364 | PackageParser.PARSE_IS_PRIVILEGED; 2365 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2366 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2367 | PackageParser.PARSE_IS_SYSTEM_DIR; 2368 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2369 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2370 | PackageParser.PARSE_IS_SYSTEM_DIR; 2371 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2372 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2373 | PackageParser.PARSE_IS_SYSTEM_DIR; 2374 } else { 2375 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2376 continue; 2377 } 2378 2379 mSettings.enableSystemPackageLPw(packageName); 2380 2381 try { 2382 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2383 } catch (PackageManagerException e) { 2384 Slog.e(TAG, "Failed to parse original system package: " 2385 + e.getMessage()); 2386 } 2387 } 2388 } 2389 } 2390 mExpectingBetter.clear(); 2391 2392 // Now that we know all of the shared libraries, update all clients to have 2393 // the correct library paths. 2394 updateAllSharedLibrariesLPw(); 2395 2396 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2397 // NOTE: We ignore potential failures here during a system scan (like 2398 // the rest of the commands above) because there's precious little we 2399 // can do about it. A settings error is reported, though. 2400 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2401 false /* boot complete */); 2402 } 2403 2404 // Now that we know all the packages we are keeping, 2405 // read and update their last usage times. 2406 mPackageUsage.readLP(); 2407 2408 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2409 SystemClock.uptimeMillis()); 2410 Slog.i(TAG, "Time to scan packages: " 2411 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2412 + " seconds"); 2413 2414 // If the platform SDK has changed since the last time we booted, 2415 // we need to re-grant app permission to catch any new ones that 2416 // appear. This is really a hack, and means that apps can in some 2417 // cases get permissions that the user didn't initially explicitly 2418 // allow... it would be nice to have some better way to handle 2419 // this situation. 2420 int updateFlags = UPDATE_PERMISSIONS_ALL; 2421 if (ver.sdkVersion != mSdkVersion) { 2422 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2423 + mSdkVersion + "; regranting permissions for internal storage"); 2424 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2425 } 2426 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2427 ver.sdkVersion = mSdkVersion; 2428 2429 // If this is the first boot or an update from pre-M, and it is a normal 2430 // boot, then we need to initialize the default preferred apps across 2431 // all defined users. 2432 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2433 for (UserInfo user : sUserManager.getUsers(true)) { 2434 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2435 applyFactoryDefaultBrowserLPw(user.id); 2436 primeDomainVerificationsLPw(user.id); 2437 } 2438 } 2439 2440 // Prepare storage for system user really early during boot, 2441 // since core system apps like SettingsProvider and SystemUI 2442 // can't wait for user to start 2443 final int storageFlags; 2444 if (StorageManager.isFileBasedEncryptionEnabled()) { 2445 storageFlags = StorageManager.FLAG_STORAGE_DE; 2446 } else { 2447 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2448 } 2449 reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2450 storageFlags); 2451 2452 // If this is first boot after an OTA, and a normal boot, then 2453 // we need to clear code cache directories. 2454 if (mIsUpgrade && !onlyCore) { 2455 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2456 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2457 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2458 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2459 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2460 } 2461 } 2462 ver.fingerprint = Build.FINGERPRINT; 2463 } 2464 2465 checkDefaultBrowser(); 2466 2467 // clear only after permissions and other defaults have been updated 2468 mExistingSystemPackages.clear(); 2469 mPromoteSystemApps = false; 2470 2471 // All the changes are done during package scanning. 2472 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2473 2474 // can downgrade to reader 2475 mSettings.writeLPr(); 2476 2477 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2478 SystemClock.uptimeMillis()); 2479 2480 if (!mOnlyCore) { 2481 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2482 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2483 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2484 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2485 mIntentFilterVerifierComponent); 2486 } else { 2487 mRequiredVerifierPackage = null; 2488 mRequiredInstallerPackage = null; 2489 mIntentFilterVerifierComponent = null; 2490 mIntentFilterVerifier = null; 2491 } 2492 2493 mInstallerService = new PackageInstallerService(context, this); 2494 2495 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2496 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2497 // both the installer and resolver must be present to enable ephemeral 2498 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2499 if (DEBUG_EPHEMERAL) { 2500 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2501 + " installer:" + ephemeralInstallerComponent); 2502 } 2503 mEphemeralResolverComponent = ephemeralResolverComponent; 2504 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2505 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2506 mEphemeralResolverConnection = 2507 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2508 } else { 2509 if (DEBUG_EPHEMERAL) { 2510 final String missingComponent = 2511 (ephemeralResolverComponent == null) 2512 ? (ephemeralInstallerComponent == null) 2513 ? "resolver and installer" 2514 : "resolver" 2515 : "installer"; 2516 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2517 } 2518 mEphemeralResolverComponent = null; 2519 mEphemeralInstallerComponent = null; 2520 mEphemeralResolverConnection = null; 2521 } 2522 2523 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2524 } // synchronized (mPackages) 2525 } // synchronized (mInstallLock) 2526 2527 // Now after opening every single application zip, make sure they 2528 // are all flushed. Not really needed, but keeps things nice and 2529 // tidy. 2530 Runtime.getRuntime().gc(); 2531 2532 // The initial scanning above does many calls into installd while 2533 // holding the mPackages lock, but we're mostly interested in yelling 2534 // once we have a booted system. 2535 mInstaller.setWarnIfHeld(mPackages); 2536 2537 // Expose private service for system components to use. 2538 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2539 } 2540 2541 @Override 2542 public boolean isFirstBoot() { 2543 return !mRestoredSettings; 2544 } 2545 2546 @Override 2547 public boolean isOnlyCoreApps() { 2548 return mOnlyCore; 2549 } 2550 2551 @Override 2552 public boolean isUpgrade() { 2553 return mIsUpgrade; 2554 } 2555 2556 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2557 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2558 2559 final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE, 2560 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2561 if (matches.size() == 1) { 2562 return matches.get(0).getComponentInfo().packageName; 2563 } else { 2564 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2565 return null; 2566 } 2567 } 2568 2569 private @NonNull String getRequiredInstallerLPr() { 2570 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2571 intent.addCategory(Intent.CATEGORY_DEFAULT); 2572 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2573 2574 final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE, 2575 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2576 if (matches.size() == 1) { 2577 return matches.get(0).getComponentInfo().packageName; 2578 } else { 2579 throw new RuntimeException("There must be exactly one installer; found " + matches); 2580 } 2581 } 2582 2583 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2584 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2585 2586 final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE, 2587 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2588 ResolveInfo best = null; 2589 final int N = matches.size(); 2590 for (int i = 0; i < N; i++) { 2591 final ResolveInfo cur = matches.get(i); 2592 final String packageName = cur.getComponentInfo().packageName; 2593 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2594 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2595 continue; 2596 } 2597 2598 if (best == null || cur.priority > best.priority) { 2599 best = cur; 2600 } 2601 } 2602 2603 if (best != null) { 2604 return best.getComponentInfo().getComponentName(); 2605 } else { 2606 throw new RuntimeException("There must be at least one intent filter verifier"); 2607 } 2608 } 2609 2610 private @Nullable ComponentName getEphemeralResolverLPr() { 2611 final String[] packageArray = 2612 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2613 if (packageArray.length == 0) { 2614 if (DEBUG_EPHEMERAL) { 2615 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2616 } 2617 return null; 2618 } 2619 2620 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2621 final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, null, 2622 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2623 2624 final int N = resolvers.size(); 2625 if (N == 0) { 2626 if (DEBUG_EPHEMERAL) { 2627 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2628 } 2629 return null; 2630 } 2631 2632 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2633 for (int i = 0; i < N; i++) { 2634 final ResolveInfo info = resolvers.get(i); 2635 2636 if (info.serviceInfo == null) { 2637 continue; 2638 } 2639 2640 final String packageName = info.serviceInfo.packageName; 2641 if (!possiblePackages.contains(packageName)) { 2642 if (DEBUG_EPHEMERAL) { 2643 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2644 + " pkg: " + packageName + ", info:" + info); 2645 } 2646 continue; 2647 } 2648 2649 if (DEBUG_EPHEMERAL) { 2650 Slog.v(TAG, "Ephemeral resolver found;" 2651 + " pkg: " + packageName + ", info:" + info); 2652 } 2653 return new ComponentName(packageName, info.serviceInfo.name); 2654 } 2655 if (DEBUG_EPHEMERAL) { 2656 Slog.v(TAG, "Ephemeral resolver NOT found"); 2657 } 2658 return null; 2659 } 2660 2661 private @Nullable ComponentName getEphemeralInstallerLPr() { 2662 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2663 intent.addCategory(Intent.CATEGORY_DEFAULT); 2664 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2665 2666 final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE, 2667 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2668 if (matches.size() == 0) { 2669 return null; 2670 } else if (matches.size() == 1) { 2671 return matches.get(0).getComponentInfo().getComponentName(); 2672 } else { 2673 throw new RuntimeException( 2674 "There must be at most one ephemeral installer; found " + matches); 2675 } 2676 } 2677 2678 private void primeDomainVerificationsLPw(int userId) { 2679 if (DEBUG_DOMAIN_VERIFICATION) { 2680 Slog.d(TAG, "Priming domain verifications in user " + userId); 2681 } 2682 2683 SystemConfig systemConfig = SystemConfig.getInstance(); 2684 ArraySet<String> packages = systemConfig.getLinkedApps(); 2685 ArraySet<String> domains = new ArraySet<String>(); 2686 2687 for (String packageName : packages) { 2688 PackageParser.Package pkg = mPackages.get(packageName); 2689 if (pkg != null) { 2690 if (!pkg.isSystemApp()) { 2691 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2692 continue; 2693 } 2694 2695 domains.clear(); 2696 for (PackageParser.Activity a : pkg.activities) { 2697 for (ActivityIntentInfo filter : a.intents) { 2698 if (hasValidDomains(filter)) { 2699 domains.addAll(filter.getHostsList()); 2700 } 2701 } 2702 } 2703 2704 if (domains.size() > 0) { 2705 if (DEBUG_DOMAIN_VERIFICATION) { 2706 Slog.v(TAG, " + " + packageName); 2707 } 2708 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2709 // state w.r.t. the formal app-linkage "no verification attempted" state; 2710 // and then 'always' in the per-user state actually used for intent resolution. 2711 final IntentFilterVerificationInfo ivi; 2712 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2713 new ArrayList<String>(domains)); 2714 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2715 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2716 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2717 } else { 2718 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2719 + "' does not handle web links"); 2720 } 2721 } else { 2722 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2723 } 2724 } 2725 2726 scheduleWritePackageRestrictionsLocked(userId); 2727 scheduleWriteSettingsLocked(); 2728 } 2729 2730 private void applyFactoryDefaultBrowserLPw(int userId) { 2731 // The default browser app's package name is stored in a string resource, 2732 // with a product-specific overlay used for vendor customization. 2733 String browserPkg = mContext.getResources().getString( 2734 com.android.internal.R.string.default_browser); 2735 if (!TextUtils.isEmpty(browserPkg)) { 2736 // non-empty string => required to be a known package 2737 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2738 if (ps == null) { 2739 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2740 browserPkg = null; 2741 } else { 2742 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2743 } 2744 } 2745 2746 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2747 // default. If there's more than one, just leave everything alone. 2748 if (browserPkg == null) { 2749 calculateDefaultBrowserLPw(userId); 2750 } 2751 } 2752 2753 private void calculateDefaultBrowserLPw(int userId) { 2754 List<String> allBrowsers = resolveAllBrowserApps(userId); 2755 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2756 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2757 } 2758 2759 private List<String> resolveAllBrowserApps(int userId) { 2760 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2761 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2762 PackageManager.MATCH_ALL, userId); 2763 2764 final int count = list.size(); 2765 List<String> result = new ArrayList<String>(count); 2766 for (int i=0; i<count; i++) { 2767 ResolveInfo info = list.get(i); 2768 if (info.activityInfo == null 2769 || !info.handleAllWebDataURI 2770 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2771 || result.contains(info.activityInfo.packageName)) { 2772 continue; 2773 } 2774 result.add(info.activityInfo.packageName); 2775 } 2776 2777 return result; 2778 } 2779 2780 private boolean packageIsBrowser(String packageName, int userId) { 2781 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2782 PackageManager.MATCH_ALL, userId); 2783 final int N = list.size(); 2784 for (int i = 0; i < N; i++) { 2785 ResolveInfo info = list.get(i); 2786 if (packageName.equals(info.activityInfo.packageName)) { 2787 return true; 2788 } 2789 } 2790 return false; 2791 } 2792 2793 private void checkDefaultBrowser() { 2794 final int myUserId = UserHandle.myUserId(); 2795 final String packageName = getDefaultBrowserPackageName(myUserId); 2796 if (packageName != null) { 2797 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2798 if (info == null) { 2799 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2800 synchronized (mPackages) { 2801 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2802 } 2803 } 2804 } 2805 } 2806 2807 @Override 2808 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2809 throws RemoteException { 2810 try { 2811 return super.onTransact(code, data, reply, flags); 2812 } catch (RuntimeException e) { 2813 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2814 Slog.wtf(TAG, "Package Manager Crash", e); 2815 } 2816 throw e; 2817 } 2818 } 2819 2820 void cleanupInstallFailedPackage(PackageSetting ps) { 2821 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2822 2823 removeDataDirsLI(ps.volumeUuid, ps.name); 2824 if (ps.codePath != null) { 2825 removeCodePathLI(ps.codePath); 2826 } 2827 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2828 if (ps.resourcePath.isDirectory()) { 2829 FileUtils.deleteContents(ps.resourcePath); 2830 } 2831 ps.resourcePath.delete(); 2832 } 2833 mSettings.removePackageLPw(ps.name); 2834 } 2835 2836 static int[] appendInts(int[] cur, int[] add) { 2837 if (add == null) return cur; 2838 if (cur == null) return add; 2839 final int N = add.length; 2840 for (int i=0; i<N; i++) { 2841 cur = appendInt(cur, add[i]); 2842 } 2843 return cur; 2844 } 2845 2846 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2847 if (!sUserManager.exists(userId)) return null; 2848 final PackageSetting ps = (PackageSetting) p.mExtras; 2849 if (ps == null) { 2850 return null; 2851 } 2852 2853 final PermissionsState permissionsState = ps.getPermissionsState(); 2854 2855 final int[] gids = permissionsState.computeGids(userId); 2856 final Set<String> permissions = permissionsState.getPermissions(userId); 2857 final PackageUserState state = ps.readUserState(userId); 2858 2859 return PackageParser.generatePackageInfo(p, gids, flags, 2860 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2861 } 2862 2863 @Override 2864 public void checkPackageStartable(String packageName, int userId) { 2865 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 2866 2867 synchronized (mPackages) { 2868 final PackageSetting ps = mSettings.mPackages.get(packageName); 2869 if (ps == null) { 2870 throw new SecurityException("Package " + packageName + " was not found!"); 2871 } 2872 2873 if (mSafeMode && !ps.isSystem()) { 2874 throw new SecurityException("Package " + packageName + " not a system app!"); 2875 } 2876 2877 if (ps.frozen) { 2878 throw new SecurityException("Package " + packageName + " is currently frozen!"); 2879 } 2880 2881 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware() 2882 || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) { 2883 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 2884 } 2885 } 2886 } 2887 2888 @Override 2889 public boolean isPackageAvailable(String packageName, int userId) { 2890 if (!sUserManager.exists(userId)) return false; 2891 enforceCrossUserPermission(Binder.getCallingUid(), userId, 2892 false /* requireFullPermission */, false /* checkShell */, "is package available"); 2893 synchronized (mPackages) { 2894 PackageParser.Package p = mPackages.get(packageName); 2895 if (p != null) { 2896 final PackageSetting ps = (PackageSetting) p.mExtras; 2897 if (ps != null) { 2898 final PackageUserState state = ps.readUserState(userId); 2899 if (state != null) { 2900 return PackageParser.isAvailable(state); 2901 } 2902 } 2903 } 2904 } 2905 return false; 2906 } 2907 2908 @Override 2909 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2910 if (!sUserManager.exists(userId)) return null; 2911 flags = updateFlagsForPackage(flags, userId, packageName); 2912 enforceCrossUserPermission(Binder.getCallingUid(), userId, 2913 false /* requireFullPermission */, false /* checkShell */, "get package info"); 2914 // reader 2915 synchronized (mPackages) { 2916 PackageParser.Package p = mPackages.get(packageName); 2917 if (DEBUG_PACKAGE_INFO) 2918 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2919 if (p != null) { 2920 return generatePackageInfo(p, flags, userId); 2921 } 2922 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2923 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2924 } 2925 } 2926 return null; 2927 } 2928 2929 @Override 2930 public String[] currentToCanonicalPackageNames(String[] names) { 2931 String[] out = new String[names.length]; 2932 // reader 2933 synchronized (mPackages) { 2934 for (int i=names.length-1; i>=0; i--) { 2935 PackageSetting ps = mSettings.mPackages.get(names[i]); 2936 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2937 } 2938 } 2939 return out; 2940 } 2941 2942 @Override 2943 public String[] canonicalToCurrentPackageNames(String[] names) { 2944 String[] out = new String[names.length]; 2945 // reader 2946 synchronized (mPackages) { 2947 for (int i=names.length-1; i>=0; i--) { 2948 String cur = mSettings.mRenamedPackages.get(names[i]); 2949 out[i] = cur != null ? cur : names[i]; 2950 } 2951 } 2952 return out; 2953 } 2954 2955 @Override 2956 public int getPackageUid(String packageName, int flags, int userId) { 2957 if (!sUserManager.exists(userId)) return -1; 2958 flags = updateFlagsForPackage(flags, userId, packageName); 2959 enforceCrossUserPermission(Binder.getCallingUid(), userId, 2960 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 2961 2962 // reader 2963 synchronized (mPackages) { 2964 final PackageParser.Package p = mPackages.get(packageName); 2965 if (p != null && p.isMatch(flags)) { 2966 return UserHandle.getUid(userId, p.applicationInfo.uid); 2967 } 2968 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2969 final PackageSetting ps = mSettings.mPackages.get(packageName); 2970 if (ps != null && ps.isMatch(flags)) { 2971 return UserHandle.getUid(userId, ps.appId); 2972 } 2973 } 2974 } 2975 2976 return -1; 2977 } 2978 2979 @Override 2980 public int[] getPackageGids(String packageName, int flags, int userId) { 2981 if (!sUserManager.exists(userId)) return null; 2982 flags = updateFlagsForPackage(flags, userId, packageName); 2983 enforceCrossUserPermission(Binder.getCallingUid(), userId, 2984 false /* requireFullPermission */, false /* checkShell */, 2985 "getPackageGids"); 2986 2987 // reader 2988 synchronized (mPackages) { 2989 final PackageParser.Package p = mPackages.get(packageName); 2990 if (p != null && p.isMatch(flags)) { 2991 PackageSetting ps = (PackageSetting) p.mExtras; 2992 return ps.getPermissionsState().computeGids(userId); 2993 } 2994 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2995 final PackageSetting ps = mSettings.mPackages.get(packageName); 2996 if (ps != null && ps.isMatch(flags)) { 2997 return ps.getPermissionsState().computeGids(userId); 2998 } 2999 } 3000 } 3001 3002 return null; 3003 } 3004 3005 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3006 if (bp.perm != null) { 3007 return PackageParser.generatePermissionInfo(bp.perm, flags); 3008 } 3009 PermissionInfo pi = new PermissionInfo(); 3010 pi.name = bp.name; 3011 pi.packageName = bp.sourcePackage; 3012 pi.nonLocalizedLabel = bp.name; 3013 pi.protectionLevel = bp.protectionLevel; 3014 return pi; 3015 } 3016 3017 @Override 3018 public PermissionInfo getPermissionInfo(String name, int flags) { 3019 // reader 3020 synchronized (mPackages) { 3021 final BasePermission p = mSettings.mPermissions.get(name); 3022 if (p != null) { 3023 return generatePermissionInfo(p, flags); 3024 } 3025 return null; 3026 } 3027 } 3028 3029 @Override 3030 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 3031 // reader 3032 synchronized (mPackages) { 3033 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3034 for (BasePermission p : mSettings.mPermissions.values()) { 3035 if (group == null) { 3036 if (p.perm == null || p.perm.info.group == null) { 3037 out.add(generatePermissionInfo(p, flags)); 3038 } 3039 } else { 3040 if (p.perm != null && group.equals(p.perm.info.group)) { 3041 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3042 } 3043 } 3044 } 3045 3046 if (out.size() > 0) { 3047 return out; 3048 } 3049 return mPermissionGroups.containsKey(group) ? out : null; 3050 } 3051 } 3052 3053 @Override 3054 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3055 // reader 3056 synchronized (mPackages) { 3057 return PackageParser.generatePermissionGroupInfo( 3058 mPermissionGroups.get(name), flags); 3059 } 3060 } 3061 3062 @Override 3063 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3064 // reader 3065 synchronized (mPackages) { 3066 final int N = mPermissionGroups.size(); 3067 ArrayList<PermissionGroupInfo> out 3068 = new ArrayList<PermissionGroupInfo>(N); 3069 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3070 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3071 } 3072 return out; 3073 } 3074 } 3075 3076 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3077 int userId) { 3078 if (!sUserManager.exists(userId)) return null; 3079 PackageSetting ps = mSettings.mPackages.get(packageName); 3080 if (ps != null) { 3081 if (ps.pkg == null) { 3082 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 3083 flags, userId); 3084 if (pInfo != null) { 3085 return pInfo.applicationInfo; 3086 } 3087 return null; 3088 } 3089 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3090 ps.readUserState(userId), userId); 3091 } 3092 return null; 3093 } 3094 3095 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 3096 int userId) { 3097 if (!sUserManager.exists(userId)) return null; 3098 PackageSetting ps = mSettings.mPackages.get(packageName); 3099 if (ps != null) { 3100 PackageParser.Package pkg = ps.pkg; 3101 if (pkg == null) { 3102 if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) { 3103 return null; 3104 } 3105 // Only data remains, so we aren't worried about code paths 3106 pkg = new PackageParser.Package(packageName); 3107 pkg.applicationInfo.packageName = packageName; 3108 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 3109 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 3110 pkg.applicationInfo.uid = ps.appId; 3111 pkg.applicationInfo.initForUser(userId); 3112 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 3113 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 3114 } 3115 return generatePackageInfo(pkg, flags, userId); 3116 } 3117 return null; 3118 } 3119 3120 @Override 3121 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3122 if (!sUserManager.exists(userId)) return null; 3123 flags = updateFlagsForApplication(flags, userId, packageName); 3124 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3125 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3126 // writer 3127 synchronized (mPackages) { 3128 PackageParser.Package p = mPackages.get(packageName); 3129 if (DEBUG_PACKAGE_INFO) Log.v( 3130 TAG, "getApplicationInfo " + packageName 3131 + ": " + p); 3132 if (p != null) { 3133 PackageSetting ps = mSettings.mPackages.get(packageName); 3134 if (ps == null) return null; 3135 // Note: isEnabledLP() does not apply here - always return info 3136 return PackageParser.generateApplicationInfo( 3137 p, flags, ps.readUserState(userId), userId); 3138 } 3139 if ("android".equals(packageName)||"system".equals(packageName)) { 3140 return mAndroidApplication; 3141 } 3142 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3143 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3144 } 3145 } 3146 return null; 3147 } 3148 3149 @Override 3150 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3151 final IPackageDataObserver observer) { 3152 mContext.enforceCallingOrSelfPermission( 3153 android.Manifest.permission.CLEAR_APP_CACHE, null); 3154 // Queue up an async operation since clearing cache may take a little while. 3155 mHandler.post(new Runnable() { 3156 public void run() { 3157 mHandler.removeCallbacks(this); 3158 boolean success = true; 3159 synchronized (mInstallLock) { 3160 try { 3161 mInstaller.freeCache(volumeUuid, freeStorageSize); 3162 } catch (InstallerException e) { 3163 Slog.w(TAG, "Couldn't clear application caches: " + e); 3164 success = false; 3165 } 3166 } 3167 if (observer != null) { 3168 try { 3169 observer.onRemoveCompleted(null, success); 3170 } catch (RemoteException e) { 3171 Slog.w(TAG, "RemoveException when invoking call back"); 3172 } 3173 } 3174 } 3175 }); 3176 } 3177 3178 @Override 3179 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3180 final IntentSender pi) { 3181 mContext.enforceCallingOrSelfPermission( 3182 android.Manifest.permission.CLEAR_APP_CACHE, null); 3183 // Queue up an async operation since clearing cache may take a little while. 3184 mHandler.post(new Runnable() { 3185 public void run() { 3186 mHandler.removeCallbacks(this); 3187 boolean success = true; 3188 synchronized (mInstallLock) { 3189 try { 3190 mInstaller.freeCache(volumeUuid, freeStorageSize); 3191 } catch (InstallerException e) { 3192 Slog.w(TAG, "Couldn't clear application caches: " + e); 3193 success = false; 3194 } 3195 } 3196 if(pi != null) { 3197 try { 3198 // Callback via pending intent 3199 int code = success ? 1 : 0; 3200 pi.sendIntent(null, code, null, 3201 null, null); 3202 } catch (SendIntentException e1) { 3203 Slog.i(TAG, "Failed to send pending intent"); 3204 } 3205 } 3206 } 3207 }); 3208 } 3209 3210 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3211 synchronized (mInstallLock) { 3212 try { 3213 mInstaller.freeCache(volumeUuid, freeStorageSize); 3214 } catch (InstallerException e) { 3215 throw new IOException("Failed to free enough space", e); 3216 } 3217 } 3218 } 3219 3220 /** 3221 * Return if the user key is currently unlocked. 3222 */ 3223 private boolean isUserKeyUnlocked(int userId) { 3224 if (StorageManager.isFileBasedEncryptionEnabled()) { 3225 final IMountService mount = IMountService.Stub 3226 .asInterface(ServiceManager.getService("mount")); 3227 if (mount == null) { 3228 Slog.w(TAG, "Early during boot, assuming locked"); 3229 return false; 3230 } 3231 final long token = Binder.clearCallingIdentity(); 3232 try { 3233 return mount.isUserKeyUnlocked(userId); 3234 } catch (RemoteException e) { 3235 throw e.rethrowAsRuntimeException(); 3236 } finally { 3237 Binder.restoreCallingIdentity(token); 3238 } 3239 } else { 3240 return true; 3241 } 3242 } 3243 3244 /** 3245 * Update given flags based on encryption status of current user. 3246 */ 3247 private int updateFlags(int flags, int userId) { 3248 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3249 | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) { 3250 // Caller expressed an explicit opinion about what encryption 3251 // aware/unaware components they want to see, so fall through and 3252 // give them what they want 3253 } else { 3254 // Caller expressed no opinion, so match based on user state 3255 if (isUserKeyUnlocked(userId)) { 3256 flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE; 3257 } else { 3258 flags |= PackageManager.MATCH_ENCRYPTION_AWARE; 3259 } 3260 } 3261 return flags; 3262 } 3263 3264 /** 3265 * Update given flags when being used to request {@link PackageInfo}. 3266 */ 3267 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3268 boolean triaged = true; 3269 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3270 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3271 // Caller is asking for component details, so they'd better be 3272 // asking for specific encryption matching behavior, or be triaged 3273 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3274 | PackageManager.MATCH_ENCRYPTION_AWARE 3275 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3276 triaged = false; 3277 } 3278 } 3279 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3280 | PackageManager.MATCH_SYSTEM_ONLY 3281 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3282 triaged = false; 3283 } 3284 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3285 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3286 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3287 } 3288 return updateFlags(flags, userId); 3289 } 3290 3291 /** 3292 * Update given flags when being used to request {@link ApplicationInfo}. 3293 */ 3294 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3295 return updateFlagsForPackage(flags, userId, cookie); 3296 } 3297 3298 /** 3299 * Update given flags when being used to request {@link ComponentInfo}. 3300 */ 3301 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3302 if (cookie instanceof Intent) { 3303 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3304 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3305 } 3306 } 3307 3308 boolean triaged = true; 3309 // Caller is asking for component details, so they'd better be 3310 // asking for specific encryption matching behavior, or be triaged 3311 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3312 | PackageManager.MATCH_ENCRYPTION_AWARE 3313 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3314 triaged = false; 3315 } 3316 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3317 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3318 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3319 } 3320 3321 return updateFlags(flags, userId); 3322 } 3323 3324 /** 3325 * Update given flags when being used to request {@link ResolveInfo}. 3326 */ 3327 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3328 // Safe mode means we shouldn't match any third-party components 3329 if (mSafeMode) { 3330 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3331 } 3332 3333 return updateFlagsForComponent(flags, userId, cookie); 3334 } 3335 3336 @Override 3337 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3338 if (!sUserManager.exists(userId)) return null; 3339 flags = updateFlagsForComponent(flags, userId, component); 3340 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3341 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3342 synchronized (mPackages) { 3343 PackageParser.Activity a = mActivities.mActivities.get(component); 3344 3345 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3346 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3347 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3348 if (ps == null) return null; 3349 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3350 userId); 3351 } 3352 if (mResolveComponentName.equals(component)) { 3353 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3354 new PackageUserState(), userId); 3355 } 3356 } 3357 return null; 3358 } 3359 3360 @Override 3361 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3362 String resolvedType) { 3363 synchronized (mPackages) { 3364 if (component.equals(mResolveComponentName)) { 3365 // The resolver supports EVERYTHING! 3366 return true; 3367 } 3368 PackageParser.Activity a = mActivities.mActivities.get(component); 3369 if (a == null) { 3370 return false; 3371 } 3372 for (int i=0; i<a.intents.size(); i++) { 3373 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3374 intent.getData(), intent.getCategories(), TAG) >= 0) { 3375 return true; 3376 } 3377 } 3378 return false; 3379 } 3380 } 3381 3382 @Override 3383 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3384 if (!sUserManager.exists(userId)) return null; 3385 flags = updateFlagsForComponent(flags, userId, component); 3386 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3387 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3388 synchronized (mPackages) { 3389 PackageParser.Activity a = mReceivers.mActivities.get(component); 3390 if (DEBUG_PACKAGE_INFO) Log.v( 3391 TAG, "getReceiverInfo " + component + ": " + a); 3392 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3393 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3394 if (ps == null) return null; 3395 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3396 userId); 3397 } 3398 } 3399 return null; 3400 } 3401 3402 @Override 3403 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3404 if (!sUserManager.exists(userId)) return null; 3405 flags = updateFlagsForComponent(flags, userId, component); 3406 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3407 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3408 synchronized (mPackages) { 3409 PackageParser.Service s = mServices.mServices.get(component); 3410 if (DEBUG_PACKAGE_INFO) Log.v( 3411 TAG, "getServiceInfo " + component + ": " + s); 3412 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3413 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3414 if (ps == null) return null; 3415 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3416 userId); 3417 } 3418 } 3419 return null; 3420 } 3421 3422 @Override 3423 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3424 if (!sUserManager.exists(userId)) return null; 3425 flags = updateFlagsForComponent(flags, userId, component); 3426 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3427 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3428 synchronized (mPackages) { 3429 PackageParser.Provider p = mProviders.mProviders.get(component); 3430 if (DEBUG_PACKAGE_INFO) Log.v( 3431 TAG, "getProviderInfo " + component + ": " + p); 3432 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3433 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3434 if (ps == null) return null; 3435 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3436 userId); 3437 } 3438 } 3439 return null; 3440 } 3441 3442 @Override 3443 public String[] getSystemSharedLibraryNames() { 3444 Set<String> libSet; 3445 synchronized (mPackages) { 3446 libSet = mSharedLibraries.keySet(); 3447 int size = libSet.size(); 3448 if (size > 0) { 3449 String[] libs = new String[size]; 3450 libSet.toArray(libs); 3451 return libs; 3452 } 3453 } 3454 return null; 3455 } 3456 3457 @Override 3458 public @Nullable String getServicesSystemSharedLibraryPackageName() { 3459 synchronized (mPackages) { 3460 SharedLibraryEntry libraryEntry = mSharedLibraries.get( 3461 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 3462 if (libraryEntry != null) { 3463 return libraryEntry.apk; 3464 } 3465 } 3466 return null; 3467 } 3468 3469 @Override 3470 public FeatureInfo[] getSystemAvailableFeatures() { 3471 Collection<FeatureInfo> featSet; 3472 synchronized (mPackages) { 3473 featSet = mAvailableFeatures.values(); 3474 int size = featSet.size(); 3475 if (size > 0) { 3476 FeatureInfo[] features = new FeatureInfo[size+1]; 3477 featSet.toArray(features); 3478 FeatureInfo fi = new FeatureInfo(); 3479 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3480 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3481 features[size] = fi; 3482 return features; 3483 } 3484 } 3485 return null; 3486 } 3487 3488 @Override 3489 public boolean hasSystemFeature(String name, int version) { 3490 synchronized (mPackages) { 3491 final FeatureInfo feat = mAvailableFeatures.get(name); 3492 if (feat == null) { 3493 return false; 3494 } else { 3495 return feat.version >= version; 3496 } 3497 } 3498 } 3499 3500 @Override 3501 public int checkPermission(String permName, String pkgName, int userId) { 3502 if (!sUserManager.exists(userId)) { 3503 return PackageManager.PERMISSION_DENIED; 3504 } 3505 3506 synchronized (mPackages) { 3507 final PackageParser.Package p = mPackages.get(pkgName); 3508 if (p != null && p.mExtras != null) { 3509 final PackageSetting ps = (PackageSetting) p.mExtras; 3510 final PermissionsState permissionsState = ps.getPermissionsState(); 3511 if (permissionsState.hasPermission(permName, userId)) { 3512 return PackageManager.PERMISSION_GRANTED; 3513 } 3514 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3515 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3516 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3517 return PackageManager.PERMISSION_GRANTED; 3518 } 3519 } 3520 } 3521 3522 return PackageManager.PERMISSION_DENIED; 3523 } 3524 3525 @Override 3526 public int checkUidPermission(String permName, int uid) { 3527 final int userId = UserHandle.getUserId(uid); 3528 3529 if (!sUserManager.exists(userId)) { 3530 return PackageManager.PERMISSION_DENIED; 3531 } 3532 3533 synchronized (mPackages) { 3534 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3535 if (obj != null) { 3536 final SettingBase ps = (SettingBase) obj; 3537 final PermissionsState permissionsState = ps.getPermissionsState(); 3538 if (permissionsState.hasPermission(permName, userId)) { 3539 return PackageManager.PERMISSION_GRANTED; 3540 } 3541 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3542 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3543 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3544 return PackageManager.PERMISSION_GRANTED; 3545 } 3546 } else { 3547 ArraySet<String> perms = mSystemPermissions.get(uid); 3548 if (perms != null) { 3549 if (perms.contains(permName)) { 3550 return PackageManager.PERMISSION_GRANTED; 3551 } 3552 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3553 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3554 return PackageManager.PERMISSION_GRANTED; 3555 } 3556 } 3557 } 3558 } 3559 3560 return PackageManager.PERMISSION_DENIED; 3561 } 3562 3563 @Override 3564 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3565 if (UserHandle.getCallingUserId() != userId) { 3566 mContext.enforceCallingPermission( 3567 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3568 "isPermissionRevokedByPolicy for user " + userId); 3569 } 3570 3571 if (checkPermission(permission, packageName, userId) 3572 == PackageManager.PERMISSION_GRANTED) { 3573 return false; 3574 } 3575 3576 final long identity = Binder.clearCallingIdentity(); 3577 try { 3578 final int flags = getPermissionFlags(permission, packageName, userId); 3579 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3580 } finally { 3581 Binder.restoreCallingIdentity(identity); 3582 } 3583 } 3584 3585 @Override 3586 public String getPermissionControllerPackageName() { 3587 synchronized (mPackages) { 3588 return mRequiredInstallerPackage; 3589 } 3590 } 3591 3592 /** 3593 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3594 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3595 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3596 * @param message the message to log on security exception 3597 */ 3598 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3599 boolean checkShell, String message) { 3600 if (userId < 0) { 3601 throw new IllegalArgumentException("Invalid userId " + userId); 3602 } 3603 if (checkShell) { 3604 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3605 } 3606 if (userId == UserHandle.getUserId(callingUid)) return; 3607 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3608 if (requireFullPermission) { 3609 mContext.enforceCallingOrSelfPermission( 3610 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3611 } else { 3612 try { 3613 mContext.enforceCallingOrSelfPermission( 3614 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3615 } catch (SecurityException se) { 3616 mContext.enforceCallingOrSelfPermission( 3617 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3618 } 3619 } 3620 } 3621 } 3622 3623 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3624 if (callingUid == Process.SHELL_UID) { 3625 if (userHandle >= 0 3626 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3627 throw new SecurityException("Shell does not have permission to access user " 3628 + userHandle); 3629 } else if (userHandle < 0) { 3630 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3631 + Debug.getCallers(3)); 3632 } 3633 } 3634 } 3635 3636 private BasePermission findPermissionTreeLP(String permName) { 3637 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3638 if (permName.startsWith(bp.name) && 3639 permName.length() > bp.name.length() && 3640 permName.charAt(bp.name.length()) == '.') { 3641 return bp; 3642 } 3643 } 3644 return null; 3645 } 3646 3647 private BasePermission checkPermissionTreeLP(String permName) { 3648 if (permName != null) { 3649 BasePermission bp = findPermissionTreeLP(permName); 3650 if (bp != null) { 3651 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3652 return bp; 3653 } 3654 throw new SecurityException("Calling uid " 3655 + Binder.getCallingUid() 3656 + " is not allowed to add to permission tree " 3657 + bp.name + " owned by uid " + bp.uid); 3658 } 3659 } 3660 throw new SecurityException("No permission tree found for " + permName); 3661 } 3662 3663 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3664 if (s1 == null) { 3665 return s2 == null; 3666 } 3667 if (s2 == null) { 3668 return false; 3669 } 3670 if (s1.getClass() != s2.getClass()) { 3671 return false; 3672 } 3673 return s1.equals(s2); 3674 } 3675 3676 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3677 if (pi1.icon != pi2.icon) return false; 3678 if (pi1.logo != pi2.logo) return false; 3679 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3680 if (!compareStrings(pi1.name, pi2.name)) return false; 3681 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3682 // We'll take care of setting this one. 3683 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3684 // These are not currently stored in settings. 3685 //if (!compareStrings(pi1.group, pi2.group)) return false; 3686 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3687 //if (pi1.labelRes != pi2.labelRes) return false; 3688 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3689 return true; 3690 } 3691 3692 int permissionInfoFootprint(PermissionInfo info) { 3693 int size = info.name.length(); 3694 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3695 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3696 return size; 3697 } 3698 3699 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3700 int size = 0; 3701 for (BasePermission perm : mSettings.mPermissions.values()) { 3702 if (perm.uid == tree.uid) { 3703 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3704 } 3705 } 3706 return size; 3707 } 3708 3709 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3710 // We calculate the max size of permissions defined by this uid and throw 3711 // if that plus the size of 'info' would exceed our stated maximum. 3712 if (tree.uid != Process.SYSTEM_UID) { 3713 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3714 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3715 throw new SecurityException("Permission tree size cap exceeded"); 3716 } 3717 } 3718 } 3719 3720 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3721 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3722 throw new SecurityException("Label must be specified in permission"); 3723 } 3724 BasePermission tree = checkPermissionTreeLP(info.name); 3725 BasePermission bp = mSettings.mPermissions.get(info.name); 3726 boolean added = bp == null; 3727 boolean changed = true; 3728 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3729 if (added) { 3730 enforcePermissionCapLocked(info, tree); 3731 bp = new BasePermission(info.name, tree.sourcePackage, 3732 BasePermission.TYPE_DYNAMIC); 3733 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3734 throw new SecurityException( 3735 "Not allowed to modify non-dynamic permission " 3736 + info.name); 3737 } else { 3738 if (bp.protectionLevel == fixedLevel 3739 && bp.perm.owner.equals(tree.perm.owner) 3740 && bp.uid == tree.uid 3741 && comparePermissionInfos(bp.perm.info, info)) { 3742 changed = false; 3743 } 3744 } 3745 bp.protectionLevel = fixedLevel; 3746 info = new PermissionInfo(info); 3747 info.protectionLevel = fixedLevel; 3748 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3749 bp.perm.info.packageName = tree.perm.info.packageName; 3750 bp.uid = tree.uid; 3751 if (added) { 3752 mSettings.mPermissions.put(info.name, bp); 3753 } 3754 if (changed) { 3755 if (!async) { 3756 mSettings.writeLPr(); 3757 } else { 3758 scheduleWriteSettingsLocked(); 3759 } 3760 } 3761 return added; 3762 } 3763 3764 @Override 3765 public boolean addPermission(PermissionInfo info) { 3766 synchronized (mPackages) { 3767 return addPermissionLocked(info, false); 3768 } 3769 } 3770 3771 @Override 3772 public boolean addPermissionAsync(PermissionInfo info) { 3773 synchronized (mPackages) { 3774 return addPermissionLocked(info, true); 3775 } 3776 } 3777 3778 @Override 3779 public void removePermission(String name) { 3780 synchronized (mPackages) { 3781 checkPermissionTreeLP(name); 3782 BasePermission bp = mSettings.mPermissions.get(name); 3783 if (bp != null) { 3784 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3785 throw new SecurityException( 3786 "Not allowed to modify non-dynamic permission " 3787 + name); 3788 } 3789 mSettings.mPermissions.remove(name); 3790 mSettings.writeLPr(); 3791 } 3792 } 3793 } 3794 3795 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3796 BasePermission bp) { 3797 int index = pkg.requestedPermissions.indexOf(bp.name); 3798 if (index == -1) { 3799 throw new SecurityException("Package " + pkg.packageName 3800 + " has not requested permission " + bp.name); 3801 } 3802 if (!bp.isRuntime() && !bp.isDevelopment()) { 3803 throw new SecurityException("Permission " + bp.name 3804 + " is not a changeable permission type"); 3805 } 3806 } 3807 3808 @Override 3809 public void grantRuntimePermission(String packageName, String name, final int userId) { 3810 if (!sUserManager.exists(userId)) { 3811 Log.e(TAG, "No such user:" + userId); 3812 return; 3813 } 3814 3815 mContext.enforceCallingOrSelfPermission( 3816 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3817 "grantRuntimePermission"); 3818 3819 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3820 true /* requireFullPermission */, true /* checkShell */, 3821 "grantRuntimePermission"); 3822 3823 final int uid; 3824 final SettingBase sb; 3825 3826 synchronized (mPackages) { 3827 final PackageParser.Package pkg = mPackages.get(packageName); 3828 if (pkg == null) { 3829 throw new IllegalArgumentException("Unknown package: " + packageName); 3830 } 3831 3832 final BasePermission bp = mSettings.mPermissions.get(name); 3833 if (bp == null) { 3834 throw new IllegalArgumentException("Unknown permission: " + name); 3835 } 3836 3837 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3838 3839 // If a permission review is required for legacy apps we represent 3840 // their permissions as always granted runtime ones since we need 3841 // to keep the review required permission flag per user while an 3842 // install permission's state is shared across all users. 3843 if (Build.PERMISSIONS_REVIEW_REQUIRED 3844 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3845 && bp.isRuntime()) { 3846 return; 3847 } 3848 3849 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3850 sb = (SettingBase) pkg.mExtras; 3851 if (sb == null) { 3852 throw new IllegalArgumentException("Unknown package: " + packageName); 3853 } 3854 3855 final PermissionsState permissionsState = sb.getPermissionsState(); 3856 3857 final int flags = permissionsState.getPermissionFlags(name, userId); 3858 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3859 throw new SecurityException("Cannot grant system fixed permission " 3860 + name + " for package " + packageName); 3861 } 3862 3863 if (bp.isDevelopment()) { 3864 // Development permissions must be handled specially, since they are not 3865 // normal runtime permissions. For now they apply to all users. 3866 if (permissionsState.grantInstallPermission(bp) != 3867 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3868 scheduleWriteSettingsLocked(); 3869 } 3870 return; 3871 } 3872 3873 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 3874 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 3875 return; 3876 } 3877 3878 final int result = permissionsState.grantRuntimePermission(bp, userId); 3879 switch (result) { 3880 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3881 return; 3882 } 3883 3884 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3885 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3886 mHandler.post(new Runnable() { 3887 @Override 3888 public void run() { 3889 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3890 } 3891 }); 3892 } 3893 break; 3894 } 3895 3896 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3897 3898 // Not critical if that is lost - app has to request again. 3899 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3900 } 3901 3902 // Only need to do this if user is initialized. Otherwise it's a new user 3903 // and there are no processes running as the user yet and there's no need 3904 // to make an expensive call to remount processes for the changed permissions. 3905 if (READ_EXTERNAL_STORAGE.equals(name) 3906 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3907 final long token = Binder.clearCallingIdentity(); 3908 try { 3909 if (sUserManager.isInitialized(userId)) { 3910 MountServiceInternal mountServiceInternal = LocalServices.getService( 3911 MountServiceInternal.class); 3912 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3913 } 3914 } finally { 3915 Binder.restoreCallingIdentity(token); 3916 } 3917 } 3918 } 3919 3920 @Override 3921 public void revokeRuntimePermission(String packageName, String name, int userId) { 3922 if (!sUserManager.exists(userId)) { 3923 Log.e(TAG, "No such user:" + userId); 3924 return; 3925 } 3926 3927 mContext.enforceCallingOrSelfPermission( 3928 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3929 "revokeRuntimePermission"); 3930 3931 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3932 true /* requireFullPermission */, true /* checkShell */, 3933 "revokeRuntimePermission"); 3934 3935 final int appId; 3936 3937 synchronized (mPackages) { 3938 final PackageParser.Package pkg = mPackages.get(packageName); 3939 if (pkg == null) { 3940 throw new IllegalArgumentException("Unknown package: " + packageName); 3941 } 3942 3943 final BasePermission bp = mSettings.mPermissions.get(name); 3944 if (bp == null) { 3945 throw new IllegalArgumentException("Unknown permission: " + name); 3946 } 3947 3948 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3949 3950 // If a permission review is required for legacy apps we represent 3951 // their permissions as always granted runtime ones since we need 3952 // to keep the review required permission flag per user while an 3953 // install permission's state is shared across all users. 3954 if (Build.PERMISSIONS_REVIEW_REQUIRED 3955 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3956 && bp.isRuntime()) { 3957 return; 3958 } 3959 3960 SettingBase sb = (SettingBase) pkg.mExtras; 3961 if (sb == null) { 3962 throw new IllegalArgumentException("Unknown package: " + packageName); 3963 } 3964 3965 final PermissionsState permissionsState = sb.getPermissionsState(); 3966 3967 final int flags = permissionsState.getPermissionFlags(name, userId); 3968 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3969 throw new SecurityException("Cannot revoke system fixed permission " 3970 + name + " for package " + packageName); 3971 } 3972 3973 if (bp.isDevelopment()) { 3974 // Development permissions must be handled specially, since they are not 3975 // normal runtime permissions. For now they apply to all users. 3976 if (permissionsState.revokeInstallPermission(bp) != 3977 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3978 scheduleWriteSettingsLocked(); 3979 } 3980 return; 3981 } 3982 3983 if (permissionsState.revokeRuntimePermission(bp, userId) == 3984 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3985 return; 3986 } 3987 3988 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3989 3990 // Critical, after this call app should never have the permission. 3991 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3992 3993 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3994 } 3995 3996 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3997 } 3998 3999 @Override 4000 public void resetRuntimePermissions() { 4001 mContext.enforceCallingOrSelfPermission( 4002 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4003 "revokeRuntimePermission"); 4004 4005 int callingUid = Binder.getCallingUid(); 4006 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4007 mContext.enforceCallingOrSelfPermission( 4008 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4009 "resetRuntimePermissions"); 4010 } 4011 4012 synchronized (mPackages) { 4013 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4014 for (int userId : UserManagerService.getInstance().getUserIds()) { 4015 final int packageCount = mPackages.size(); 4016 for (int i = 0; i < packageCount; i++) { 4017 PackageParser.Package pkg = mPackages.valueAt(i); 4018 if (!(pkg.mExtras instanceof PackageSetting)) { 4019 continue; 4020 } 4021 PackageSetting ps = (PackageSetting) pkg.mExtras; 4022 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4023 } 4024 } 4025 } 4026 } 4027 4028 @Override 4029 public int getPermissionFlags(String name, String packageName, int userId) { 4030 if (!sUserManager.exists(userId)) { 4031 return 0; 4032 } 4033 4034 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4035 4036 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4037 true /* requireFullPermission */, false /* checkShell */, 4038 "getPermissionFlags"); 4039 4040 synchronized (mPackages) { 4041 final PackageParser.Package pkg = mPackages.get(packageName); 4042 if (pkg == null) { 4043 throw new IllegalArgumentException("Unknown package: " + packageName); 4044 } 4045 4046 final BasePermission bp = mSettings.mPermissions.get(name); 4047 if (bp == null) { 4048 throw new IllegalArgumentException("Unknown permission: " + name); 4049 } 4050 4051 SettingBase sb = (SettingBase) pkg.mExtras; 4052 if (sb == null) { 4053 throw new IllegalArgumentException("Unknown package: " + packageName); 4054 } 4055 4056 PermissionsState permissionsState = sb.getPermissionsState(); 4057 return permissionsState.getPermissionFlags(name, userId); 4058 } 4059 } 4060 4061 @Override 4062 public void updatePermissionFlags(String name, String packageName, int flagMask, 4063 int flagValues, int userId) { 4064 if (!sUserManager.exists(userId)) { 4065 return; 4066 } 4067 4068 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4069 4070 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4071 true /* requireFullPermission */, true /* checkShell */, 4072 "updatePermissionFlags"); 4073 4074 // Only the system can change these flags and nothing else. 4075 if (getCallingUid() != Process.SYSTEM_UID) { 4076 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4077 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4078 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4079 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4080 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4081 } 4082 4083 synchronized (mPackages) { 4084 final PackageParser.Package pkg = mPackages.get(packageName); 4085 if (pkg == null) { 4086 throw new IllegalArgumentException("Unknown package: " + packageName); 4087 } 4088 4089 final BasePermission bp = mSettings.mPermissions.get(name); 4090 if (bp == null) { 4091 throw new IllegalArgumentException("Unknown permission: " + name); 4092 } 4093 4094 SettingBase sb = (SettingBase) pkg.mExtras; 4095 if (sb == null) { 4096 throw new IllegalArgumentException("Unknown package: " + packageName); 4097 } 4098 4099 PermissionsState permissionsState = sb.getPermissionsState(); 4100 4101 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4102 4103 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4104 // Install and runtime permissions are stored in different places, 4105 // so figure out what permission changed and persist the change. 4106 if (permissionsState.getInstallPermissionState(name) != null) { 4107 scheduleWriteSettingsLocked(); 4108 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4109 || hadState) { 4110 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4111 } 4112 } 4113 } 4114 } 4115 4116 /** 4117 * Update the permission flags for all packages and runtime permissions of a user in order 4118 * to allow device or profile owner to remove POLICY_FIXED. 4119 */ 4120 @Override 4121 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4122 if (!sUserManager.exists(userId)) { 4123 return; 4124 } 4125 4126 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4127 4128 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4129 true /* requireFullPermission */, true /* checkShell */, 4130 "updatePermissionFlagsForAllApps"); 4131 4132 // Only the system can change system fixed flags. 4133 if (getCallingUid() != Process.SYSTEM_UID) { 4134 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4135 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4136 } 4137 4138 synchronized (mPackages) { 4139 boolean changed = false; 4140 final int packageCount = mPackages.size(); 4141 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4142 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4143 SettingBase sb = (SettingBase) pkg.mExtras; 4144 if (sb == null) { 4145 continue; 4146 } 4147 PermissionsState permissionsState = sb.getPermissionsState(); 4148 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4149 userId, flagMask, flagValues); 4150 } 4151 if (changed) { 4152 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4153 } 4154 } 4155 } 4156 4157 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4158 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4159 != PackageManager.PERMISSION_GRANTED 4160 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4161 != PackageManager.PERMISSION_GRANTED) { 4162 throw new SecurityException(message + " requires " 4163 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4164 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4165 } 4166 } 4167 4168 @Override 4169 public boolean shouldShowRequestPermissionRationale(String permissionName, 4170 String packageName, int userId) { 4171 if (UserHandle.getCallingUserId() != userId) { 4172 mContext.enforceCallingPermission( 4173 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4174 "canShowRequestPermissionRationale for user " + userId); 4175 } 4176 4177 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4178 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4179 return false; 4180 } 4181 4182 if (checkPermission(permissionName, packageName, userId) 4183 == PackageManager.PERMISSION_GRANTED) { 4184 return false; 4185 } 4186 4187 final int flags; 4188 4189 final long identity = Binder.clearCallingIdentity(); 4190 try { 4191 flags = getPermissionFlags(permissionName, 4192 packageName, userId); 4193 } finally { 4194 Binder.restoreCallingIdentity(identity); 4195 } 4196 4197 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4198 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4199 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4200 4201 if ((flags & fixedFlags) != 0) { 4202 return false; 4203 } 4204 4205 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4206 } 4207 4208 @Override 4209 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4210 mContext.enforceCallingOrSelfPermission( 4211 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4212 "addOnPermissionsChangeListener"); 4213 4214 synchronized (mPackages) { 4215 mOnPermissionChangeListeners.addListenerLocked(listener); 4216 } 4217 } 4218 4219 @Override 4220 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4221 synchronized (mPackages) { 4222 mOnPermissionChangeListeners.removeListenerLocked(listener); 4223 } 4224 } 4225 4226 @Override 4227 public boolean isProtectedBroadcast(String actionName) { 4228 synchronized (mPackages) { 4229 if (mProtectedBroadcasts.contains(actionName)) { 4230 return true; 4231 } else if (actionName != null) { 4232 // TODO: remove these terrible hacks 4233 if (actionName.startsWith("android.net.netmon.lingerExpired") 4234 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4235 || actionName.startsWith("com.android.internal.telephony.data-reconnect")) { 4236 return true; 4237 } 4238 } 4239 } 4240 return false; 4241 } 4242 4243 @Override 4244 public int checkSignatures(String pkg1, String pkg2) { 4245 synchronized (mPackages) { 4246 final PackageParser.Package p1 = mPackages.get(pkg1); 4247 final PackageParser.Package p2 = mPackages.get(pkg2); 4248 if (p1 == null || p1.mExtras == null 4249 || p2 == null || p2.mExtras == null) { 4250 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4251 } 4252 return compareSignatures(p1.mSignatures, p2.mSignatures); 4253 } 4254 } 4255 4256 @Override 4257 public int checkUidSignatures(int uid1, int uid2) { 4258 // Map to base uids. 4259 uid1 = UserHandle.getAppId(uid1); 4260 uid2 = UserHandle.getAppId(uid2); 4261 // reader 4262 synchronized (mPackages) { 4263 Signature[] s1; 4264 Signature[] s2; 4265 Object obj = mSettings.getUserIdLPr(uid1); 4266 if (obj != null) { 4267 if (obj instanceof SharedUserSetting) { 4268 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4269 } else if (obj instanceof PackageSetting) { 4270 s1 = ((PackageSetting)obj).signatures.mSignatures; 4271 } else { 4272 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4273 } 4274 } else { 4275 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4276 } 4277 obj = mSettings.getUserIdLPr(uid2); 4278 if (obj != null) { 4279 if (obj instanceof SharedUserSetting) { 4280 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4281 } else if (obj instanceof PackageSetting) { 4282 s2 = ((PackageSetting)obj).signatures.mSignatures; 4283 } else { 4284 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4285 } 4286 } else { 4287 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4288 } 4289 return compareSignatures(s1, s2); 4290 } 4291 } 4292 4293 private void killUid(int appId, int userId, String reason) { 4294 final long identity = Binder.clearCallingIdentity(); 4295 try { 4296 IActivityManager am = ActivityManagerNative.getDefault(); 4297 if (am != null) { 4298 try { 4299 am.killUid(appId, userId, reason); 4300 } catch (RemoteException e) { 4301 /* ignore - same process */ 4302 } 4303 } 4304 } finally { 4305 Binder.restoreCallingIdentity(identity); 4306 } 4307 } 4308 4309 /** 4310 * Compares two sets of signatures. Returns: 4311 * <br /> 4312 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4313 * <br /> 4314 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4315 * <br /> 4316 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4317 * <br /> 4318 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4319 * <br /> 4320 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4321 */ 4322 static int compareSignatures(Signature[] s1, Signature[] s2) { 4323 if (s1 == null) { 4324 return s2 == null 4325 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4326 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4327 } 4328 4329 if (s2 == null) { 4330 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4331 } 4332 4333 if (s1.length != s2.length) { 4334 return PackageManager.SIGNATURE_NO_MATCH; 4335 } 4336 4337 // Since both signature sets are of size 1, we can compare without HashSets. 4338 if (s1.length == 1) { 4339 return s1[0].equals(s2[0]) ? 4340 PackageManager.SIGNATURE_MATCH : 4341 PackageManager.SIGNATURE_NO_MATCH; 4342 } 4343 4344 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4345 for (Signature sig : s1) { 4346 set1.add(sig); 4347 } 4348 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4349 for (Signature sig : s2) { 4350 set2.add(sig); 4351 } 4352 // Make sure s2 contains all signatures in s1. 4353 if (set1.equals(set2)) { 4354 return PackageManager.SIGNATURE_MATCH; 4355 } 4356 return PackageManager.SIGNATURE_NO_MATCH; 4357 } 4358 4359 /** 4360 * If the database version for this type of package (internal storage or 4361 * external storage) is less than the version where package signatures 4362 * were updated, return true. 4363 */ 4364 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4365 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4366 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4367 } 4368 4369 /** 4370 * Used for backward compatibility to make sure any packages with 4371 * certificate chains get upgraded to the new style. {@code existingSigs} 4372 * will be in the old format (since they were stored on disk from before the 4373 * system upgrade) and {@code scannedSigs} will be in the newer format. 4374 */ 4375 private int compareSignaturesCompat(PackageSignatures existingSigs, 4376 PackageParser.Package scannedPkg) { 4377 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4378 return PackageManager.SIGNATURE_NO_MATCH; 4379 } 4380 4381 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4382 for (Signature sig : existingSigs.mSignatures) { 4383 existingSet.add(sig); 4384 } 4385 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4386 for (Signature sig : scannedPkg.mSignatures) { 4387 try { 4388 Signature[] chainSignatures = sig.getChainSignatures(); 4389 for (Signature chainSig : chainSignatures) { 4390 scannedCompatSet.add(chainSig); 4391 } 4392 } catch (CertificateEncodingException e) { 4393 scannedCompatSet.add(sig); 4394 } 4395 } 4396 /* 4397 * Make sure the expanded scanned set contains all signatures in the 4398 * existing one. 4399 */ 4400 if (scannedCompatSet.equals(existingSet)) { 4401 // Migrate the old signatures to the new scheme. 4402 existingSigs.assignSignatures(scannedPkg.mSignatures); 4403 // The new KeySets will be re-added later in the scanning process. 4404 synchronized (mPackages) { 4405 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4406 } 4407 return PackageManager.SIGNATURE_MATCH; 4408 } 4409 return PackageManager.SIGNATURE_NO_MATCH; 4410 } 4411 4412 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4413 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4414 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4415 } 4416 4417 private int compareSignaturesRecover(PackageSignatures existingSigs, 4418 PackageParser.Package scannedPkg) { 4419 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4420 return PackageManager.SIGNATURE_NO_MATCH; 4421 } 4422 4423 String msg = null; 4424 try { 4425 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4426 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4427 + scannedPkg.packageName); 4428 return PackageManager.SIGNATURE_MATCH; 4429 } 4430 } catch (CertificateException e) { 4431 msg = e.getMessage(); 4432 } 4433 4434 logCriticalInfo(Log.INFO, 4435 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4436 return PackageManager.SIGNATURE_NO_MATCH; 4437 } 4438 4439 @Override 4440 public String[] getPackagesForUid(int uid) { 4441 uid = UserHandle.getAppId(uid); 4442 // reader 4443 synchronized (mPackages) { 4444 Object obj = mSettings.getUserIdLPr(uid); 4445 if (obj instanceof SharedUserSetting) { 4446 final SharedUserSetting sus = (SharedUserSetting) obj; 4447 final int N = sus.packages.size(); 4448 final String[] res = new String[N]; 4449 final Iterator<PackageSetting> it = sus.packages.iterator(); 4450 int i = 0; 4451 while (it.hasNext()) { 4452 res[i++] = it.next().name; 4453 } 4454 return res; 4455 } else if (obj instanceof PackageSetting) { 4456 final PackageSetting ps = (PackageSetting) obj; 4457 return new String[] { ps.name }; 4458 } 4459 } 4460 return null; 4461 } 4462 4463 @Override 4464 public String getNameForUid(int uid) { 4465 // reader 4466 synchronized (mPackages) { 4467 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4468 if (obj instanceof SharedUserSetting) { 4469 final SharedUserSetting sus = (SharedUserSetting) obj; 4470 return sus.name + ":" + sus.userId; 4471 } else if (obj instanceof PackageSetting) { 4472 final PackageSetting ps = (PackageSetting) obj; 4473 return ps.name; 4474 } 4475 } 4476 return null; 4477 } 4478 4479 @Override 4480 public int getUidForSharedUser(String sharedUserName) { 4481 if(sharedUserName == null) { 4482 return -1; 4483 } 4484 // reader 4485 synchronized (mPackages) { 4486 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4487 if (suid == null) { 4488 return -1; 4489 } 4490 return suid.userId; 4491 } 4492 } 4493 4494 @Override 4495 public int getFlagsForUid(int uid) { 4496 synchronized (mPackages) { 4497 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4498 if (obj instanceof SharedUserSetting) { 4499 final SharedUserSetting sus = (SharedUserSetting) obj; 4500 return sus.pkgFlags; 4501 } else if (obj instanceof PackageSetting) { 4502 final PackageSetting ps = (PackageSetting) obj; 4503 return ps.pkgFlags; 4504 } 4505 } 4506 return 0; 4507 } 4508 4509 @Override 4510 public int getPrivateFlagsForUid(int uid) { 4511 synchronized (mPackages) { 4512 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4513 if (obj instanceof SharedUserSetting) { 4514 final SharedUserSetting sus = (SharedUserSetting) obj; 4515 return sus.pkgPrivateFlags; 4516 } else if (obj instanceof PackageSetting) { 4517 final PackageSetting ps = (PackageSetting) obj; 4518 return ps.pkgPrivateFlags; 4519 } 4520 } 4521 return 0; 4522 } 4523 4524 @Override 4525 public boolean isUidPrivileged(int uid) { 4526 uid = UserHandle.getAppId(uid); 4527 // reader 4528 synchronized (mPackages) { 4529 Object obj = mSettings.getUserIdLPr(uid); 4530 if (obj instanceof SharedUserSetting) { 4531 final SharedUserSetting sus = (SharedUserSetting) obj; 4532 final Iterator<PackageSetting> it = sus.packages.iterator(); 4533 while (it.hasNext()) { 4534 if (it.next().isPrivileged()) { 4535 return true; 4536 } 4537 } 4538 } else if (obj instanceof PackageSetting) { 4539 final PackageSetting ps = (PackageSetting) obj; 4540 return ps.isPrivileged(); 4541 } 4542 } 4543 return false; 4544 } 4545 4546 @Override 4547 public String[] getAppOpPermissionPackages(String permissionName) { 4548 synchronized (mPackages) { 4549 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4550 if (pkgs == null) { 4551 return null; 4552 } 4553 return pkgs.toArray(new String[pkgs.size()]); 4554 } 4555 } 4556 4557 @Override 4558 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4559 int flags, int userId) { 4560 if (!sUserManager.exists(userId)) return null; 4561 flags = updateFlagsForResolve(flags, userId, intent); 4562 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4563 false /* requireFullPermission */, false /* checkShell */, "resolve intent"); 4564 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4565 final ResolveInfo bestChoice = 4566 chooseBestActivity(intent, resolvedType, flags, query, userId); 4567 4568 if (isEphemeralAllowed(intent, query, userId)) { 4569 final EphemeralResolveInfo ai = 4570 getEphemeralResolveInfo(intent, resolvedType, userId); 4571 if (ai != null) { 4572 if (DEBUG_EPHEMERAL) { 4573 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4574 } 4575 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4576 bestChoice.ephemeralResolveInfo = ai; 4577 } 4578 } 4579 return bestChoice; 4580 } 4581 4582 @Override 4583 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4584 IntentFilter filter, int match, ComponentName activity) { 4585 final int userId = UserHandle.getCallingUserId(); 4586 if (DEBUG_PREFERRED) { 4587 Log.v(TAG, "setLastChosenActivity intent=" + intent 4588 + " resolvedType=" + resolvedType 4589 + " flags=" + flags 4590 + " filter=" + filter 4591 + " match=" + match 4592 + " activity=" + activity); 4593 filter.dump(new PrintStreamPrinter(System.out), " "); 4594 } 4595 intent.setComponent(null); 4596 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4597 // Find any earlier preferred or last chosen entries and nuke them 4598 findPreferredActivity(intent, resolvedType, 4599 flags, query, 0, false, true, false, userId); 4600 // Add the new activity as the last chosen for this filter 4601 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4602 "Setting last chosen"); 4603 } 4604 4605 @Override 4606 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4607 final int userId = UserHandle.getCallingUserId(); 4608 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4609 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4610 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4611 false, false, false, userId); 4612 } 4613 4614 4615 private boolean isEphemeralAllowed( 4616 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4617 // Short circuit and return early if possible. 4618 if (DISABLE_EPHEMERAL_APPS) { 4619 return false; 4620 } 4621 final int callingUser = UserHandle.getCallingUserId(); 4622 if (callingUser != UserHandle.USER_SYSTEM) { 4623 return false; 4624 } 4625 if (mEphemeralResolverConnection == null) { 4626 return false; 4627 } 4628 if (intent.getComponent() != null) { 4629 return false; 4630 } 4631 if (intent.getPackage() != null) { 4632 return false; 4633 } 4634 final boolean isWebUri = hasWebURI(intent); 4635 if (!isWebUri) { 4636 return false; 4637 } 4638 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4639 synchronized (mPackages) { 4640 final int count = resolvedActivites.size(); 4641 for (int n = 0; n < count; n++) { 4642 ResolveInfo info = resolvedActivites.get(n); 4643 String packageName = info.activityInfo.packageName; 4644 PackageSetting ps = mSettings.mPackages.get(packageName); 4645 if (ps != null) { 4646 // Try to get the status from User settings first 4647 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4648 int status = (int) (packedStatus >> 32); 4649 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4650 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4651 if (DEBUG_EPHEMERAL) { 4652 Slog.v(TAG, "DENY ephemeral apps;" 4653 + " pkg: " + packageName + ", status: " + status); 4654 } 4655 return false; 4656 } 4657 } 4658 } 4659 } 4660 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4661 return true; 4662 } 4663 4664 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4665 int userId) { 4666 MessageDigest digest = null; 4667 try { 4668 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4669 } catch (NoSuchAlgorithmException e) { 4670 // If we can't create a digest, ignore ephemeral apps. 4671 return null; 4672 } 4673 4674 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4675 final byte[] digestBytes = digest.digest(hostBytes); 4676 int shaPrefix = 4677 digestBytes[0] << 24 4678 | digestBytes[1] << 16 4679 | digestBytes[2] << 8 4680 | digestBytes[3] << 0; 4681 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4682 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4683 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4684 // No hash prefix match; there are no ephemeral apps for this domain. 4685 return null; 4686 } 4687 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4688 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4689 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4690 continue; 4691 } 4692 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4693 // No filters; this should never happen. 4694 if (filters.isEmpty()) { 4695 continue; 4696 } 4697 // We have a domain match; resolve the filters to see if anything matches. 4698 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4699 for (int j = filters.size() - 1; j >= 0; --j) { 4700 final EphemeralResolveIntentInfo intentInfo = 4701 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4702 ephemeralResolver.addFilter(intentInfo); 4703 } 4704 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4705 intent, resolvedType, false /*defaultOnly*/, userId); 4706 if (!matchedResolveInfoList.isEmpty()) { 4707 return matchedResolveInfoList.get(0); 4708 } 4709 } 4710 // Hash or filter mis-match; no ephemeral apps for this domain. 4711 return null; 4712 } 4713 4714 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4715 int flags, List<ResolveInfo> query, int userId) { 4716 if (query != null) { 4717 final int N = query.size(); 4718 if (N == 1) { 4719 return query.get(0); 4720 } else if (N > 1) { 4721 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4722 // If there is more than one activity with the same priority, 4723 // then let the user decide between them. 4724 ResolveInfo r0 = query.get(0); 4725 ResolveInfo r1 = query.get(1); 4726 if (DEBUG_INTENT_MATCHING || debug) { 4727 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4728 + r1.activityInfo.name + "=" + r1.priority); 4729 } 4730 // If the first activity has a higher priority, or a different 4731 // default, then it is always desirable to pick it. 4732 if (r0.priority != r1.priority 4733 || r0.preferredOrder != r1.preferredOrder 4734 || r0.isDefault != r1.isDefault) { 4735 return query.get(0); 4736 } 4737 // If we have saved a preference for a preferred activity for 4738 // this Intent, use that. 4739 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4740 flags, query, r0.priority, true, false, debug, userId); 4741 if (ri != null) { 4742 return ri; 4743 } 4744 ri = new ResolveInfo(mResolveInfo); 4745 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4746 ri.activityInfo.applicationInfo = new ApplicationInfo( 4747 ri.activityInfo.applicationInfo); 4748 if (userId != 0) { 4749 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4750 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4751 } 4752 // Make sure that the resolver is displayable in car mode 4753 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4754 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4755 return ri; 4756 } 4757 } 4758 return null; 4759 } 4760 4761 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4762 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4763 final int N = query.size(); 4764 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4765 .get(userId); 4766 // Get the list of persistent preferred activities that handle the intent 4767 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4768 List<PersistentPreferredActivity> pprefs = ppir != null 4769 ? ppir.queryIntent(intent, resolvedType, 4770 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4771 : null; 4772 if (pprefs != null && pprefs.size() > 0) { 4773 final int M = pprefs.size(); 4774 for (int i=0; i<M; i++) { 4775 final PersistentPreferredActivity ppa = pprefs.get(i); 4776 if (DEBUG_PREFERRED || debug) { 4777 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4778 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4779 + "\n component=" + ppa.mComponent); 4780 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4781 } 4782 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4783 flags | MATCH_DISABLED_COMPONENTS, userId); 4784 if (DEBUG_PREFERRED || debug) { 4785 Slog.v(TAG, "Found persistent preferred activity:"); 4786 if (ai != null) { 4787 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4788 } else { 4789 Slog.v(TAG, " null"); 4790 } 4791 } 4792 if (ai == null) { 4793 // This previously registered persistent preferred activity 4794 // component is no longer known. Ignore it and do NOT remove it. 4795 continue; 4796 } 4797 for (int j=0; j<N; j++) { 4798 final ResolveInfo ri = query.get(j); 4799 if (!ri.activityInfo.applicationInfo.packageName 4800 .equals(ai.applicationInfo.packageName)) { 4801 continue; 4802 } 4803 if (!ri.activityInfo.name.equals(ai.name)) { 4804 continue; 4805 } 4806 // Found a persistent preference that can handle the intent. 4807 if (DEBUG_PREFERRED || debug) { 4808 Slog.v(TAG, "Returning persistent preferred activity: " + 4809 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4810 } 4811 return ri; 4812 } 4813 } 4814 } 4815 return null; 4816 } 4817 4818 // TODO: handle preferred activities missing while user has amnesia 4819 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4820 List<ResolveInfo> query, int priority, boolean always, 4821 boolean removeMatches, boolean debug, int userId) { 4822 if (!sUserManager.exists(userId)) return null; 4823 flags = updateFlagsForResolve(flags, userId, intent); 4824 // writer 4825 synchronized (mPackages) { 4826 if (intent.getSelector() != null) { 4827 intent = intent.getSelector(); 4828 } 4829 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4830 4831 // Try to find a matching persistent preferred activity. 4832 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4833 debug, userId); 4834 4835 // If a persistent preferred activity matched, use it. 4836 if (pri != null) { 4837 return pri; 4838 } 4839 4840 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4841 // Get the list of preferred activities that handle the intent 4842 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4843 List<PreferredActivity> prefs = pir != null 4844 ? pir.queryIntent(intent, resolvedType, 4845 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4846 : null; 4847 if (prefs != null && prefs.size() > 0) { 4848 boolean changed = false; 4849 try { 4850 // First figure out how good the original match set is. 4851 // We will only allow preferred activities that came 4852 // from the same match quality. 4853 int match = 0; 4854 4855 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4856 4857 final int N = query.size(); 4858 for (int j=0; j<N; j++) { 4859 final ResolveInfo ri = query.get(j); 4860 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4861 + ": 0x" + Integer.toHexString(match)); 4862 if (ri.match > match) { 4863 match = ri.match; 4864 } 4865 } 4866 4867 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4868 + Integer.toHexString(match)); 4869 4870 match &= IntentFilter.MATCH_CATEGORY_MASK; 4871 final int M = prefs.size(); 4872 for (int i=0; i<M; i++) { 4873 final PreferredActivity pa = prefs.get(i); 4874 if (DEBUG_PREFERRED || debug) { 4875 Slog.v(TAG, "Checking PreferredActivity ds=" 4876 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4877 + "\n component=" + pa.mPref.mComponent); 4878 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4879 } 4880 if (pa.mPref.mMatch != match) { 4881 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4882 + Integer.toHexString(pa.mPref.mMatch)); 4883 continue; 4884 } 4885 // If it's not an "always" type preferred activity and that's what we're 4886 // looking for, skip it. 4887 if (always && !pa.mPref.mAlways) { 4888 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4889 continue; 4890 } 4891 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4892 flags | MATCH_DISABLED_COMPONENTS, userId); 4893 if (DEBUG_PREFERRED || debug) { 4894 Slog.v(TAG, "Found preferred activity:"); 4895 if (ai != null) { 4896 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4897 } else { 4898 Slog.v(TAG, " null"); 4899 } 4900 } 4901 if (ai == null) { 4902 // This previously registered preferred activity 4903 // component is no longer known. Most likely an update 4904 // to the app was installed and in the new version this 4905 // component no longer exists. Clean it up by removing 4906 // it from the preferred activities list, and skip it. 4907 Slog.w(TAG, "Removing dangling preferred activity: " 4908 + pa.mPref.mComponent); 4909 pir.removeFilter(pa); 4910 changed = true; 4911 continue; 4912 } 4913 for (int j=0; j<N; j++) { 4914 final ResolveInfo ri = query.get(j); 4915 if (!ri.activityInfo.applicationInfo.packageName 4916 .equals(ai.applicationInfo.packageName)) { 4917 continue; 4918 } 4919 if (!ri.activityInfo.name.equals(ai.name)) { 4920 continue; 4921 } 4922 4923 if (removeMatches) { 4924 pir.removeFilter(pa); 4925 changed = true; 4926 if (DEBUG_PREFERRED) { 4927 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4928 } 4929 break; 4930 } 4931 4932 // Okay we found a previously set preferred or last chosen app. 4933 // If the result set is different from when this 4934 // was created, we need to clear it and re-ask the 4935 // user their preference, if we're looking for an "always" type entry. 4936 if (always && !pa.mPref.sameSet(query)) { 4937 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4938 + intent + " type " + resolvedType); 4939 if (DEBUG_PREFERRED) { 4940 Slog.v(TAG, "Removing preferred activity since set changed " 4941 + pa.mPref.mComponent); 4942 } 4943 pir.removeFilter(pa); 4944 // Re-add the filter as a "last chosen" entry (!always) 4945 PreferredActivity lastChosen = new PreferredActivity( 4946 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4947 pir.addFilter(lastChosen); 4948 changed = true; 4949 return null; 4950 } 4951 4952 // Yay! Either the set matched or we're looking for the last chosen 4953 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4954 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4955 return ri; 4956 } 4957 } 4958 } finally { 4959 if (changed) { 4960 if (DEBUG_PREFERRED) { 4961 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4962 } 4963 scheduleWritePackageRestrictionsLocked(userId); 4964 } 4965 } 4966 } 4967 } 4968 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4969 return null; 4970 } 4971 4972 /* 4973 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4974 */ 4975 @Override 4976 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4977 int targetUserId) { 4978 mContext.enforceCallingOrSelfPermission( 4979 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4980 List<CrossProfileIntentFilter> matches = 4981 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4982 if (matches != null) { 4983 int size = matches.size(); 4984 for (int i = 0; i < size; i++) { 4985 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4986 } 4987 } 4988 if (hasWebURI(intent)) { 4989 // cross-profile app linking works only towards the parent. 4990 final UserInfo parent = getProfileParent(sourceUserId); 4991 synchronized(mPackages) { 4992 int flags = updateFlagsForResolve(0, parent.id, intent); 4993 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4994 intent, resolvedType, flags, sourceUserId, parent.id); 4995 return xpDomainInfo != null; 4996 } 4997 } 4998 return false; 4999 } 5000 5001 private UserInfo getProfileParent(int userId) { 5002 final long identity = Binder.clearCallingIdentity(); 5003 try { 5004 return sUserManager.getProfileParent(userId); 5005 } finally { 5006 Binder.restoreCallingIdentity(identity); 5007 } 5008 } 5009 5010 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5011 String resolvedType, int userId) { 5012 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5013 if (resolver != null) { 5014 return resolver.queryIntent(intent, resolvedType, false, userId); 5015 } 5016 return null; 5017 } 5018 5019 @Override 5020 public List<ResolveInfo> queryIntentActivities(Intent intent, 5021 String resolvedType, int flags, int userId) { 5022 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5023 flags = updateFlagsForResolve(flags, userId, intent); 5024 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5025 false /* requireFullPermission */, false /* checkShell */, 5026 "query intent activities"); 5027 ComponentName comp = intent.getComponent(); 5028 if (comp == null) { 5029 if (intent.getSelector() != null) { 5030 intent = intent.getSelector(); 5031 comp = intent.getComponent(); 5032 } 5033 } 5034 5035 if (comp != null) { 5036 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5037 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5038 if (ai != null) { 5039 final ResolveInfo ri = new ResolveInfo(); 5040 ri.activityInfo = ai; 5041 list.add(ri); 5042 } 5043 return list; 5044 } 5045 5046 // reader 5047 synchronized (mPackages) { 5048 final String pkgName = intent.getPackage(); 5049 if (pkgName == null) { 5050 List<CrossProfileIntentFilter> matchingFilters = 5051 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5052 // Check for results that need to skip the current profile. 5053 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5054 resolvedType, flags, userId); 5055 if (xpResolveInfo != null) { 5056 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5057 result.add(xpResolveInfo); 5058 return filterIfNotSystemUser(result, userId); 5059 } 5060 5061 // Check for results in the current profile. 5062 List<ResolveInfo> result = mActivities.queryIntent( 5063 intent, resolvedType, flags, userId); 5064 result = filterIfNotSystemUser(result, userId); 5065 5066 // Check for cross profile results. 5067 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5068 xpResolveInfo = queryCrossProfileIntents( 5069 matchingFilters, intent, resolvedType, flags, userId, 5070 hasNonNegativePriorityResult); 5071 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5072 boolean isVisibleToUser = filterIfNotSystemUser( 5073 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5074 if (isVisibleToUser) { 5075 result.add(xpResolveInfo); 5076 Collections.sort(result, mResolvePrioritySorter); 5077 } 5078 } 5079 if (hasWebURI(intent)) { 5080 CrossProfileDomainInfo xpDomainInfo = null; 5081 final UserInfo parent = getProfileParent(userId); 5082 if (parent != null) { 5083 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5084 flags, userId, parent.id); 5085 } 5086 if (xpDomainInfo != null) { 5087 if (xpResolveInfo != null) { 5088 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5089 // in the result. 5090 result.remove(xpResolveInfo); 5091 } 5092 if (result.size() == 0) { 5093 result.add(xpDomainInfo.resolveInfo); 5094 return result; 5095 } 5096 } else if (result.size() <= 1) { 5097 return result; 5098 } 5099 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5100 xpDomainInfo, userId); 5101 Collections.sort(result, mResolvePrioritySorter); 5102 } 5103 return result; 5104 } 5105 final PackageParser.Package pkg = mPackages.get(pkgName); 5106 if (pkg != null) { 5107 return filterIfNotSystemUser( 5108 mActivities.queryIntentForPackage( 5109 intent, resolvedType, flags, pkg.activities, userId), 5110 userId); 5111 } 5112 return new ArrayList<ResolveInfo>(); 5113 } 5114 } 5115 5116 private static class CrossProfileDomainInfo { 5117 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5118 ResolveInfo resolveInfo; 5119 /* Best domain verification status of the activities found in the other profile */ 5120 int bestDomainVerificationStatus; 5121 } 5122 5123 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5124 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5125 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5126 sourceUserId)) { 5127 return null; 5128 } 5129 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5130 resolvedType, flags, parentUserId); 5131 5132 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5133 return null; 5134 } 5135 CrossProfileDomainInfo result = null; 5136 int size = resultTargetUser.size(); 5137 for (int i = 0; i < size; i++) { 5138 ResolveInfo riTargetUser = resultTargetUser.get(i); 5139 // Intent filter verification is only for filters that specify a host. So don't return 5140 // those that handle all web uris. 5141 if (riTargetUser.handleAllWebDataURI) { 5142 continue; 5143 } 5144 String packageName = riTargetUser.activityInfo.packageName; 5145 PackageSetting ps = mSettings.mPackages.get(packageName); 5146 if (ps == null) { 5147 continue; 5148 } 5149 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5150 int status = (int)(verificationState >> 32); 5151 if (result == null) { 5152 result = new CrossProfileDomainInfo(); 5153 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5154 sourceUserId, parentUserId); 5155 result.bestDomainVerificationStatus = status; 5156 } else { 5157 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5158 result.bestDomainVerificationStatus); 5159 } 5160 } 5161 // Don't consider matches with status NEVER across profiles. 5162 if (result != null && result.bestDomainVerificationStatus 5163 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5164 return null; 5165 } 5166 return result; 5167 } 5168 5169 /** 5170 * Verification statuses are ordered from the worse to the best, except for 5171 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5172 */ 5173 private int bestDomainVerificationStatus(int status1, int status2) { 5174 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5175 return status2; 5176 } 5177 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5178 return status1; 5179 } 5180 return (int) MathUtils.max(status1, status2); 5181 } 5182 5183 private boolean isUserEnabled(int userId) { 5184 long callingId = Binder.clearCallingIdentity(); 5185 try { 5186 UserInfo userInfo = sUserManager.getUserInfo(userId); 5187 return userInfo != null && userInfo.isEnabled(); 5188 } finally { 5189 Binder.restoreCallingIdentity(callingId); 5190 } 5191 } 5192 5193 /** 5194 * Filter out activities with systemUserOnly flag set, when current user is not System. 5195 * 5196 * @return filtered list 5197 */ 5198 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5199 if (userId == UserHandle.USER_SYSTEM) { 5200 return resolveInfos; 5201 } 5202 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5203 ResolveInfo info = resolveInfos.get(i); 5204 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5205 resolveInfos.remove(i); 5206 } 5207 } 5208 return resolveInfos; 5209 } 5210 5211 /** 5212 * @param resolveInfos list of resolve infos in descending priority order 5213 * @return if the list contains a resolve info with non-negative priority 5214 */ 5215 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5216 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5217 } 5218 5219 private static boolean hasWebURI(Intent intent) { 5220 if (intent.getData() == null) { 5221 return false; 5222 } 5223 final String scheme = intent.getScheme(); 5224 if (TextUtils.isEmpty(scheme)) { 5225 return false; 5226 } 5227 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5228 } 5229 5230 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5231 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5232 int userId) { 5233 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5234 5235 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5236 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5237 candidates.size()); 5238 } 5239 5240 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5241 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5242 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5243 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5244 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5245 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5246 5247 synchronized (mPackages) { 5248 final int count = candidates.size(); 5249 // First, try to use linked apps. Partition the candidates into four lists: 5250 // one for the final results, one for the "do not use ever", one for "undefined status" 5251 // and finally one for "browser app type". 5252 for (int n=0; n<count; n++) { 5253 ResolveInfo info = candidates.get(n); 5254 String packageName = info.activityInfo.packageName; 5255 PackageSetting ps = mSettings.mPackages.get(packageName); 5256 if (ps != null) { 5257 // Add to the special match all list (Browser use case) 5258 if (info.handleAllWebDataURI) { 5259 matchAllList.add(info); 5260 continue; 5261 } 5262 // Try to get the status from User settings first 5263 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5264 int status = (int)(packedStatus >> 32); 5265 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5266 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5267 if (DEBUG_DOMAIN_VERIFICATION) { 5268 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5269 + " : linkgen=" + linkGeneration); 5270 } 5271 // Use link-enabled generation as preferredOrder, i.e. 5272 // prefer newly-enabled over earlier-enabled. 5273 info.preferredOrder = linkGeneration; 5274 alwaysList.add(info); 5275 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5276 if (DEBUG_DOMAIN_VERIFICATION) { 5277 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5278 } 5279 neverList.add(info); 5280 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5281 if (DEBUG_DOMAIN_VERIFICATION) { 5282 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5283 } 5284 alwaysAskList.add(info); 5285 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5286 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5287 if (DEBUG_DOMAIN_VERIFICATION) { 5288 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5289 } 5290 undefinedList.add(info); 5291 } 5292 } 5293 } 5294 5295 // We'll want to include browser possibilities in a few cases 5296 boolean includeBrowser = false; 5297 5298 // First try to add the "always" resolution(s) for the current user, if any 5299 if (alwaysList.size() > 0) { 5300 result.addAll(alwaysList); 5301 } else { 5302 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5303 result.addAll(undefinedList); 5304 // Maybe add one for the other profile. 5305 if (xpDomainInfo != null && ( 5306 xpDomainInfo.bestDomainVerificationStatus 5307 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5308 result.add(xpDomainInfo.resolveInfo); 5309 } 5310 includeBrowser = true; 5311 } 5312 5313 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5314 // If there were 'always' entries their preferred order has been set, so we also 5315 // back that off to make the alternatives equivalent 5316 if (alwaysAskList.size() > 0) { 5317 for (ResolveInfo i : result) { 5318 i.preferredOrder = 0; 5319 } 5320 result.addAll(alwaysAskList); 5321 includeBrowser = true; 5322 } 5323 5324 if (includeBrowser) { 5325 // Also add browsers (all of them or only the default one) 5326 if (DEBUG_DOMAIN_VERIFICATION) { 5327 Slog.v(TAG, " ...including browsers in candidate set"); 5328 } 5329 if ((matchFlags & MATCH_ALL) != 0) { 5330 result.addAll(matchAllList); 5331 } else { 5332 // Browser/generic handling case. If there's a default browser, go straight 5333 // to that (but only if there is no other higher-priority match). 5334 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5335 int maxMatchPrio = 0; 5336 ResolveInfo defaultBrowserMatch = null; 5337 final int numCandidates = matchAllList.size(); 5338 for (int n = 0; n < numCandidates; n++) { 5339 ResolveInfo info = matchAllList.get(n); 5340 // track the highest overall match priority... 5341 if (info.priority > maxMatchPrio) { 5342 maxMatchPrio = info.priority; 5343 } 5344 // ...and the highest-priority default browser match 5345 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5346 if (defaultBrowserMatch == null 5347 || (defaultBrowserMatch.priority < info.priority)) { 5348 if (debug) { 5349 Slog.v(TAG, "Considering default browser match " + info); 5350 } 5351 defaultBrowserMatch = info; 5352 } 5353 } 5354 } 5355 if (defaultBrowserMatch != null 5356 && defaultBrowserMatch.priority >= maxMatchPrio 5357 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5358 { 5359 if (debug) { 5360 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5361 } 5362 result.add(defaultBrowserMatch); 5363 } else { 5364 result.addAll(matchAllList); 5365 } 5366 } 5367 5368 // If there is nothing selected, add all candidates and remove the ones that the user 5369 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5370 if (result.size() == 0) { 5371 result.addAll(candidates); 5372 result.removeAll(neverList); 5373 } 5374 } 5375 } 5376 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5377 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5378 result.size()); 5379 for (ResolveInfo info : result) { 5380 Slog.v(TAG, " + " + info.activityInfo); 5381 } 5382 } 5383 return result; 5384 } 5385 5386 // Returns a packed value as a long: 5387 // 5388 // high 'int'-sized word: link status: undefined/ask/never/always. 5389 // low 'int'-sized word: relative priority among 'always' results. 5390 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5391 long result = ps.getDomainVerificationStatusForUser(userId); 5392 // if none available, get the master status 5393 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5394 if (ps.getIntentFilterVerificationInfo() != null) { 5395 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5396 } 5397 } 5398 return result; 5399 } 5400 5401 private ResolveInfo querySkipCurrentProfileIntents( 5402 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5403 int flags, int sourceUserId) { 5404 if (matchingFilters != null) { 5405 int size = matchingFilters.size(); 5406 for (int i = 0; i < size; i ++) { 5407 CrossProfileIntentFilter filter = matchingFilters.get(i); 5408 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5409 // Checking if there are activities in the target user that can handle the 5410 // intent. 5411 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5412 resolvedType, flags, sourceUserId); 5413 if (resolveInfo != null) { 5414 return resolveInfo; 5415 } 5416 } 5417 } 5418 } 5419 return null; 5420 } 5421 5422 // Return matching ResolveInfo in target user if any. 5423 private ResolveInfo queryCrossProfileIntents( 5424 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5425 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5426 if (matchingFilters != null) { 5427 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5428 // match the same intent. For performance reasons, it is better not to 5429 // run queryIntent twice for the same userId 5430 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5431 int size = matchingFilters.size(); 5432 for (int i = 0; i < size; i++) { 5433 CrossProfileIntentFilter filter = matchingFilters.get(i); 5434 int targetUserId = filter.getTargetUserId(); 5435 boolean skipCurrentProfile = 5436 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5437 boolean skipCurrentProfileIfNoMatchFound = 5438 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5439 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5440 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5441 // Checking if there are activities in the target user that can handle the 5442 // intent. 5443 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5444 resolvedType, flags, sourceUserId); 5445 if (resolveInfo != null) return resolveInfo; 5446 alreadyTriedUserIds.put(targetUserId, true); 5447 } 5448 } 5449 } 5450 return null; 5451 } 5452 5453 /** 5454 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5455 * will forward the intent to the filter's target user. 5456 * Otherwise, returns null. 5457 */ 5458 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5459 String resolvedType, int flags, int sourceUserId) { 5460 int targetUserId = filter.getTargetUserId(); 5461 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5462 resolvedType, flags, targetUserId); 5463 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5464 // If all the matches in the target profile are suspended, return null. 5465 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5466 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5467 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5468 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5469 targetUserId); 5470 } 5471 } 5472 } 5473 return null; 5474 } 5475 5476 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5477 int sourceUserId, int targetUserId) { 5478 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5479 long ident = Binder.clearCallingIdentity(); 5480 boolean targetIsProfile; 5481 try { 5482 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5483 } finally { 5484 Binder.restoreCallingIdentity(ident); 5485 } 5486 String className; 5487 if (targetIsProfile) { 5488 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5489 } else { 5490 className = FORWARD_INTENT_TO_PARENT; 5491 } 5492 ComponentName forwardingActivityComponentName = new ComponentName( 5493 mAndroidApplication.packageName, className); 5494 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5495 sourceUserId); 5496 if (!targetIsProfile) { 5497 forwardingActivityInfo.showUserIcon = targetUserId; 5498 forwardingResolveInfo.noResourceId = true; 5499 } 5500 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5501 forwardingResolveInfo.priority = 0; 5502 forwardingResolveInfo.preferredOrder = 0; 5503 forwardingResolveInfo.match = 0; 5504 forwardingResolveInfo.isDefault = true; 5505 forwardingResolveInfo.filter = filter; 5506 forwardingResolveInfo.targetUserId = targetUserId; 5507 return forwardingResolveInfo; 5508 } 5509 5510 @Override 5511 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5512 Intent[] specifics, String[] specificTypes, Intent intent, 5513 String resolvedType, int flags, int userId) { 5514 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5515 flags = updateFlagsForResolve(flags, userId, intent); 5516 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5517 false /* requireFullPermission */, false /* checkShell */, 5518 "query intent activity options"); 5519 final String resultsAction = intent.getAction(); 5520 5521 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 5522 | PackageManager.GET_RESOLVED_FILTER, userId); 5523 5524 if (DEBUG_INTENT_MATCHING) { 5525 Log.v(TAG, "Query " + intent + ": " + results); 5526 } 5527 5528 int specificsPos = 0; 5529 int N; 5530 5531 // todo: note that the algorithm used here is O(N^2). This 5532 // isn't a problem in our current environment, but if we start running 5533 // into situations where we have more than 5 or 10 matches then this 5534 // should probably be changed to something smarter... 5535 5536 // First we go through and resolve each of the specific items 5537 // that were supplied, taking care of removing any corresponding 5538 // duplicate items in the generic resolve list. 5539 if (specifics != null) { 5540 for (int i=0; i<specifics.length; i++) { 5541 final Intent sintent = specifics[i]; 5542 if (sintent == null) { 5543 continue; 5544 } 5545 5546 if (DEBUG_INTENT_MATCHING) { 5547 Log.v(TAG, "Specific #" + i + ": " + sintent); 5548 } 5549 5550 String action = sintent.getAction(); 5551 if (resultsAction != null && resultsAction.equals(action)) { 5552 // If this action was explicitly requested, then don't 5553 // remove things that have it. 5554 action = null; 5555 } 5556 5557 ResolveInfo ri = null; 5558 ActivityInfo ai = null; 5559 5560 ComponentName comp = sintent.getComponent(); 5561 if (comp == null) { 5562 ri = resolveIntent( 5563 sintent, 5564 specificTypes != null ? specificTypes[i] : null, 5565 flags, userId); 5566 if (ri == null) { 5567 continue; 5568 } 5569 if (ri == mResolveInfo) { 5570 // ACK! Must do something better with this. 5571 } 5572 ai = ri.activityInfo; 5573 comp = new ComponentName(ai.applicationInfo.packageName, 5574 ai.name); 5575 } else { 5576 ai = getActivityInfo(comp, flags, userId); 5577 if (ai == null) { 5578 continue; 5579 } 5580 } 5581 5582 // Look for any generic query activities that are duplicates 5583 // of this specific one, and remove them from the results. 5584 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5585 N = results.size(); 5586 int j; 5587 for (j=specificsPos; j<N; j++) { 5588 ResolveInfo sri = results.get(j); 5589 if ((sri.activityInfo.name.equals(comp.getClassName()) 5590 && sri.activityInfo.applicationInfo.packageName.equals( 5591 comp.getPackageName())) 5592 || (action != null && sri.filter.matchAction(action))) { 5593 results.remove(j); 5594 if (DEBUG_INTENT_MATCHING) Log.v( 5595 TAG, "Removing duplicate item from " + j 5596 + " due to specific " + specificsPos); 5597 if (ri == null) { 5598 ri = sri; 5599 } 5600 j--; 5601 N--; 5602 } 5603 } 5604 5605 // Add this specific item to its proper place. 5606 if (ri == null) { 5607 ri = new ResolveInfo(); 5608 ri.activityInfo = ai; 5609 } 5610 results.add(specificsPos, ri); 5611 ri.specificIndex = i; 5612 specificsPos++; 5613 } 5614 } 5615 5616 // Now we go through the remaining generic results and remove any 5617 // duplicate actions that are found here. 5618 N = results.size(); 5619 for (int i=specificsPos; i<N-1; i++) { 5620 final ResolveInfo rii = results.get(i); 5621 if (rii.filter == null) { 5622 continue; 5623 } 5624 5625 // Iterate over all of the actions of this result's intent 5626 // filter... typically this should be just one. 5627 final Iterator<String> it = rii.filter.actionsIterator(); 5628 if (it == null) { 5629 continue; 5630 } 5631 while (it.hasNext()) { 5632 final String action = it.next(); 5633 if (resultsAction != null && resultsAction.equals(action)) { 5634 // If this action was explicitly requested, then don't 5635 // remove things that have it. 5636 continue; 5637 } 5638 for (int j=i+1; j<N; j++) { 5639 final ResolveInfo rij = results.get(j); 5640 if (rij.filter != null && rij.filter.hasAction(action)) { 5641 results.remove(j); 5642 if (DEBUG_INTENT_MATCHING) Log.v( 5643 TAG, "Removing duplicate item from " + j 5644 + " due to action " + action + " at " + i); 5645 j--; 5646 N--; 5647 } 5648 } 5649 } 5650 5651 // If the caller didn't request filter information, drop it now 5652 // so we don't have to marshall/unmarshall it. 5653 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5654 rii.filter = null; 5655 } 5656 } 5657 5658 // Filter out the caller activity if so requested. 5659 if (caller != null) { 5660 N = results.size(); 5661 for (int i=0; i<N; i++) { 5662 ActivityInfo ainfo = results.get(i).activityInfo; 5663 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5664 && caller.getClassName().equals(ainfo.name)) { 5665 results.remove(i); 5666 break; 5667 } 5668 } 5669 } 5670 5671 // If the caller didn't request filter information, 5672 // drop them now so we don't have to 5673 // marshall/unmarshall it. 5674 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5675 N = results.size(); 5676 for (int i=0; i<N; i++) { 5677 results.get(i).filter = null; 5678 } 5679 } 5680 5681 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5682 return results; 5683 } 5684 5685 @Override 5686 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5687 int userId) { 5688 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5689 flags = updateFlagsForResolve(flags, userId, intent); 5690 ComponentName comp = intent.getComponent(); 5691 if (comp == null) { 5692 if (intent.getSelector() != null) { 5693 intent = intent.getSelector(); 5694 comp = intent.getComponent(); 5695 } 5696 } 5697 if (comp != null) { 5698 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5699 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5700 if (ai != null) { 5701 ResolveInfo ri = new ResolveInfo(); 5702 ri.activityInfo = ai; 5703 list.add(ri); 5704 } 5705 return list; 5706 } 5707 5708 // reader 5709 synchronized (mPackages) { 5710 String pkgName = intent.getPackage(); 5711 if (pkgName == null) { 5712 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5713 } 5714 final PackageParser.Package pkg = mPackages.get(pkgName); 5715 if (pkg != null) { 5716 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5717 userId); 5718 } 5719 return null; 5720 } 5721 } 5722 5723 @Override 5724 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5725 if (!sUserManager.exists(userId)) return null; 5726 flags = updateFlagsForResolve(flags, userId, intent); 5727 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5728 if (query != null) { 5729 if (query.size() >= 1) { 5730 // If there is more than one service with the same priority, 5731 // just arbitrarily pick the first one. 5732 return query.get(0); 5733 } 5734 } 5735 return null; 5736 } 5737 5738 @Override 5739 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5740 int userId) { 5741 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5742 flags = updateFlagsForResolve(flags, userId, intent); 5743 ComponentName comp = intent.getComponent(); 5744 if (comp == null) { 5745 if (intent.getSelector() != null) { 5746 intent = intent.getSelector(); 5747 comp = intent.getComponent(); 5748 } 5749 } 5750 if (comp != null) { 5751 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5752 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5753 if (si != null) { 5754 final ResolveInfo ri = new ResolveInfo(); 5755 ri.serviceInfo = si; 5756 list.add(ri); 5757 } 5758 return list; 5759 } 5760 5761 // reader 5762 synchronized (mPackages) { 5763 String pkgName = intent.getPackage(); 5764 if (pkgName == null) { 5765 return mServices.queryIntent(intent, resolvedType, flags, userId); 5766 } 5767 final PackageParser.Package pkg = mPackages.get(pkgName); 5768 if (pkg != null) { 5769 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5770 userId); 5771 } 5772 return null; 5773 } 5774 } 5775 5776 @Override 5777 public List<ResolveInfo> queryIntentContentProviders( 5778 Intent intent, String resolvedType, int flags, int userId) { 5779 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5780 flags = updateFlagsForResolve(flags, userId, intent); 5781 ComponentName comp = intent.getComponent(); 5782 if (comp == null) { 5783 if (intent.getSelector() != null) { 5784 intent = intent.getSelector(); 5785 comp = intent.getComponent(); 5786 } 5787 } 5788 if (comp != null) { 5789 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5790 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5791 if (pi != null) { 5792 final ResolveInfo ri = new ResolveInfo(); 5793 ri.providerInfo = pi; 5794 list.add(ri); 5795 } 5796 return list; 5797 } 5798 5799 // reader 5800 synchronized (mPackages) { 5801 String pkgName = intent.getPackage(); 5802 if (pkgName == null) { 5803 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5804 } 5805 final PackageParser.Package pkg = mPackages.get(pkgName); 5806 if (pkg != null) { 5807 return mProviders.queryIntentForPackage( 5808 intent, resolvedType, flags, pkg.providers, userId); 5809 } 5810 return null; 5811 } 5812 } 5813 5814 @Override 5815 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5816 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5817 flags = updateFlagsForPackage(flags, userId, null); 5818 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5819 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5820 true /* requireFullPermission */, false /* checkShell */, 5821 "get installed packages"); 5822 5823 // writer 5824 synchronized (mPackages) { 5825 ArrayList<PackageInfo> list; 5826 if (listUninstalled) { 5827 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5828 for (PackageSetting ps : mSettings.mPackages.values()) { 5829 PackageInfo pi; 5830 if (ps.pkg != null) { 5831 pi = generatePackageInfo(ps.pkg, flags, userId); 5832 } else { 5833 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5834 } 5835 if (pi != null) { 5836 list.add(pi); 5837 } 5838 } 5839 } else { 5840 list = new ArrayList<PackageInfo>(mPackages.size()); 5841 for (PackageParser.Package p : mPackages.values()) { 5842 PackageInfo pi = generatePackageInfo(p, flags, userId); 5843 if (pi != null) { 5844 list.add(pi); 5845 } 5846 } 5847 } 5848 5849 return new ParceledListSlice<PackageInfo>(list); 5850 } 5851 } 5852 5853 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5854 String[] permissions, boolean[] tmp, int flags, int userId) { 5855 int numMatch = 0; 5856 final PermissionsState permissionsState = ps.getPermissionsState(); 5857 for (int i=0; i<permissions.length; i++) { 5858 final String permission = permissions[i]; 5859 if (permissionsState.hasPermission(permission, userId)) { 5860 tmp[i] = true; 5861 numMatch++; 5862 } else { 5863 tmp[i] = false; 5864 } 5865 } 5866 if (numMatch == 0) { 5867 return; 5868 } 5869 PackageInfo pi; 5870 if (ps.pkg != null) { 5871 pi = generatePackageInfo(ps.pkg, flags, userId); 5872 } else { 5873 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5874 } 5875 // The above might return null in cases of uninstalled apps or install-state 5876 // skew across users/profiles. 5877 if (pi != null) { 5878 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5879 if (numMatch == permissions.length) { 5880 pi.requestedPermissions = permissions; 5881 } else { 5882 pi.requestedPermissions = new String[numMatch]; 5883 numMatch = 0; 5884 for (int i=0; i<permissions.length; i++) { 5885 if (tmp[i]) { 5886 pi.requestedPermissions[numMatch] = permissions[i]; 5887 numMatch++; 5888 } 5889 } 5890 } 5891 } 5892 list.add(pi); 5893 } 5894 } 5895 5896 @Override 5897 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5898 String[] permissions, int flags, int userId) { 5899 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5900 flags = updateFlagsForPackage(flags, userId, permissions); 5901 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5902 5903 // writer 5904 synchronized (mPackages) { 5905 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5906 boolean[] tmpBools = new boolean[permissions.length]; 5907 if (listUninstalled) { 5908 for (PackageSetting ps : mSettings.mPackages.values()) { 5909 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5910 } 5911 } else { 5912 for (PackageParser.Package pkg : mPackages.values()) { 5913 PackageSetting ps = (PackageSetting)pkg.mExtras; 5914 if (ps != null) { 5915 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5916 userId); 5917 } 5918 } 5919 } 5920 5921 return new ParceledListSlice<PackageInfo>(list); 5922 } 5923 } 5924 5925 @Override 5926 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5927 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5928 flags = updateFlagsForApplication(flags, userId, null); 5929 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5930 5931 // writer 5932 synchronized (mPackages) { 5933 ArrayList<ApplicationInfo> list; 5934 if (listUninstalled) { 5935 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5936 for (PackageSetting ps : mSettings.mPackages.values()) { 5937 ApplicationInfo ai; 5938 if (ps.pkg != null) { 5939 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5940 ps.readUserState(userId), userId); 5941 } else { 5942 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5943 } 5944 if (ai != null) { 5945 list.add(ai); 5946 } 5947 } 5948 } else { 5949 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5950 for (PackageParser.Package p : mPackages.values()) { 5951 if (p.mExtras != null) { 5952 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5953 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5954 if (ai != null) { 5955 list.add(ai); 5956 } 5957 } 5958 } 5959 } 5960 5961 return new ParceledListSlice<ApplicationInfo>(list); 5962 } 5963 } 5964 5965 @Override 5966 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 5967 if (DISABLE_EPHEMERAL_APPS) { 5968 return null; 5969 } 5970 5971 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 5972 "getEphemeralApplications"); 5973 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5974 true /* requireFullPermission */, false /* checkShell */, 5975 "getEphemeralApplications"); 5976 synchronized (mPackages) { 5977 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 5978 .getEphemeralApplicationsLPw(userId); 5979 if (ephemeralApps != null) { 5980 return new ParceledListSlice<>(ephemeralApps); 5981 } 5982 } 5983 return null; 5984 } 5985 5986 @Override 5987 public boolean isEphemeralApplication(String packageName, int userId) { 5988 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5989 true /* requireFullPermission */, false /* checkShell */, 5990 "isEphemeral"); 5991 if (DISABLE_EPHEMERAL_APPS) { 5992 return false; 5993 } 5994 5995 if (!isCallerSameApp(packageName)) { 5996 return false; 5997 } 5998 synchronized (mPackages) { 5999 PackageParser.Package pkg = mPackages.get(packageName); 6000 if (pkg != null) { 6001 return pkg.applicationInfo.isEphemeralApp(); 6002 } 6003 } 6004 return false; 6005 } 6006 6007 @Override 6008 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6009 if (DISABLE_EPHEMERAL_APPS) { 6010 return null; 6011 } 6012 6013 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6014 true /* requireFullPermission */, false /* checkShell */, 6015 "getCookie"); 6016 if (!isCallerSameApp(packageName)) { 6017 return null; 6018 } 6019 synchronized (mPackages) { 6020 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6021 packageName, userId); 6022 } 6023 } 6024 6025 @Override 6026 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6027 if (DISABLE_EPHEMERAL_APPS) { 6028 return true; 6029 } 6030 6031 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6032 true /* requireFullPermission */, true /* checkShell */, 6033 "setCookie"); 6034 if (!isCallerSameApp(packageName)) { 6035 return false; 6036 } 6037 synchronized (mPackages) { 6038 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6039 packageName, cookie, userId); 6040 } 6041 } 6042 6043 @Override 6044 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6045 if (DISABLE_EPHEMERAL_APPS) { 6046 return null; 6047 } 6048 6049 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6050 "getEphemeralApplicationIcon"); 6051 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6052 true /* requireFullPermission */, false /* checkShell */, 6053 "getEphemeralApplicationIcon"); 6054 synchronized (mPackages) { 6055 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6056 packageName, userId); 6057 } 6058 } 6059 6060 private boolean isCallerSameApp(String packageName) { 6061 PackageParser.Package pkg = mPackages.get(packageName); 6062 return pkg != null 6063 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6064 } 6065 6066 public List<ApplicationInfo> getPersistentApplications(int flags) { 6067 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6068 6069 // reader 6070 synchronized (mPackages) { 6071 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6072 final int userId = UserHandle.getCallingUserId(); 6073 while (i.hasNext()) { 6074 final PackageParser.Package p = i.next(); 6075 if (p.applicationInfo != null 6076 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 6077 && (!mSafeMode || isSystemApp(p))) { 6078 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6079 if (ps != null) { 6080 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6081 ps.readUserState(userId), userId); 6082 if (ai != null) { 6083 finalList.add(ai); 6084 } 6085 } 6086 } 6087 } 6088 } 6089 6090 return finalList; 6091 } 6092 6093 @Override 6094 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6095 if (!sUserManager.exists(userId)) return null; 6096 flags = updateFlagsForComponent(flags, userId, name); 6097 // reader 6098 synchronized (mPackages) { 6099 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6100 PackageSetting ps = provider != null 6101 ? mSettings.mPackages.get(provider.owner.packageName) 6102 : null; 6103 return ps != null 6104 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6105 ? PackageParser.generateProviderInfo(provider, flags, 6106 ps.readUserState(userId), userId) 6107 : null; 6108 } 6109 } 6110 6111 /** 6112 * @deprecated 6113 */ 6114 @Deprecated 6115 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6116 // reader 6117 synchronized (mPackages) { 6118 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6119 .entrySet().iterator(); 6120 final int userId = UserHandle.getCallingUserId(); 6121 while (i.hasNext()) { 6122 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6123 PackageParser.Provider p = entry.getValue(); 6124 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6125 6126 if (ps != null && p.syncable 6127 && (!mSafeMode || (p.info.applicationInfo.flags 6128 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6129 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6130 ps.readUserState(userId), userId); 6131 if (info != null) { 6132 outNames.add(entry.getKey()); 6133 outInfo.add(info); 6134 } 6135 } 6136 } 6137 } 6138 } 6139 6140 @Override 6141 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6142 int uid, int flags) { 6143 final int userId = processName != null ? UserHandle.getUserId(uid) 6144 : UserHandle.getCallingUserId(); 6145 if (!sUserManager.exists(userId)) return null; 6146 flags = updateFlagsForComponent(flags, userId, processName); 6147 6148 ArrayList<ProviderInfo> finalList = null; 6149 // reader 6150 synchronized (mPackages) { 6151 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6152 while (i.hasNext()) { 6153 final PackageParser.Provider p = i.next(); 6154 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6155 if (ps != null && p.info.authority != null 6156 && (processName == null 6157 || (p.info.processName.equals(processName) 6158 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6159 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6160 if (finalList == null) { 6161 finalList = new ArrayList<ProviderInfo>(3); 6162 } 6163 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6164 ps.readUserState(userId), userId); 6165 if (info != null) { 6166 finalList.add(info); 6167 } 6168 } 6169 } 6170 } 6171 6172 if (finalList != null) { 6173 Collections.sort(finalList, mProviderInitOrderSorter); 6174 return new ParceledListSlice<ProviderInfo>(finalList); 6175 } 6176 6177 return null; 6178 } 6179 6180 @Override 6181 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6182 // reader 6183 synchronized (mPackages) { 6184 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6185 return PackageParser.generateInstrumentationInfo(i, flags); 6186 } 6187 } 6188 6189 @Override 6190 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 6191 int flags) { 6192 ArrayList<InstrumentationInfo> finalList = 6193 new ArrayList<InstrumentationInfo>(); 6194 6195 // reader 6196 synchronized (mPackages) { 6197 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6198 while (i.hasNext()) { 6199 final PackageParser.Instrumentation p = i.next(); 6200 if (targetPackage == null 6201 || targetPackage.equals(p.info.targetPackage)) { 6202 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6203 flags); 6204 if (ii != null) { 6205 finalList.add(ii); 6206 } 6207 } 6208 } 6209 } 6210 6211 return finalList; 6212 } 6213 6214 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6215 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6216 if (overlays == null) { 6217 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6218 return; 6219 } 6220 for (PackageParser.Package opkg : overlays.values()) { 6221 // Not much to do if idmap fails: we already logged the error 6222 // and we certainly don't want to abort installation of pkg simply 6223 // because an overlay didn't fit properly. For these reasons, 6224 // ignore the return value of createIdmapForPackagePairLI. 6225 createIdmapForPackagePairLI(pkg, opkg); 6226 } 6227 } 6228 6229 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6230 PackageParser.Package opkg) { 6231 if (!opkg.mTrustedOverlay) { 6232 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6233 opkg.baseCodePath + ": overlay not trusted"); 6234 return false; 6235 } 6236 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6237 if (overlaySet == null) { 6238 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6239 opkg.baseCodePath + " but target package has no known overlays"); 6240 return false; 6241 } 6242 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6243 // TODO: generate idmap for split APKs 6244 try { 6245 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6246 } catch (InstallerException e) { 6247 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6248 + opkg.baseCodePath); 6249 return false; 6250 } 6251 PackageParser.Package[] overlayArray = 6252 overlaySet.values().toArray(new PackageParser.Package[0]); 6253 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6254 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6255 return p1.mOverlayPriority - p2.mOverlayPriority; 6256 } 6257 }; 6258 Arrays.sort(overlayArray, cmp); 6259 6260 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6261 int i = 0; 6262 for (PackageParser.Package p : overlayArray) { 6263 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6264 } 6265 return true; 6266 } 6267 6268 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6269 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6270 try { 6271 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6272 } finally { 6273 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6274 } 6275 } 6276 6277 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6278 final File[] files = dir.listFiles(); 6279 if (ArrayUtils.isEmpty(files)) { 6280 Log.d(TAG, "No files in app dir " + dir); 6281 return; 6282 } 6283 6284 if (DEBUG_PACKAGE_SCANNING) { 6285 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6286 + " flags=0x" + Integer.toHexString(parseFlags)); 6287 } 6288 6289 for (File file : files) { 6290 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6291 && !PackageInstallerService.isStageName(file.getName()); 6292 if (!isPackage) { 6293 // Ignore entries which are not packages 6294 continue; 6295 } 6296 try { 6297 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6298 scanFlags, currentTime, null); 6299 } catch (PackageManagerException e) { 6300 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6301 6302 // Delete invalid userdata apps 6303 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6304 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6305 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6306 removeCodePathLI(file); 6307 } 6308 } 6309 } 6310 } 6311 6312 private static File getSettingsProblemFile() { 6313 File dataDir = Environment.getDataDirectory(); 6314 File systemDir = new File(dataDir, "system"); 6315 File fname = new File(systemDir, "uiderrors.txt"); 6316 return fname; 6317 } 6318 6319 static void reportSettingsProblem(int priority, String msg) { 6320 logCriticalInfo(priority, msg); 6321 } 6322 6323 static void logCriticalInfo(int priority, String msg) { 6324 Slog.println(priority, TAG, msg); 6325 EventLogTags.writePmCriticalInfo(msg); 6326 try { 6327 File fname = getSettingsProblemFile(); 6328 FileOutputStream out = new FileOutputStream(fname, true); 6329 PrintWriter pw = new FastPrintWriter(out); 6330 SimpleDateFormat formatter = new SimpleDateFormat(); 6331 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6332 pw.println(dateString + ": " + msg); 6333 pw.close(); 6334 FileUtils.setPermissions( 6335 fname.toString(), 6336 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6337 -1, -1); 6338 } catch (java.io.IOException e) { 6339 } 6340 } 6341 6342 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6343 int parseFlags) throws PackageManagerException { 6344 if (ps != null 6345 && ps.codePath.equals(srcFile) 6346 && ps.timeStamp == srcFile.lastModified() 6347 && !isCompatSignatureUpdateNeeded(pkg) 6348 && !isRecoverSignatureUpdateNeeded(pkg)) { 6349 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6350 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6351 ArraySet<PublicKey> signingKs; 6352 synchronized (mPackages) { 6353 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6354 } 6355 if (ps.signatures.mSignatures != null 6356 && ps.signatures.mSignatures.length != 0 6357 && signingKs != null) { 6358 // Optimization: reuse the existing cached certificates 6359 // if the package appears to be unchanged. 6360 pkg.mSignatures = ps.signatures.mSignatures; 6361 pkg.mSigningKeys = signingKs; 6362 return; 6363 } 6364 6365 Slog.w(TAG, "PackageSetting for " + ps.name 6366 + " is missing signatures. Collecting certs again to recover them."); 6367 } else { 6368 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6369 } 6370 6371 try { 6372 PackageParser.collectCertificates(pkg, parseFlags); 6373 } catch (PackageParserException e) { 6374 throw PackageManagerException.from(e); 6375 } 6376 } 6377 6378 /** 6379 * Traces a package scan. 6380 * @see #scanPackageLI(File, int, int, long, UserHandle) 6381 */ 6382 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6383 long currentTime, UserHandle user) throws PackageManagerException { 6384 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6385 try { 6386 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6387 } finally { 6388 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6389 } 6390 } 6391 6392 /** 6393 * Scans a package and returns the newly parsed package. 6394 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6395 */ 6396 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6397 long currentTime, UserHandle user) throws PackageManagerException { 6398 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6399 parseFlags |= mDefParseFlags; 6400 PackageParser pp = new PackageParser(); 6401 pp.setSeparateProcesses(mSeparateProcesses); 6402 pp.setOnlyCoreApps(mOnlyCore); 6403 pp.setDisplayMetrics(mMetrics); 6404 6405 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6406 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6407 } 6408 6409 final PackageParser.Package pkg; 6410 try { 6411 pkg = pp.parsePackage(scanFile, parseFlags); 6412 } catch (PackageParserException e) { 6413 throw PackageManagerException.from(e); 6414 } 6415 6416 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6417 } 6418 6419 /** 6420 * Scans a package and returns the newly parsed package. 6421 * @throws PackageManagerException on a parse error. 6422 */ 6423 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6424 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6425 throws PackageManagerException { 6426 // If the package has children and this is the first dive in the function 6427 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6428 // packages (parent and children) would be successfully scanned before the 6429 // actual scan since scanning mutates internal state and we want to atomically 6430 // install the package and its children. 6431 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6432 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6433 scanFlags |= SCAN_CHECK_ONLY; 6434 } 6435 } else { 6436 scanFlags &= ~SCAN_CHECK_ONLY; 6437 } 6438 6439 // Scan the parent 6440 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags, 6441 scanFlags, currentTime, user); 6442 6443 // Scan the children 6444 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6445 for (int i = 0; i < childCount; i++) { 6446 PackageParser.Package childPackage = pkg.childPackages.get(i); 6447 scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags, 6448 currentTime, user); 6449 } 6450 6451 6452 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6453 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6454 } 6455 6456 return scannedPkg; 6457 } 6458 6459 /** 6460 * Scans a package and returns the newly parsed package. 6461 * @throws PackageManagerException on a parse error. 6462 */ 6463 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6464 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6465 throws PackageManagerException { 6466 PackageSetting ps = null; 6467 PackageSetting updatedPkg; 6468 // reader 6469 synchronized (mPackages) { 6470 // Look to see if we already know about this package. 6471 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6472 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6473 // This package has been renamed to its original name. Let's 6474 // use that. 6475 ps = mSettings.peekPackageLPr(oldName); 6476 } 6477 // If there was no original package, see one for the real package name. 6478 if (ps == null) { 6479 ps = mSettings.peekPackageLPr(pkg.packageName); 6480 } 6481 // Check to see if this package could be hiding/updating a system 6482 // package. Must look for it either under the original or real 6483 // package name depending on our state. 6484 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6485 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6486 6487 // If this is a package we don't know about on the system partition, we 6488 // may need to remove disabled child packages on the system partition 6489 // or may need to not add child packages if the parent apk is updated 6490 // on the data partition and no longer defines this child package. 6491 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6492 // If this is a parent package for an updated system app and this system 6493 // app got an OTA update which no longer defines some of the child packages 6494 // we have to prune them from the disabled system packages. 6495 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6496 if (disabledPs != null) { 6497 final int scannedChildCount = (pkg.childPackages != null) 6498 ? pkg.childPackages.size() : 0; 6499 final int disabledChildCount = disabledPs.childPackageNames != null 6500 ? disabledPs.childPackageNames.size() : 0; 6501 for (int i = 0; i < disabledChildCount; i++) { 6502 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6503 boolean disabledPackageAvailable = false; 6504 for (int j = 0; j < scannedChildCount; j++) { 6505 PackageParser.Package childPkg = pkg.childPackages.get(j); 6506 if (childPkg.packageName.equals(disabledChildPackageName)) { 6507 disabledPackageAvailable = true; 6508 break; 6509 } 6510 } 6511 if (!disabledPackageAvailable) { 6512 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6513 } 6514 } 6515 } 6516 } 6517 } 6518 6519 boolean updatedPkgBetter = false; 6520 // First check if this is a system package that may involve an update 6521 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6522 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6523 // it needs to drop FLAG_PRIVILEGED. 6524 if (locationIsPrivileged(scanFile)) { 6525 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6526 } else { 6527 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6528 } 6529 6530 if (ps != null && !ps.codePath.equals(scanFile)) { 6531 // The path has changed from what was last scanned... check the 6532 // version of the new path against what we have stored to determine 6533 // what to do. 6534 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6535 if (pkg.mVersionCode <= ps.versionCode) { 6536 // The system package has been updated and the code path does not match 6537 // Ignore entry. Skip it. 6538 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6539 + " ignored: updated version " + ps.versionCode 6540 + " better than this " + pkg.mVersionCode); 6541 if (!updatedPkg.codePath.equals(scanFile)) { 6542 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6543 + ps.name + " changing from " + updatedPkg.codePathString 6544 + " to " + scanFile); 6545 updatedPkg.codePath = scanFile; 6546 updatedPkg.codePathString = scanFile.toString(); 6547 updatedPkg.resourcePath = scanFile; 6548 updatedPkg.resourcePathString = scanFile.toString(); 6549 } 6550 updatedPkg.pkg = pkg; 6551 updatedPkg.versionCode = pkg.mVersionCode; 6552 6553 // Update the disabled system child packages to point to the package too. 6554 final int childCount = updatedPkg.childPackageNames != null 6555 ? updatedPkg.childPackageNames.size() : 0; 6556 for (int i = 0; i < childCount; i++) { 6557 String childPackageName = updatedPkg.childPackageNames.get(i); 6558 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6559 childPackageName); 6560 if (updatedChildPkg != null) { 6561 updatedChildPkg.pkg = pkg; 6562 updatedChildPkg.versionCode = pkg.mVersionCode; 6563 } 6564 } 6565 6566 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6567 + scanFile + " ignored: updated version " + ps.versionCode 6568 + " better than this " + pkg.mVersionCode); 6569 } else { 6570 // The current app on the system partition is better than 6571 // what we have updated to on the data partition; switch 6572 // back to the system partition version. 6573 // At this point, its safely assumed that package installation for 6574 // apps in system partition will go through. If not there won't be a working 6575 // version of the app 6576 // writer 6577 synchronized (mPackages) { 6578 // Just remove the loaded entries from package lists. 6579 mPackages.remove(ps.name); 6580 } 6581 6582 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6583 + " reverting from " + ps.codePathString 6584 + ": new version " + pkg.mVersionCode 6585 + " better than installed " + ps.versionCode); 6586 6587 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6588 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6589 synchronized (mInstallLock) { 6590 args.cleanUpResourcesLI(); 6591 } 6592 synchronized (mPackages) { 6593 mSettings.enableSystemPackageLPw(ps.name); 6594 } 6595 updatedPkgBetter = true; 6596 } 6597 } 6598 } 6599 6600 if (updatedPkg != null) { 6601 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6602 // initially 6603 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6604 6605 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6606 // flag set initially 6607 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6608 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6609 } 6610 } 6611 6612 // Verify certificates against what was last scanned 6613 collectCertificatesLI(ps, pkg, scanFile, parseFlags); 6614 6615 /* 6616 * A new system app appeared, but we already had a non-system one of the 6617 * same name installed earlier. 6618 */ 6619 boolean shouldHideSystemApp = false; 6620 if (updatedPkg == null && ps != null 6621 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6622 /* 6623 * Check to make sure the signatures match first. If they don't, 6624 * wipe the installed application and its data. 6625 */ 6626 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6627 != PackageManager.SIGNATURE_MATCH) { 6628 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6629 + " signatures don't match existing userdata copy; removing"); 6630 deletePackageLI(pkg.packageName, null, true, null, 0, null, false, null); 6631 ps = null; 6632 } else { 6633 /* 6634 * If the newly-added system app is an older version than the 6635 * already installed version, hide it. It will be scanned later 6636 * and re-added like an update. 6637 */ 6638 if (pkg.mVersionCode <= ps.versionCode) { 6639 shouldHideSystemApp = true; 6640 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6641 + " but new version " + pkg.mVersionCode + " better than installed " 6642 + ps.versionCode + "; hiding system"); 6643 } else { 6644 /* 6645 * The newly found system app is a newer version that the 6646 * one previously installed. Simply remove the 6647 * already-installed application and replace it with our own 6648 * while keeping the application data. 6649 */ 6650 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6651 + " reverting from " + ps.codePathString + ": new version " 6652 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6653 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6654 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6655 synchronized (mInstallLock) { 6656 args.cleanUpResourcesLI(); 6657 } 6658 } 6659 } 6660 } 6661 6662 // The apk is forward locked (not public) if its code and resources 6663 // are kept in different files. (except for app in either system or 6664 // vendor path). 6665 // TODO grab this value from PackageSettings 6666 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6667 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6668 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6669 } 6670 } 6671 6672 // TODO: extend to support forward-locked splits 6673 String resourcePath = null; 6674 String baseResourcePath = null; 6675 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6676 if (ps != null && ps.resourcePathString != null) { 6677 resourcePath = ps.resourcePathString; 6678 baseResourcePath = ps.resourcePathString; 6679 } else { 6680 // Should not happen at all. Just log an error. 6681 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6682 } 6683 } else { 6684 resourcePath = pkg.codePath; 6685 baseResourcePath = pkg.baseCodePath; 6686 } 6687 6688 // Set application objects path explicitly. 6689 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 6690 pkg.setApplicationInfoCodePath(pkg.codePath); 6691 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 6692 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 6693 pkg.setApplicationInfoResourcePath(resourcePath); 6694 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 6695 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 6696 6697 // Note that we invoke the following method only if we are about to unpack an application 6698 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6699 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6700 6701 /* 6702 * If the system app should be overridden by a previously installed 6703 * data, hide the system app now and let the /data/app scan pick it up 6704 * again. 6705 */ 6706 if (shouldHideSystemApp) { 6707 synchronized (mPackages) { 6708 mSettings.disableSystemPackageLPw(pkg.packageName, true); 6709 } 6710 } 6711 6712 return scannedPkg; 6713 } 6714 6715 private static String fixProcessName(String defProcessName, 6716 String processName, int uid) { 6717 if (processName == null) { 6718 return defProcessName; 6719 } 6720 return processName; 6721 } 6722 6723 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6724 throws PackageManagerException { 6725 if (pkgSetting.signatures.mSignatures != null) { 6726 // Already existing package. Make sure signatures match 6727 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6728 == PackageManager.SIGNATURE_MATCH; 6729 if (!match) { 6730 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6731 == PackageManager.SIGNATURE_MATCH; 6732 } 6733 if (!match) { 6734 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6735 == PackageManager.SIGNATURE_MATCH; 6736 } 6737 if (!match) { 6738 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6739 + pkg.packageName + " signatures do not match the " 6740 + "previously installed version; ignoring!"); 6741 } 6742 } 6743 6744 // Check for shared user signatures 6745 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6746 // Already existing package. Make sure signatures match 6747 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6748 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6749 if (!match) { 6750 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6751 == PackageManager.SIGNATURE_MATCH; 6752 } 6753 if (!match) { 6754 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6755 == PackageManager.SIGNATURE_MATCH; 6756 } 6757 if (!match) { 6758 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6759 "Package " + pkg.packageName 6760 + " has no signatures that match those in shared user " 6761 + pkgSetting.sharedUser.name + "; ignoring!"); 6762 } 6763 } 6764 } 6765 6766 /** 6767 * Enforces that only the system UID or root's UID can call a method exposed 6768 * via Binder. 6769 * 6770 * @param message used as message if SecurityException is thrown 6771 * @throws SecurityException if the caller is not system or root 6772 */ 6773 private static final void enforceSystemOrRoot(String message) { 6774 final int uid = Binder.getCallingUid(); 6775 if (uid != Process.SYSTEM_UID && uid != 0) { 6776 throw new SecurityException(message); 6777 } 6778 } 6779 6780 @Override 6781 public void performFstrimIfNeeded() { 6782 enforceSystemOrRoot("Only the system can request fstrim"); 6783 6784 // Before everything else, see whether we need to fstrim. 6785 try { 6786 IMountService ms = PackageHelper.getMountService(); 6787 if (ms != null) { 6788 final boolean isUpgrade = isUpgrade(); 6789 boolean doTrim = isUpgrade; 6790 if (doTrim) { 6791 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6792 } else { 6793 final long interval = android.provider.Settings.Global.getLong( 6794 mContext.getContentResolver(), 6795 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6796 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6797 if (interval > 0) { 6798 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6799 if (timeSinceLast > interval) { 6800 doTrim = true; 6801 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6802 + "; running immediately"); 6803 } 6804 } 6805 } 6806 if (doTrim) { 6807 if (!isFirstBoot()) { 6808 try { 6809 ActivityManagerNative.getDefault().showBootMessage( 6810 mContext.getResources().getString( 6811 R.string.android_upgrading_fstrim), true); 6812 } catch (RemoteException e) { 6813 } 6814 } 6815 ms.runMaintenance(); 6816 } 6817 } else { 6818 Slog.e(TAG, "Mount service unavailable!"); 6819 } 6820 } catch (RemoteException e) { 6821 // Can't happen; MountService is local 6822 } 6823 } 6824 6825 @Override 6826 public void extractPackagesIfNeeded() { 6827 enforceSystemOrRoot("Only the system can request package extraction"); 6828 6829 // Extract pacakges only if profile-guided compilation is enabled because 6830 // otherwise BackgroundDexOptService will not dexopt them later. 6831 if (!mUseJitProfiles || !isUpgrade()) { 6832 return; 6833 } 6834 6835 List<PackageParser.Package> pkgs; 6836 synchronized (mPackages) { 6837 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 6838 } 6839 6840 int curr = 0; 6841 int total = pkgs.size(); 6842 for (PackageParser.Package pkg : pkgs) { 6843 curr++; 6844 6845 if (DEBUG_DEXOPT) { 6846 Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName); 6847 } 6848 6849 if (!isFirstBoot()) { 6850 try { 6851 ActivityManagerNative.getDefault().showBootMessage( 6852 mContext.getResources().getString(R.string.android_upgrading_apk, 6853 curr, total), true); 6854 } catch (RemoteException e) { 6855 } 6856 } 6857 6858 if (PackageDexOptimizer.canOptimizePackage(pkg)) { 6859 performDexOpt(pkg.packageName, null /* instructionSet */, 6860 false /* useProfiles */, true /* extractOnly */, false /* force */); 6861 } 6862 } 6863 } 6864 6865 @Override 6866 public void notifyPackageUse(String packageName) { 6867 synchronized (mPackages) { 6868 PackageParser.Package p = mPackages.get(packageName); 6869 if (p == null) { 6870 return; 6871 } 6872 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6873 } 6874 } 6875 6876 // TODO: this is not used nor needed. Delete it. 6877 @Override 6878 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6879 return performDexOptTraced(packageName, instructionSet, false /* useProfiles */, 6880 false /* extractOnly */, false /* force */); 6881 } 6882 6883 @Override 6884 public boolean performDexOpt(String packageName, String instructionSet, boolean useProfiles, 6885 boolean extractOnly, boolean force) { 6886 return performDexOptTraced(packageName, instructionSet, useProfiles, extractOnly, force); 6887 } 6888 6889 private boolean performDexOptTraced(String packageName, String instructionSet, 6890 boolean useProfiles, boolean extractOnly, boolean force) { 6891 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6892 try { 6893 return performDexOptInternal(packageName, instructionSet, useProfiles, extractOnly, 6894 force); 6895 } finally { 6896 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6897 } 6898 } 6899 6900 private boolean performDexOptInternal(String packageName, String instructionSet, 6901 boolean useProfiles, boolean extractOnly, boolean force) { 6902 PackageParser.Package p; 6903 final String targetInstructionSet; 6904 synchronized (mPackages) { 6905 p = mPackages.get(packageName); 6906 if (p == null) { 6907 return false; 6908 } 6909 mPackageUsage.write(false); 6910 6911 targetInstructionSet = instructionSet != null ? instructionSet : 6912 getPrimaryInstructionSet(p.applicationInfo); 6913 if (!force && !useProfiles && p.mDexOptPerformed.contains(targetInstructionSet)) { 6914 // Skip only if we do not use profiles since they might trigger a recompilation. 6915 return false; 6916 } 6917 } 6918 long callingId = Binder.clearCallingIdentity(); 6919 try { 6920 synchronized (mInstallLock) { 6921 final String[] instructionSets = new String[] { targetInstructionSet }; 6922 int result = performDexOptInternalWithDependenciesLI(p, instructionSets, 6923 useProfiles, extractOnly, force); 6924 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6925 } 6926 } finally { 6927 Binder.restoreCallingIdentity(callingId); 6928 } 6929 } 6930 6931 public ArraySet<String> getOptimizablePackages() { 6932 ArraySet<String> pkgs = new ArraySet<String>(); 6933 synchronized (mPackages) { 6934 for (PackageParser.Package p : mPackages.values()) { 6935 if (PackageDexOptimizer.canOptimizePackage(p)) { 6936 pkgs.add(p.packageName); 6937 } 6938 } 6939 } 6940 return pkgs; 6941 } 6942 6943 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 6944 String instructionSets[], boolean useProfiles, boolean extractOnly, boolean force) { 6945 // Select the dex optimizer based on the force parameter. 6946 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 6947 // allocate an object here. 6948 PackageDexOptimizer pdo = force 6949 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 6950 : mPackageDexOptimizer; 6951 6952 // Optimize all dependencies first. Note: we ignore the return value and march on 6953 // on errors. 6954 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 6955 if (!deps.isEmpty()) { 6956 for (PackageParser.Package depPackage : deps) { 6957 // TODO: Analyze and investigate if we (should) profile libraries. 6958 // Currently this will do a full compilation of the library. 6959 pdo.performDexOpt(depPackage, instructionSets, false /* useProfiles */, 6960 false /* extractOnly */); 6961 } 6962 } 6963 6964 return pdo.performDexOpt(p, instructionSets, useProfiles, extractOnly); 6965 } 6966 6967 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 6968 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 6969 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 6970 Set<String> collectedNames = new HashSet<>(); 6971 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 6972 6973 retValue.remove(p); 6974 6975 return retValue; 6976 } else { 6977 return Collections.emptyList(); 6978 } 6979 } 6980 6981 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 6982 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 6983 if (!collectedNames.contains(p.packageName)) { 6984 collectedNames.add(p.packageName); 6985 collected.add(p); 6986 6987 if (p.usesLibraries != null) { 6988 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 6989 } 6990 if (p.usesOptionalLibraries != null) { 6991 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 6992 collectedNames); 6993 } 6994 } 6995 } 6996 6997 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 6998 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 6999 for (String libName : libs) { 7000 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7001 if (libPkg != null) { 7002 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7003 } 7004 } 7005 } 7006 7007 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7008 synchronized (mPackages) { 7009 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7010 if (lib != null && lib.apk != null) { 7011 return mPackages.get(lib.apk); 7012 } 7013 } 7014 return null; 7015 } 7016 7017 public void shutdown() { 7018 mPackageUsage.write(true); 7019 } 7020 7021 @Override 7022 public void forceDexOpt(String packageName) { 7023 enforceSystemOrRoot("forceDexOpt"); 7024 7025 PackageParser.Package pkg; 7026 synchronized (mPackages) { 7027 pkg = mPackages.get(packageName); 7028 if (pkg == null) { 7029 throw new IllegalArgumentException("Unknown package: " + packageName); 7030 } 7031 } 7032 7033 synchronized (mInstallLock) { 7034 final String[] instructionSets = new String[] { 7035 getPrimaryInstructionSet(pkg.applicationInfo) }; 7036 7037 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7038 7039 // Whoever is calling forceDexOpt wants a fully compiled package. 7040 // Don't use profiles since that may cause compilation to be skipped. 7041 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7042 false /* useProfiles */, false /* extractOnly */, true /* force */); 7043 7044 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7045 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7046 throw new IllegalStateException("Failed to dexopt: " + res); 7047 } 7048 } 7049 } 7050 7051 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7052 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7053 Slog.w(TAG, "Unable to update from " + oldPkg.name 7054 + " to " + newPkg.packageName 7055 + ": old package not in system partition"); 7056 return false; 7057 } else if (mPackages.get(oldPkg.name) != null) { 7058 Slog.w(TAG, "Unable to update from " + oldPkg.name 7059 + " to " + newPkg.packageName 7060 + ": old package still exists"); 7061 return false; 7062 } 7063 return true; 7064 } 7065 7066 private boolean removeDataDirsLI(String volumeUuid, String packageName) { 7067 // TODO: triage flags as part of 26466827 7068 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7069 7070 boolean res = true; 7071 final int[] users = sUserManager.getUserIds(); 7072 for (int user : users) { 7073 try { 7074 mInstaller.destroyAppData(volumeUuid, packageName, user, flags); 7075 } catch (InstallerException e) { 7076 Slog.w(TAG, "Failed to delete data directory", e); 7077 res = false; 7078 } 7079 } 7080 return res; 7081 } 7082 7083 void removeCodePathLI(File codePath) { 7084 if (codePath.isDirectory()) { 7085 try { 7086 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7087 } catch (InstallerException e) { 7088 Slog.w(TAG, "Failed to remove code path", e); 7089 } 7090 } else { 7091 codePath.delete(); 7092 } 7093 } 7094 7095 void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) { 7096 try { 7097 mInstaller.destroyAppData(volumeUuid, packageName, userId, flags); 7098 } catch (InstallerException e) { 7099 Slog.w(TAG, "Failed to destroy app data", e); 7100 } 7101 } 7102 7103 void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags, 7104 int appId, String seinfo) { 7105 try { 7106 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo); 7107 } catch (InstallerException e) { 7108 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 7109 } 7110 } 7111 7112 private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 7113 final PackageParser.Package pkg; 7114 synchronized (mPackages) { 7115 pkg = mPackages.get(packageName); 7116 } 7117 if (pkg == null) { 7118 Slog.w(TAG, "Failed to delete code cache directory. No package: " + packageName); 7119 return; 7120 } 7121 deleteCodeCacheDirsLI(pkg); 7122 } 7123 7124 private void deleteCodeCacheDirsLI(PackageParser.Package pkg) { 7125 // TODO: triage flags as part of 26466827 7126 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7127 7128 int[] users = sUserManager.getUserIds(); 7129 int res = 0; 7130 for (int user : users) { 7131 // Remove the parent code cache 7132 try { 7133 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, user, 7134 flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7135 } catch (InstallerException e) { 7136 Slog.w(TAG, "Failed to delete code cache directory", e); 7137 } 7138 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7139 for (int i = 0; i < childCount; i++) { 7140 PackageParser.Package childPkg = pkg.childPackages.get(i); 7141 // Remove the child code cache 7142 try { 7143 mInstaller.clearAppData(childPkg.volumeUuid, childPkg.packageName, 7144 user, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7145 } catch (InstallerException e) { 7146 Slog.w(TAG, "Failed to delete code cache directory", e); 7147 } 7148 } 7149 } 7150 } 7151 7152 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7153 long lastUpdateTime) { 7154 // Set parent install/update time 7155 PackageSetting ps = (PackageSetting) pkg.mExtras; 7156 if (ps != null) { 7157 ps.firstInstallTime = firstInstallTime; 7158 ps.lastUpdateTime = lastUpdateTime; 7159 } 7160 // Set children install/update time 7161 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7162 for (int i = 0; i < childCount; i++) { 7163 PackageParser.Package childPkg = pkg.childPackages.get(i); 7164 ps = (PackageSetting) childPkg.mExtras; 7165 if (ps != null) { 7166 ps.firstInstallTime = firstInstallTime; 7167 ps.lastUpdateTime = lastUpdateTime; 7168 } 7169 } 7170 } 7171 7172 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7173 PackageParser.Package changingLib) { 7174 if (file.path != null) { 7175 usesLibraryFiles.add(file.path); 7176 return; 7177 } 7178 PackageParser.Package p = mPackages.get(file.apk); 7179 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7180 // If we are doing this while in the middle of updating a library apk, 7181 // then we need to make sure to use that new apk for determining the 7182 // dependencies here. (We haven't yet finished committing the new apk 7183 // to the package manager state.) 7184 if (p == null || p.packageName.equals(changingLib.packageName)) { 7185 p = changingLib; 7186 } 7187 } 7188 if (p != null) { 7189 usesLibraryFiles.addAll(p.getAllCodePaths()); 7190 } 7191 } 7192 7193 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7194 PackageParser.Package changingLib) throws PackageManagerException { 7195 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7196 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7197 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7198 for (int i=0; i<N; i++) { 7199 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7200 if (file == null) { 7201 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7202 "Package " + pkg.packageName + " requires unavailable shared library " 7203 + pkg.usesLibraries.get(i) + "; failing!"); 7204 } 7205 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7206 } 7207 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7208 for (int i=0; i<N; i++) { 7209 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7210 if (file == null) { 7211 Slog.w(TAG, "Package " + pkg.packageName 7212 + " desires unavailable shared library " 7213 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7214 } else { 7215 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7216 } 7217 } 7218 N = usesLibraryFiles.size(); 7219 if (N > 0) { 7220 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7221 } else { 7222 pkg.usesLibraryFiles = null; 7223 } 7224 } 7225 } 7226 7227 private static boolean hasString(List<String> list, List<String> which) { 7228 if (list == null) { 7229 return false; 7230 } 7231 for (int i=list.size()-1; i>=0; i--) { 7232 for (int j=which.size()-1; j>=0; j--) { 7233 if (which.get(j).equals(list.get(i))) { 7234 return true; 7235 } 7236 } 7237 } 7238 return false; 7239 } 7240 7241 private void updateAllSharedLibrariesLPw() { 7242 for (PackageParser.Package pkg : mPackages.values()) { 7243 try { 7244 updateSharedLibrariesLPw(pkg, null); 7245 } catch (PackageManagerException e) { 7246 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7247 } 7248 } 7249 } 7250 7251 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7252 PackageParser.Package changingPkg) { 7253 ArrayList<PackageParser.Package> res = null; 7254 for (PackageParser.Package pkg : mPackages.values()) { 7255 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7256 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7257 if (res == null) { 7258 res = new ArrayList<PackageParser.Package>(); 7259 } 7260 res.add(pkg); 7261 try { 7262 updateSharedLibrariesLPw(pkg, changingPkg); 7263 } catch (PackageManagerException e) { 7264 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7265 } 7266 } 7267 } 7268 return res; 7269 } 7270 7271 /** 7272 * Derive the value of the {@code cpuAbiOverride} based on the provided 7273 * value and an optional stored value from the package settings. 7274 */ 7275 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7276 String cpuAbiOverride = null; 7277 7278 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7279 cpuAbiOverride = null; 7280 } else if (abiOverride != null) { 7281 cpuAbiOverride = abiOverride; 7282 } else if (settings != null) { 7283 cpuAbiOverride = settings.cpuAbiOverrideString; 7284 } 7285 7286 return cpuAbiOverride; 7287 } 7288 7289 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 7290 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7291 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7292 // If the package has children and this is the first dive in the function 7293 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7294 // whether all packages (parent and children) would be successfully scanned 7295 // before the actual scan since scanning mutates internal state and we want 7296 // to atomically install the package and its children. 7297 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7298 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7299 scanFlags |= SCAN_CHECK_ONLY; 7300 } 7301 } else { 7302 scanFlags &= ~SCAN_CHECK_ONLY; 7303 } 7304 7305 final PackageParser.Package scannedPkg; 7306 try { 7307 // Scan the parent 7308 scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 7309 // Scan the children 7310 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7311 for (int i = 0; i < childCount; i++) { 7312 PackageParser.Package childPkg = pkg.childPackages.get(i); 7313 scanPackageLI(childPkg, parseFlags, 7314 scanFlags, currentTime, user); 7315 } 7316 } finally { 7317 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7318 } 7319 7320 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7321 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 7322 } 7323 7324 return scannedPkg; 7325 } 7326 7327 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 7328 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7329 boolean success = false; 7330 try { 7331 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 7332 currentTime, user); 7333 success = true; 7334 return res; 7335 } finally { 7336 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7337 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 7338 } 7339 } 7340 } 7341 7342 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 7343 int scanFlags, long currentTime, UserHandle user) 7344 throws PackageManagerException { 7345 final File scanFile = new File(pkg.codePath); 7346 if (pkg.applicationInfo.getCodePath() == null || 7347 pkg.applicationInfo.getResourcePath() == null) { 7348 // Bail out. The resource and code paths haven't been set. 7349 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7350 "Code and resource paths haven't been set correctly"); 7351 } 7352 7353 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7354 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7355 } else { 7356 // Only allow system apps to be flagged as core apps. 7357 pkg.coreApp = false; 7358 } 7359 7360 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7361 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7362 } 7363 7364 if (mCustomResolverComponentName != null && 7365 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7366 setUpCustomResolverActivity(pkg); 7367 } 7368 7369 if (pkg.packageName.equals("android")) { 7370 synchronized (mPackages) { 7371 if (mAndroidApplication != null) { 7372 Slog.w(TAG, "*************************************************"); 7373 Slog.w(TAG, "Core android package being redefined. Skipping."); 7374 Slog.w(TAG, " file=" + scanFile); 7375 Slog.w(TAG, "*************************************************"); 7376 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7377 "Core android package being redefined. Skipping."); 7378 } 7379 7380 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7381 // Set up information for our fall-back user intent resolution activity. 7382 mPlatformPackage = pkg; 7383 pkg.mVersionCode = mSdkVersion; 7384 mAndroidApplication = pkg.applicationInfo; 7385 7386 if (!mResolverReplaced) { 7387 mResolveActivity.applicationInfo = mAndroidApplication; 7388 mResolveActivity.name = ResolverActivity.class.getName(); 7389 mResolveActivity.packageName = mAndroidApplication.packageName; 7390 mResolveActivity.processName = "system:ui"; 7391 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7392 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7393 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7394 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7395 mResolveActivity.exported = true; 7396 mResolveActivity.enabled = true; 7397 mResolveInfo.activityInfo = mResolveActivity; 7398 mResolveInfo.priority = 0; 7399 mResolveInfo.preferredOrder = 0; 7400 mResolveInfo.match = 0; 7401 mResolveComponentName = new ComponentName( 7402 mAndroidApplication.packageName, mResolveActivity.name); 7403 } 7404 } 7405 } 7406 } 7407 7408 if (DEBUG_PACKAGE_SCANNING) { 7409 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7410 Log.d(TAG, "Scanning package " + pkg.packageName); 7411 } 7412 7413 synchronized (mPackages) { 7414 if (mPackages.containsKey(pkg.packageName) 7415 || mSharedLibraries.containsKey(pkg.packageName)) { 7416 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7417 "Application package " + pkg.packageName 7418 + " already installed. Skipping duplicate."); 7419 } 7420 7421 // If we're only installing presumed-existing packages, require that the 7422 // scanned APK is both already known and at the path previously established 7423 // for it. Previously unknown packages we pick up normally, but if we have an 7424 // a priori expectation about this package's install presence, enforce it. 7425 // With a singular exception for new system packages. When an OTA contains 7426 // a new system package, we allow the codepath to change from a system location 7427 // to the user-installed location. If we don't allow this change, any newer, 7428 // user-installed version of the application will be ignored. 7429 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7430 if (mExpectingBetter.containsKey(pkg.packageName)) { 7431 logCriticalInfo(Log.WARN, 7432 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7433 } else { 7434 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7435 if (known != null) { 7436 if (DEBUG_PACKAGE_SCANNING) { 7437 Log.d(TAG, "Examining " + pkg.codePath 7438 + " and requiring known paths " + known.codePathString 7439 + " & " + known.resourcePathString); 7440 } 7441 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7442 || !pkg.applicationInfo.getResourcePath().equals( 7443 known.resourcePathString)) { 7444 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7445 "Application package " + pkg.packageName 7446 + " found at " + pkg.applicationInfo.getCodePath() 7447 + " but expected at " + known.codePathString 7448 + "; ignoring."); 7449 } 7450 } 7451 } 7452 } 7453 } 7454 7455 // Initialize package source and resource directories 7456 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7457 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7458 7459 SharedUserSetting suid = null; 7460 PackageSetting pkgSetting = null; 7461 7462 if (!isSystemApp(pkg)) { 7463 // Only system apps can use these features. 7464 pkg.mOriginalPackages = null; 7465 pkg.mRealPackage = null; 7466 pkg.mAdoptPermissions = null; 7467 } 7468 7469 // Getting the package setting may have a side-effect, so if we 7470 // are only checking if scan would succeed, stash a copy of the 7471 // old setting to restore at the end. 7472 PackageSetting nonMutatedPs = null; 7473 7474 // writer 7475 synchronized (mPackages) { 7476 if (pkg.mSharedUserId != null) { 7477 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7478 if (suid == null) { 7479 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7480 "Creating application package " + pkg.packageName 7481 + " for shared user failed"); 7482 } 7483 if (DEBUG_PACKAGE_SCANNING) { 7484 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7485 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7486 + "): packages=" + suid.packages); 7487 } 7488 } 7489 7490 // Check if we are renaming from an original package name. 7491 PackageSetting origPackage = null; 7492 String realName = null; 7493 if (pkg.mOriginalPackages != null) { 7494 // This package may need to be renamed to a previously 7495 // installed name. Let's check on that... 7496 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7497 if (pkg.mOriginalPackages.contains(renamed)) { 7498 // This package had originally been installed as the 7499 // original name, and we have already taken care of 7500 // transitioning to the new one. Just update the new 7501 // one to continue using the old name. 7502 realName = pkg.mRealPackage; 7503 if (!pkg.packageName.equals(renamed)) { 7504 // Callers into this function may have already taken 7505 // care of renaming the package; only do it here if 7506 // it is not already done. 7507 pkg.setPackageName(renamed); 7508 } 7509 7510 } else { 7511 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7512 if ((origPackage = mSettings.peekPackageLPr( 7513 pkg.mOriginalPackages.get(i))) != null) { 7514 // We do have the package already installed under its 7515 // original name... should we use it? 7516 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7517 // New package is not compatible with original. 7518 origPackage = null; 7519 continue; 7520 } else if (origPackage.sharedUser != null) { 7521 // Make sure uid is compatible between packages. 7522 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7523 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7524 + " to " + pkg.packageName + ": old uid " 7525 + origPackage.sharedUser.name 7526 + " differs from " + pkg.mSharedUserId); 7527 origPackage = null; 7528 continue; 7529 } 7530 } else { 7531 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7532 + pkg.packageName + " to old name " + origPackage.name); 7533 } 7534 break; 7535 } 7536 } 7537 } 7538 } 7539 7540 if (mTransferedPackages.contains(pkg.packageName)) { 7541 Slog.w(TAG, "Package " + pkg.packageName 7542 + " was transferred to another, but its .apk remains"); 7543 } 7544 7545 // See comments in nonMutatedPs declaration 7546 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7547 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 7548 if (foundPs != null) { 7549 nonMutatedPs = new PackageSetting(foundPs); 7550 } 7551 } 7552 7553 // Just create the setting, don't add it yet. For already existing packages 7554 // the PkgSetting exists already and doesn't have to be created. 7555 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7556 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7557 pkg.applicationInfo.primaryCpuAbi, 7558 pkg.applicationInfo.secondaryCpuAbi, 7559 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7560 user, false); 7561 if (pkgSetting == null) { 7562 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7563 "Creating application package " + pkg.packageName + " failed"); 7564 } 7565 7566 if (pkgSetting.origPackage != null) { 7567 // If we are first transitioning from an original package, 7568 // fix up the new package's name now. We need to do this after 7569 // looking up the package under its new name, so getPackageLP 7570 // can take care of fiddling things correctly. 7571 pkg.setPackageName(origPackage.name); 7572 7573 // File a report about this. 7574 String msg = "New package " + pkgSetting.realName 7575 + " renamed to replace old package " + pkgSetting.name; 7576 reportSettingsProblem(Log.WARN, msg); 7577 7578 // Make a note of it. 7579 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7580 mTransferedPackages.add(origPackage.name); 7581 } 7582 7583 // No longer need to retain this. 7584 pkgSetting.origPackage = null; 7585 } 7586 7587 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 7588 // Make a note of it. 7589 mTransferedPackages.add(pkg.packageName); 7590 } 7591 7592 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7593 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7594 } 7595 7596 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7597 // Check all shared libraries and map to their actual file path. 7598 // We only do this here for apps not on a system dir, because those 7599 // are the only ones that can fail an install due to this. We 7600 // will take care of the system apps by updating all of their 7601 // library paths after the scan is done. 7602 updateSharedLibrariesLPw(pkg, null); 7603 } 7604 7605 if (mFoundPolicyFile) { 7606 SELinuxMMAC.assignSeinfoValue(pkg); 7607 } 7608 7609 pkg.applicationInfo.uid = pkgSetting.appId; 7610 pkg.mExtras = pkgSetting; 7611 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7612 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7613 // We just determined the app is signed correctly, so bring 7614 // over the latest parsed certs. 7615 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7616 } else { 7617 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7618 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7619 "Package " + pkg.packageName + " upgrade keys do not match the " 7620 + "previously installed version"); 7621 } else { 7622 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7623 String msg = "System package " + pkg.packageName 7624 + " signature changed; retaining data."; 7625 reportSettingsProblem(Log.WARN, msg); 7626 } 7627 } 7628 } else { 7629 try { 7630 verifySignaturesLP(pkgSetting, pkg); 7631 // We just determined the app is signed correctly, so bring 7632 // over the latest parsed certs. 7633 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7634 } catch (PackageManagerException e) { 7635 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7636 throw e; 7637 } 7638 // The signature has changed, but this package is in the system 7639 // image... let's recover! 7640 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7641 // However... if this package is part of a shared user, but it 7642 // doesn't match the signature of the shared user, let's fail. 7643 // What this means is that you can't change the signatures 7644 // associated with an overall shared user, which doesn't seem all 7645 // that unreasonable. 7646 if (pkgSetting.sharedUser != null) { 7647 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7648 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7649 throw new PackageManagerException( 7650 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7651 "Signature mismatch for shared user: " 7652 + pkgSetting.sharedUser); 7653 } 7654 } 7655 // File a report about this. 7656 String msg = "System package " + pkg.packageName 7657 + " signature changed; retaining data."; 7658 reportSettingsProblem(Log.WARN, msg); 7659 } 7660 } 7661 // Verify that this new package doesn't have any content providers 7662 // that conflict with existing packages. Only do this if the 7663 // package isn't already installed, since we don't want to break 7664 // things that are installed. 7665 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7666 final int N = pkg.providers.size(); 7667 int i; 7668 for (i=0; i<N; i++) { 7669 PackageParser.Provider p = pkg.providers.get(i); 7670 if (p.info.authority != null) { 7671 String names[] = p.info.authority.split(";"); 7672 for (int j = 0; j < names.length; j++) { 7673 if (mProvidersByAuthority.containsKey(names[j])) { 7674 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7675 final String otherPackageName = 7676 ((other != null && other.getComponentName() != null) ? 7677 other.getComponentName().getPackageName() : "?"); 7678 throw new PackageManagerException( 7679 INSTALL_FAILED_CONFLICTING_PROVIDER, 7680 "Can't install because provider name " + names[j] 7681 + " (in package " + pkg.applicationInfo.packageName 7682 + ") is already used by " + otherPackageName); 7683 } 7684 } 7685 } 7686 } 7687 } 7688 7689 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 7690 // This package wants to adopt ownership of permissions from 7691 // another package. 7692 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7693 final String origName = pkg.mAdoptPermissions.get(i); 7694 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7695 if (orig != null) { 7696 if (verifyPackageUpdateLPr(orig, pkg)) { 7697 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7698 + pkg.packageName); 7699 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7700 } 7701 } 7702 } 7703 } 7704 } 7705 7706 final String pkgName = pkg.packageName; 7707 7708 final long scanFileTime = scanFile.lastModified(); 7709 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7710 pkg.applicationInfo.processName = fixProcessName( 7711 pkg.applicationInfo.packageName, 7712 pkg.applicationInfo.processName, 7713 pkg.applicationInfo.uid); 7714 7715 if (pkg != mPlatformPackage) { 7716 // Get all of our default paths setup 7717 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7718 } 7719 7720 final String path = scanFile.getPath(); 7721 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7722 7723 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7724 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7725 7726 // Some system apps still use directory structure for native libraries 7727 // in which case we might end up not detecting abi solely based on apk 7728 // structure. Try to detect abi based on directory structure. 7729 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7730 pkg.applicationInfo.primaryCpuAbi == null) { 7731 setBundledAppAbisAndRoots(pkg, pkgSetting); 7732 setNativeLibraryPaths(pkg); 7733 } 7734 7735 } else { 7736 if ((scanFlags & SCAN_MOVE) != 0) { 7737 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7738 // but we already have this packages package info in the PackageSetting. We just 7739 // use that and derive the native library path based on the new codepath. 7740 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7741 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7742 } 7743 7744 // Set native library paths again. For moves, the path will be updated based on the 7745 // ABIs we've determined above. For non-moves, the path will be updated based on the 7746 // ABIs we determined during compilation, but the path will depend on the final 7747 // package path (after the rename away from the stage path). 7748 setNativeLibraryPaths(pkg); 7749 } 7750 7751 // This is a special case for the "system" package, where the ABI is 7752 // dictated by the zygote configuration (and init.rc). We should keep track 7753 // of this ABI so that we can deal with "normal" applications that run under 7754 // the same UID correctly. 7755 if (mPlatformPackage == pkg) { 7756 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7757 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7758 } 7759 7760 // If there's a mismatch between the abi-override in the package setting 7761 // and the abiOverride specified for the install. Warn about this because we 7762 // would've already compiled the app without taking the package setting into 7763 // account. 7764 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7765 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7766 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7767 " for package " + pkg.packageName); 7768 } 7769 } 7770 7771 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7772 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7773 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7774 7775 // Copy the derived override back to the parsed package, so that we can 7776 // update the package settings accordingly. 7777 pkg.cpuAbiOverride = cpuAbiOverride; 7778 7779 if (DEBUG_ABI_SELECTION) { 7780 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7781 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7782 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7783 } 7784 7785 // Push the derived path down into PackageSettings so we know what to 7786 // clean up at uninstall time. 7787 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7788 7789 if (DEBUG_ABI_SELECTION) { 7790 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7791 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7792 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7793 } 7794 7795 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7796 // We don't do this here during boot because we can do it all 7797 // at once after scanning all existing packages. 7798 // 7799 // We also do this *before* we perform dexopt on this package, so that 7800 // we can avoid redundant dexopts, and also to make sure we've got the 7801 // code and package path correct. 7802 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7803 pkg, true /* boot complete */); 7804 } 7805 7806 if (mFactoryTest && pkg.requestedPermissions.contains( 7807 android.Manifest.permission.FACTORY_TEST)) { 7808 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7809 } 7810 7811 ArrayList<PackageParser.Package> clientLibPkgs = null; 7812 7813 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7814 if (nonMutatedPs != null) { 7815 synchronized (mPackages) { 7816 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 7817 } 7818 } 7819 return pkg; 7820 } 7821 7822 // Only privileged apps and updated privileged apps can add child packages. 7823 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 7824 if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) { 7825 throw new PackageManagerException("Only privileged apps and updated " 7826 + "privileged apps can add child packages. Ignoring package " 7827 + pkg.packageName); 7828 } 7829 final int childCount = pkg.childPackages.size(); 7830 for (int i = 0; i < childCount; i++) { 7831 PackageParser.Package childPkg = pkg.childPackages.get(i); 7832 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 7833 childPkg.packageName)) { 7834 throw new PackageManagerException("Cannot override a child package of " 7835 + "another disabled system app. Ignoring package " + pkg.packageName); 7836 } 7837 } 7838 } 7839 7840 // writer 7841 synchronized (mPackages) { 7842 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7843 // Only system apps can add new shared libraries. 7844 if (pkg.libraryNames != null) { 7845 for (int i=0; i<pkg.libraryNames.size(); i++) { 7846 String name = pkg.libraryNames.get(i); 7847 boolean allowed = false; 7848 if (pkg.isUpdatedSystemApp()) { 7849 // New library entries can only be added through the 7850 // system image. This is important to get rid of a lot 7851 // of nasty edge cases: for example if we allowed a non- 7852 // system update of the app to add a library, then uninstalling 7853 // the update would make the library go away, and assumptions 7854 // we made such as through app install filtering would now 7855 // have allowed apps on the device which aren't compatible 7856 // with it. Better to just have the restriction here, be 7857 // conservative, and create many fewer cases that can negatively 7858 // impact the user experience. 7859 final PackageSetting sysPs = mSettings 7860 .getDisabledSystemPkgLPr(pkg.packageName); 7861 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7862 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7863 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7864 allowed = true; 7865 break; 7866 } 7867 } 7868 } 7869 } else { 7870 allowed = true; 7871 } 7872 if (allowed) { 7873 if (!mSharedLibraries.containsKey(name)) { 7874 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7875 } else if (!name.equals(pkg.packageName)) { 7876 Slog.w(TAG, "Package " + pkg.packageName + " library " 7877 + name + " already exists; skipping"); 7878 } 7879 } else { 7880 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7881 + name + " that is not declared on system image; skipping"); 7882 } 7883 } 7884 if ((scanFlags & SCAN_BOOTING) == 0) { 7885 // If we are not booting, we need to update any applications 7886 // that are clients of our shared library. If we are booting, 7887 // this will all be done once the scan is complete. 7888 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7889 } 7890 } 7891 } 7892 } 7893 7894 // Request the ActivityManager to kill the process(only for existing packages) 7895 // so that we do not end up in a confused state while the user is still using the older 7896 // version of the application while the new one gets installed. 7897 if ((scanFlags & SCAN_REPLACING) != 0) { 7898 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7899 7900 killApplication(pkg.applicationInfo.packageName, 7901 pkg.applicationInfo.uid, "replace pkg"); 7902 7903 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7904 } 7905 7906 // Also need to kill any apps that are dependent on the library. 7907 if (clientLibPkgs != null) { 7908 for (int i=0; i<clientLibPkgs.size(); i++) { 7909 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7910 killApplication(clientPkg.applicationInfo.packageName, 7911 clientPkg.applicationInfo.uid, "update lib"); 7912 } 7913 } 7914 7915 // Make sure we're not adding any bogus keyset info 7916 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7917 ksms.assertScannedPackageValid(pkg); 7918 7919 // writer 7920 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7921 7922 boolean createIdmapFailed = false; 7923 synchronized (mPackages) { 7924 // We don't expect installation to fail beyond this point 7925 7926 // Add the new setting to mSettings 7927 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7928 // Add the new setting to mPackages 7929 mPackages.put(pkg.applicationInfo.packageName, pkg); 7930 // Make sure we don't accidentally delete its data. 7931 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7932 while (iter.hasNext()) { 7933 PackageCleanItem item = iter.next(); 7934 if (pkgName.equals(item.packageName)) { 7935 iter.remove(); 7936 } 7937 } 7938 7939 // Take care of first install / last update times. 7940 if (currentTime != 0) { 7941 if (pkgSetting.firstInstallTime == 0) { 7942 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7943 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7944 pkgSetting.lastUpdateTime = currentTime; 7945 } 7946 } else if (pkgSetting.firstInstallTime == 0) { 7947 // We need *something*. Take time time stamp of the file. 7948 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7949 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7950 if (scanFileTime != pkgSetting.timeStamp) { 7951 // A package on the system image has changed; consider this 7952 // to be an update. 7953 pkgSetting.lastUpdateTime = scanFileTime; 7954 } 7955 } 7956 7957 // Add the package's KeySets to the global KeySetManagerService 7958 ksms.addScannedPackageLPw(pkg); 7959 7960 int N = pkg.providers.size(); 7961 StringBuilder r = null; 7962 int i; 7963 for (i=0; i<N; i++) { 7964 PackageParser.Provider p = pkg.providers.get(i); 7965 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7966 p.info.processName, pkg.applicationInfo.uid); 7967 mProviders.addProvider(p); 7968 p.syncable = p.info.isSyncable; 7969 if (p.info.authority != null) { 7970 String names[] = p.info.authority.split(";"); 7971 p.info.authority = null; 7972 for (int j = 0; j < names.length; j++) { 7973 if (j == 1 && p.syncable) { 7974 // We only want the first authority for a provider to possibly be 7975 // syncable, so if we already added this provider using a different 7976 // authority clear the syncable flag. We copy the provider before 7977 // changing it because the mProviders object contains a reference 7978 // to a provider that we don't want to change. 7979 // Only do this for the second authority since the resulting provider 7980 // object can be the same for all future authorities for this provider. 7981 p = new PackageParser.Provider(p); 7982 p.syncable = false; 7983 } 7984 if (!mProvidersByAuthority.containsKey(names[j])) { 7985 mProvidersByAuthority.put(names[j], p); 7986 if (p.info.authority == null) { 7987 p.info.authority = names[j]; 7988 } else { 7989 p.info.authority = p.info.authority + ";" + names[j]; 7990 } 7991 if (DEBUG_PACKAGE_SCANNING) { 7992 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7993 Log.d(TAG, "Registered content provider: " + names[j] 7994 + ", className = " + p.info.name + ", isSyncable = " 7995 + p.info.isSyncable); 7996 } 7997 } else { 7998 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7999 Slog.w(TAG, "Skipping provider name " + names[j] + 8000 " (in package " + pkg.applicationInfo.packageName + 8001 "): name already used by " 8002 + ((other != null && other.getComponentName() != null) 8003 ? other.getComponentName().getPackageName() : "?")); 8004 } 8005 } 8006 } 8007 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8008 if (r == null) { 8009 r = new StringBuilder(256); 8010 } else { 8011 r.append(' '); 8012 } 8013 r.append(p.info.name); 8014 } 8015 } 8016 if (r != null) { 8017 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8018 } 8019 8020 N = pkg.services.size(); 8021 r = null; 8022 for (i=0; i<N; i++) { 8023 PackageParser.Service s = pkg.services.get(i); 8024 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8025 s.info.processName, pkg.applicationInfo.uid); 8026 mServices.addService(s); 8027 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8028 if (r == null) { 8029 r = new StringBuilder(256); 8030 } else { 8031 r.append(' '); 8032 } 8033 r.append(s.info.name); 8034 } 8035 } 8036 if (r != null) { 8037 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8038 } 8039 8040 N = pkg.receivers.size(); 8041 r = null; 8042 for (i=0; i<N; i++) { 8043 PackageParser.Activity a = pkg.receivers.get(i); 8044 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8045 a.info.processName, pkg.applicationInfo.uid); 8046 mReceivers.addActivity(a, "receiver"); 8047 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8048 if (r == null) { 8049 r = new StringBuilder(256); 8050 } else { 8051 r.append(' '); 8052 } 8053 r.append(a.info.name); 8054 } 8055 } 8056 if (r != null) { 8057 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8058 } 8059 8060 N = pkg.activities.size(); 8061 r = null; 8062 for (i=0; i<N; i++) { 8063 PackageParser.Activity a = pkg.activities.get(i); 8064 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8065 a.info.processName, pkg.applicationInfo.uid); 8066 mActivities.addActivity(a, "activity"); 8067 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8068 if (r == null) { 8069 r = new StringBuilder(256); 8070 } else { 8071 r.append(' '); 8072 } 8073 r.append(a.info.name); 8074 } 8075 } 8076 if (r != null) { 8077 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8078 } 8079 8080 N = pkg.permissionGroups.size(); 8081 r = null; 8082 for (i=0; i<N; i++) { 8083 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8084 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8085 if (cur == null) { 8086 mPermissionGroups.put(pg.info.name, pg); 8087 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8088 if (r == null) { 8089 r = new StringBuilder(256); 8090 } else { 8091 r.append(' '); 8092 } 8093 r.append(pg.info.name); 8094 } 8095 } else { 8096 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8097 + pg.info.packageName + " ignored: original from " 8098 + cur.info.packageName); 8099 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8100 if (r == null) { 8101 r = new StringBuilder(256); 8102 } else { 8103 r.append(' '); 8104 } 8105 r.append("DUP:"); 8106 r.append(pg.info.name); 8107 } 8108 } 8109 } 8110 if (r != null) { 8111 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8112 } 8113 8114 N = pkg.permissions.size(); 8115 r = null; 8116 for (i=0; i<N; i++) { 8117 PackageParser.Permission p = pkg.permissions.get(i); 8118 8119 // Assume by default that we did not install this permission into the system. 8120 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8121 8122 // Now that permission groups have a special meaning, we ignore permission 8123 // groups for legacy apps to prevent unexpected behavior. In particular, 8124 // permissions for one app being granted to someone just becase they happen 8125 // to be in a group defined by another app (before this had no implications). 8126 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8127 p.group = mPermissionGroups.get(p.info.group); 8128 // Warn for a permission in an unknown group. 8129 if (p.info.group != null && p.group == null) { 8130 Slog.w(TAG, "Permission " + p.info.name + " from package " 8131 + p.info.packageName + " in an unknown group " + p.info.group); 8132 } 8133 } 8134 8135 ArrayMap<String, BasePermission> permissionMap = 8136 p.tree ? mSettings.mPermissionTrees 8137 : mSettings.mPermissions; 8138 BasePermission bp = permissionMap.get(p.info.name); 8139 8140 // Allow system apps to redefine non-system permissions 8141 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8142 final boolean currentOwnerIsSystem = (bp.perm != null 8143 && isSystemApp(bp.perm.owner)); 8144 if (isSystemApp(p.owner)) { 8145 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8146 // It's a built-in permission and no owner, take ownership now 8147 bp.packageSetting = pkgSetting; 8148 bp.perm = p; 8149 bp.uid = pkg.applicationInfo.uid; 8150 bp.sourcePackage = p.info.packageName; 8151 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8152 } else if (!currentOwnerIsSystem) { 8153 String msg = "New decl " + p.owner + " of permission " 8154 + p.info.name + " is system; overriding " + bp.sourcePackage; 8155 reportSettingsProblem(Log.WARN, msg); 8156 bp = null; 8157 } 8158 } 8159 } 8160 8161 if (bp == null) { 8162 bp = new BasePermission(p.info.name, p.info.packageName, 8163 BasePermission.TYPE_NORMAL); 8164 permissionMap.put(p.info.name, bp); 8165 } 8166 8167 if (bp.perm == null) { 8168 if (bp.sourcePackage == null 8169 || bp.sourcePackage.equals(p.info.packageName)) { 8170 BasePermission tree = findPermissionTreeLP(p.info.name); 8171 if (tree == null 8172 || tree.sourcePackage.equals(p.info.packageName)) { 8173 bp.packageSetting = pkgSetting; 8174 bp.perm = p; 8175 bp.uid = pkg.applicationInfo.uid; 8176 bp.sourcePackage = p.info.packageName; 8177 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8178 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8179 if (r == null) { 8180 r = new StringBuilder(256); 8181 } else { 8182 r.append(' '); 8183 } 8184 r.append(p.info.name); 8185 } 8186 } else { 8187 Slog.w(TAG, "Permission " + p.info.name + " from package " 8188 + p.info.packageName + " ignored: base tree " 8189 + tree.name + " is from package " 8190 + tree.sourcePackage); 8191 } 8192 } else { 8193 Slog.w(TAG, "Permission " + p.info.name + " from package " 8194 + p.info.packageName + " ignored: original from " 8195 + bp.sourcePackage); 8196 } 8197 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8198 if (r == null) { 8199 r = new StringBuilder(256); 8200 } else { 8201 r.append(' '); 8202 } 8203 r.append("DUP:"); 8204 r.append(p.info.name); 8205 } 8206 if (bp.perm == p) { 8207 bp.protectionLevel = p.info.protectionLevel; 8208 } 8209 } 8210 8211 if (r != null) { 8212 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8213 } 8214 8215 N = pkg.instrumentation.size(); 8216 r = null; 8217 for (i=0; i<N; i++) { 8218 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8219 a.info.packageName = pkg.applicationInfo.packageName; 8220 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8221 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8222 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8223 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8224 a.info.dataDir = pkg.applicationInfo.dataDir; 8225 a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir; 8226 a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir; 8227 8228 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8229 // need other information about the application, like the ABI and what not ? 8230 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8231 mInstrumentation.put(a.getComponentName(), a); 8232 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8233 if (r == null) { 8234 r = new StringBuilder(256); 8235 } else { 8236 r.append(' '); 8237 } 8238 r.append(a.info.name); 8239 } 8240 } 8241 if (r != null) { 8242 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8243 } 8244 8245 if (pkg.protectedBroadcasts != null) { 8246 N = pkg.protectedBroadcasts.size(); 8247 for (i=0; i<N; i++) { 8248 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8249 } 8250 } 8251 8252 pkgSetting.setTimeStamp(scanFileTime); 8253 8254 // Create idmap files for pairs of (packages, overlay packages). 8255 // Note: "android", ie framework-res.apk, is handled by native layers. 8256 if (pkg.mOverlayTarget != null) { 8257 // This is an overlay package. 8258 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8259 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8260 mOverlays.put(pkg.mOverlayTarget, 8261 new ArrayMap<String, PackageParser.Package>()); 8262 } 8263 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8264 map.put(pkg.packageName, pkg); 8265 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8266 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8267 createIdmapFailed = true; 8268 } 8269 } 8270 } else if (mOverlays.containsKey(pkg.packageName) && 8271 !pkg.packageName.equals("android")) { 8272 // This is a regular package, with one or more known overlay packages. 8273 createIdmapsForPackageLI(pkg); 8274 } 8275 } 8276 8277 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8278 8279 if (createIdmapFailed) { 8280 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8281 "scanPackageLI failed to createIdmap"); 8282 } 8283 return pkg; 8284 } 8285 8286 /** 8287 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8288 * is derived purely on the basis of the contents of {@code scanFile} and 8289 * {@code cpuAbiOverride}. 8290 * 8291 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8292 */ 8293 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8294 String cpuAbiOverride, boolean extractLibs) 8295 throws PackageManagerException { 8296 // TODO: We can probably be smarter about this stuff. For installed apps, 8297 // we can calculate this information at install time once and for all. For 8298 // system apps, we can probably assume that this information doesn't change 8299 // after the first boot scan. As things stand, we do lots of unnecessary work. 8300 8301 // Give ourselves some initial paths; we'll come back for another 8302 // pass once we've determined ABI below. 8303 setNativeLibraryPaths(pkg); 8304 8305 // We would never need to extract libs for forward-locked and external packages, 8306 // since the container service will do it for us. We shouldn't attempt to 8307 // extract libs from system app when it was not updated. 8308 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8309 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8310 extractLibs = false; 8311 } 8312 8313 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8314 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8315 8316 NativeLibraryHelper.Handle handle = null; 8317 try { 8318 handle = NativeLibraryHelper.Handle.create(pkg); 8319 // TODO(multiArch): This can be null for apps that didn't go through the 8320 // usual installation process. We can calculate it again, like we 8321 // do during install time. 8322 // 8323 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8324 // unnecessary. 8325 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8326 8327 // Null out the abis so that they can be recalculated. 8328 pkg.applicationInfo.primaryCpuAbi = null; 8329 pkg.applicationInfo.secondaryCpuAbi = null; 8330 if (isMultiArch(pkg.applicationInfo)) { 8331 // Warn if we've set an abiOverride for multi-lib packages.. 8332 // By definition, we need to copy both 32 and 64 bit libraries for 8333 // such packages. 8334 if (pkg.cpuAbiOverride != null 8335 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8336 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8337 } 8338 8339 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8340 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8341 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8342 if (extractLibs) { 8343 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8344 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8345 useIsaSpecificSubdirs); 8346 } else { 8347 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8348 } 8349 } 8350 8351 maybeThrowExceptionForMultiArchCopy( 8352 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8353 8354 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8355 if (extractLibs) { 8356 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8357 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8358 useIsaSpecificSubdirs); 8359 } else { 8360 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8361 } 8362 } 8363 8364 maybeThrowExceptionForMultiArchCopy( 8365 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8366 8367 if (abi64 >= 0) { 8368 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8369 } 8370 8371 if (abi32 >= 0) { 8372 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8373 if (abi64 >= 0) { 8374 if (cpuAbiOverride == null && pkg.use32bitAbi) { 8375 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8376 pkg.applicationInfo.primaryCpuAbi = abi; 8377 } else { 8378 pkg.applicationInfo.secondaryCpuAbi = abi; 8379 } 8380 } else { 8381 pkg.applicationInfo.primaryCpuAbi = abi; 8382 } 8383 } 8384 8385 } else { 8386 String[] abiList = (cpuAbiOverride != null) ? 8387 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8388 8389 // Enable gross and lame hacks for apps that are built with old 8390 // SDK tools. We must scan their APKs for renderscript bitcode and 8391 // not launch them if it's present. Don't bother checking on devices 8392 // that don't have 64 bit support. 8393 boolean needsRenderScriptOverride = false; 8394 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8395 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8396 abiList = Build.SUPPORTED_32_BIT_ABIS; 8397 needsRenderScriptOverride = true; 8398 } 8399 8400 final int copyRet; 8401 if (extractLibs) { 8402 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8403 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8404 } else { 8405 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8406 } 8407 8408 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8409 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8410 "Error unpackaging native libs for app, errorCode=" + copyRet); 8411 } 8412 8413 if (copyRet >= 0) { 8414 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8415 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8416 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8417 } else if (needsRenderScriptOverride) { 8418 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8419 } 8420 } 8421 } catch (IOException ioe) { 8422 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8423 } finally { 8424 IoUtils.closeQuietly(handle); 8425 } 8426 8427 // Now that we've calculated the ABIs and determined if it's an internal app, 8428 // we will go ahead and populate the nativeLibraryPath. 8429 setNativeLibraryPaths(pkg); 8430 } 8431 8432 /** 8433 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8434 * i.e, so that all packages can be run inside a single process if required. 8435 * 8436 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8437 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8438 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8439 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8440 * updating a package that belongs to a shared user. 8441 * 8442 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8443 * adds unnecessary complexity. 8444 */ 8445 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8446 PackageParser.Package scannedPackage, boolean bootComplete) { 8447 String requiredInstructionSet = null; 8448 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8449 requiredInstructionSet = VMRuntime.getInstructionSet( 8450 scannedPackage.applicationInfo.primaryCpuAbi); 8451 } 8452 8453 PackageSetting requirer = null; 8454 for (PackageSetting ps : packagesForUser) { 8455 // If packagesForUser contains scannedPackage, we skip it. This will happen 8456 // when scannedPackage is an update of an existing package. Without this check, 8457 // we will never be able to change the ABI of any package belonging to a shared 8458 // user, even if it's compatible with other packages. 8459 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8460 if (ps.primaryCpuAbiString == null) { 8461 continue; 8462 } 8463 8464 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8465 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8466 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8467 // this but there's not much we can do. 8468 String errorMessage = "Instruction set mismatch, " 8469 + ((requirer == null) ? "[caller]" : requirer) 8470 + " requires " + requiredInstructionSet + " whereas " + ps 8471 + " requires " + instructionSet; 8472 Slog.w(TAG, errorMessage); 8473 } 8474 8475 if (requiredInstructionSet == null) { 8476 requiredInstructionSet = instructionSet; 8477 requirer = ps; 8478 } 8479 } 8480 } 8481 8482 if (requiredInstructionSet != null) { 8483 String adjustedAbi; 8484 if (requirer != null) { 8485 // requirer != null implies that either scannedPackage was null or that scannedPackage 8486 // did not require an ABI, in which case we have to adjust scannedPackage to match 8487 // the ABI of the set (which is the same as requirer's ABI) 8488 adjustedAbi = requirer.primaryCpuAbiString; 8489 if (scannedPackage != null) { 8490 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8491 } 8492 } else { 8493 // requirer == null implies that we're updating all ABIs in the set to 8494 // match scannedPackage. 8495 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8496 } 8497 8498 for (PackageSetting ps : packagesForUser) { 8499 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8500 if (ps.primaryCpuAbiString != null) { 8501 continue; 8502 } 8503 8504 ps.primaryCpuAbiString = adjustedAbi; 8505 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8506 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8507 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8508 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8509 + " (requirer=" 8510 + (requirer == null ? "null" : requirer.pkg.packageName) 8511 + ", scannedPackage=" 8512 + (scannedPackage != null ? scannedPackage.packageName : "null") 8513 + ")"); 8514 try { 8515 mInstaller.rmdex(ps.codePathString, 8516 getDexCodeInstructionSet(getPreferredInstructionSet())); 8517 } catch (InstallerException ignored) { 8518 } 8519 } 8520 } 8521 } 8522 } 8523 } 8524 8525 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8526 synchronized (mPackages) { 8527 mResolverReplaced = true; 8528 // Set up information for custom user intent resolution activity. 8529 mResolveActivity.applicationInfo = pkg.applicationInfo; 8530 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8531 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8532 mResolveActivity.processName = pkg.applicationInfo.packageName; 8533 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8534 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8535 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8536 mResolveActivity.theme = 0; 8537 mResolveActivity.exported = true; 8538 mResolveActivity.enabled = true; 8539 mResolveInfo.activityInfo = mResolveActivity; 8540 mResolveInfo.priority = 0; 8541 mResolveInfo.preferredOrder = 0; 8542 mResolveInfo.match = 0; 8543 mResolveComponentName = mCustomResolverComponentName; 8544 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8545 mResolveComponentName); 8546 } 8547 } 8548 8549 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8550 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8551 8552 // Set up information for ephemeral installer activity 8553 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8554 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8555 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8556 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8557 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8558 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8559 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8560 mEphemeralInstallerActivity.theme = 0; 8561 mEphemeralInstallerActivity.exported = true; 8562 mEphemeralInstallerActivity.enabled = true; 8563 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8564 mEphemeralInstallerInfo.priority = 0; 8565 mEphemeralInstallerInfo.preferredOrder = 0; 8566 mEphemeralInstallerInfo.match = 0; 8567 8568 if (DEBUG_EPHEMERAL) { 8569 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8570 } 8571 } 8572 8573 private static String calculateBundledApkRoot(final String codePathString) { 8574 final File codePath = new File(codePathString); 8575 final File codeRoot; 8576 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8577 codeRoot = Environment.getRootDirectory(); 8578 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8579 codeRoot = Environment.getOemDirectory(); 8580 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8581 codeRoot = Environment.getVendorDirectory(); 8582 } else { 8583 // Unrecognized code path; take its top real segment as the apk root: 8584 // e.g. /something/app/blah.apk => /something 8585 try { 8586 File f = codePath.getCanonicalFile(); 8587 File parent = f.getParentFile(); // non-null because codePath is a file 8588 File tmp; 8589 while ((tmp = parent.getParentFile()) != null) { 8590 f = parent; 8591 parent = tmp; 8592 } 8593 codeRoot = f; 8594 Slog.w(TAG, "Unrecognized code path " 8595 + codePath + " - using " + codeRoot); 8596 } catch (IOException e) { 8597 // Can't canonicalize the code path -- shenanigans? 8598 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8599 return Environment.getRootDirectory().getPath(); 8600 } 8601 } 8602 return codeRoot.getPath(); 8603 } 8604 8605 /** 8606 * Derive and set the location of native libraries for the given package, 8607 * which varies depending on where and how the package was installed. 8608 */ 8609 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8610 final ApplicationInfo info = pkg.applicationInfo; 8611 final String codePath = pkg.codePath; 8612 final File codeFile = new File(codePath); 8613 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8614 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8615 8616 info.nativeLibraryRootDir = null; 8617 info.nativeLibraryRootRequiresIsa = false; 8618 info.nativeLibraryDir = null; 8619 info.secondaryNativeLibraryDir = null; 8620 8621 if (isApkFile(codeFile)) { 8622 // Monolithic install 8623 if (bundledApp) { 8624 // If "/system/lib64/apkname" exists, assume that is the per-package 8625 // native library directory to use; otherwise use "/system/lib/apkname". 8626 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8627 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8628 getPrimaryInstructionSet(info)); 8629 8630 // This is a bundled system app so choose the path based on the ABI. 8631 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8632 // is just the default path. 8633 final String apkName = deriveCodePathName(codePath); 8634 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8635 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8636 apkName).getAbsolutePath(); 8637 8638 if (info.secondaryCpuAbi != null) { 8639 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8640 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8641 secondaryLibDir, apkName).getAbsolutePath(); 8642 } 8643 } else if (asecApp) { 8644 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8645 .getAbsolutePath(); 8646 } else { 8647 final String apkName = deriveCodePathName(codePath); 8648 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8649 .getAbsolutePath(); 8650 } 8651 8652 info.nativeLibraryRootRequiresIsa = false; 8653 info.nativeLibraryDir = info.nativeLibraryRootDir; 8654 } else { 8655 // Cluster install 8656 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8657 info.nativeLibraryRootRequiresIsa = true; 8658 8659 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8660 getPrimaryInstructionSet(info)).getAbsolutePath(); 8661 8662 if (info.secondaryCpuAbi != null) { 8663 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8664 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8665 } 8666 } 8667 } 8668 8669 /** 8670 * Calculate the abis and roots for a bundled app. These can uniquely 8671 * be determined from the contents of the system partition, i.e whether 8672 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8673 * of this information, and instead assume that the system was built 8674 * sensibly. 8675 */ 8676 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8677 PackageSetting pkgSetting) { 8678 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8679 8680 // If "/system/lib64/apkname" exists, assume that is the per-package 8681 // native library directory to use; otherwise use "/system/lib/apkname". 8682 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8683 setBundledAppAbi(pkg, apkRoot, apkName); 8684 // pkgSetting might be null during rescan following uninstall of updates 8685 // to a bundled app, so accommodate that possibility. The settings in 8686 // that case will be established later from the parsed package. 8687 // 8688 // If the settings aren't null, sync them up with what we've just derived. 8689 // note that apkRoot isn't stored in the package settings. 8690 if (pkgSetting != null) { 8691 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8692 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8693 } 8694 } 8695 8696 /** 8697 * Deduces the ABI of a bundled app and sets the relevant fields on the 8698 * parsed pkg object. 8699 * 8700 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8701 * under which system libraries are installed. 8702 * @param apkName the name of the installed package. 8703 */ 8704 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8705 final File codeFile = new File(pkg.codePath); 8706 8707 final boolean has64BitLibs; 8708 final boolean has32BitLibs; 8709 if (isApkFile(codeFile)) { 8710 // Monolithic install 8711 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8712 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8713 } else { 8714 // Cluster install 8715 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8716 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8717 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8718 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8719 has64BitLibs = (new File(rootDir, isa)).exists(); 8720 } else { 8721 has64BitLibs = false; 8722 } 8723 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8724 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8725 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8726 has32BitLibs = (new File(rootDir, isa)).exists(); 8727 } else { 8728 has32BitLibs = false; 8729 } 8730 } 8731 8732 if (has64BitLibs && !has32BitLibs) { 8733 // The package has 64 bit libs, but not 32 bit libs. Its primary 8734 // ABI should be 64 bit. We can safely assume here that the bundled 8735 // native libraries correspond to the most preferred ABI in the list. 8736 8737 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8738 pkg.applicationInfo.secondaryCpuAbi = null; 8739 } else if (has32BitLibs && !has64BitLibs) { 8740 // The package has 32 bit libs but not 64 bit libs. Its primary 8741 // ABI should be 32 bit. 8742 8743 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8744 pkg.applicationInfo.secondaryCpuAbi = null; 8745 } else if (has32BitLibs && has64BitLibs) { 8746 // The application has both 64 and 32 bit bundled libraries. We check 8747 // here that the app declares multiArch support, and warn if it doesn't. 8748 // 8749 // We will be lenient here and record both ABIs. The primary will be the 8750 // ABI that's higher on the list, i.e, a device that's configured to prefer 8751 // 64 bit apps will see a 64 bit primary ABI, 8752 8753 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8754 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 8755 } 8756 8757 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8758 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8759 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8760 } else { 8761 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8762 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8763 } 8764 } else { 8765 pkg.applicationInfo.primaryCpuAbi = null; 8766 pkg.applicationInfo.secondaryCpuAbi = null; 8767 } 8768 } 8769 8770 private void killPackage(PackageParser.Package pkg, String reason) { 8771 // Kill the parent package 8772 killApplication(pkg.packageName, pkg.applicationInfo.uid, reason); 8773 // Kill the child packages 8774 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8775 for (int i = 0; i < childCount; i++) { 8776 PackageParser.Package childPkg = pkg.childPackages.get(i); 8777 killApplication(childPkg.packageName, childPkg.applicationInfo.uid, reason); 8778 } 8779 } 8780 8781 private void killApplication(String pkgName, int appId, String reason) { 8782 // Request the ActivityManager to kill the process(only for existing packages) 8783 // so that we do not end up in a confused state while the user is still using the older 8784 // version of the application while the new one gets installed. 8785 IActivityManager am = ActivityManagerNative.getDefault(); 8786 if (am != null) { 8787 try { 8788 am.killApplicationWithAppId(pkgName, appId, reason); 8789 } catch (RemoteException e) { 8790 } 8791 } 8792 } 8793 8794 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 8795 // Remove the parent package setting 8796 PackageSetting ps = (PackageSetting) pkg.mExtras; 8797 if (ps != null) { 8798 removePackageLI(ps, chatty); 8799 } 8800 // Remove the child package setting 8801 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8802 for (int i = 0; i < childCount; i++) { 8803 PackageParser.Package childPkg = pkg.childPackages.get(i); 8804 ps = (PackageSetting) childPkg.mExtras; 8805 if (ps != null) { 8806 removePackageLI(ps, chatty); 8807 } 8808 } 8809 } 8810 8811 void removePackageLI(PackageSetting ps, boolean chatty) { 8812 if (DEBUG_INSTALL) { 8813 if (chatty) 8814 Log.d(TAG, "Removing package " + ps.name); 8815 } 8816 8817 // writer 8818 synchronized (mPackages) { 8819 mPackages.remove(ps.name); 8820 final PackageParser.Package pkg = ps.pkg; 8821 if (pkg != null) { 8822 cleanPackageDataStructuresLILPw(pkg, chatty); 8823 } 8824 } 8825 } 8826 8827 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8828 if (DEBUG_INSTALL) { 8829 if (chatty) 8830 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8831 } 8832 8833 // writer 8834 synchronized (mPackages) { 8835 // Remove the parent package 8836 mPackages.remove(pkg.applicationInfo.packageName); 8837 cleanPackageDataStructuresLILPw(pkg, chatty); 8838 8839 // Remove the child packages 8840 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8841 for (int i = 0; i < childCount; i++) { 8842 PackageParser.Package childPkg = pkg.childPackages.get(i); 8843 mPackages.remove(childPkg.applicationInfo.packageName); 8844 cleanPackageDataStructuresLILPw(childPkg, chatty); 8845 } 8846 } 8847 } 8848 8849 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8850 int N = pkg.providers.size(); 8851 StringBuilder r = null; 8852 int i; 8853 for (i=0; i<N; i++) { 8854 PackageParser.Provider p = pkg.providers.get(i); 8855 mProviders.removeProvider(p); 8856 if (p.info.authority == null) { 8857 8858 /* There was another ContentProvider with this authority when 8859 * this app was installed so this authority is null, 8860 * Ignore it as we don't have to unregister the provider. 8861 */ 8862 continue; 8863 } 8864 String names[] = p.info.authority.split(";"); 8865 for (int j = 0; j < names.length; j++) { 8866 if (mProvidersByAuthority.get(names[j]) == p) { 8867 mProvidersByAuthority.remove(names[j]); 8868 if (DEBUG_REMOVE) { 8869 if (chatty) 8870 Log.d(TAG, "Unregistered content provider: " + names[j] 8871 + ", className = " + p.info.name + ", isSyncable = " 8872 + p.info.isSyncable); 8873 } 8874 } 8875 } 8876 if (DEBUG_REMOVE && chatty) { 8877 if (r == null) { 8878 r = new StringBuilder(256); 8879 } else { 8880 r.append(' '); 8881 } 8882 r.append(p.info.name); 8883 } 8884 } 8885 if (r != null) { 8886 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8887 } 8888 8889 N = pkg.services.size(); 8890 r = null; 8891 for (i=0; i<N; i++) { 8892 PackageParser.Service s = pkg.services.get(i); 8893 mServices.removeService(s); 8894 if (chatty) { 8895 if (r == null) { 8896 r = new StringBuilder(256); 8897 } else { 8898 r.append(' '); 8899 } 8900 r.append(s.info.name); 8901 } 8902 } 8903 if (r != null) { 8904 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8905 } 8906 8907 N = pkg.receivers.size(); 8908 r = null; 8909 for (i=0; i<N; i++) { 8910 PackageParser.Activity a = pkg.receivers.get(i); 8911 mReceivers.removeActivity(a, "receiver"); 8912 if (DEBUG_REMOVE && chatty) { 8913 if (r == null) { 8914 r = new StringBuilder(256); 8915 } else { 8916 r.append(' '); 8917 } 8918 r.append(a.info.name); 8919 } 8920 } 8921 if (r != null) { 8922 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8923 } 8924 8925 N = pkg.activities.size(); 8926 r = null; 8927 for (i=0; i<N; i++) { 8928 PackageParser.Activity a = pkg.activities.get(i); 8929 mActivities.removeActivity(a, "activity"); 8930 if (DEBUG_REMOVE && chatty) { 8931 if (r == null) { 8932 r = new StringBuilder(256); 8933 } else { 8934 r.append(' '); 8935 } 8936 r.append(a.info.name); 8937 } 8938 } 8939 if (r != null) { 8940 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8941 } 8942 8943 N = pkg.permissions.size(); 8944 r = null; 8945 for (i=0; i<N; i++) { 8946 PackageParser.Permission p = pkg.permissions.get(i); 8947 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8948 if (bp == null) { 8949 bp = mSettings.mPermissionTrees.get(p.info.name); 8950 } 8951 if (bp != null && bp.perm == p) { 8952 bp.perm = null; 8953 if (DEBUG_REMOVE && chatty) { 8954 if (r == null) { 8955 r = new StringBuilder(256); 8956 } else { 8957 r.append(' '); 8958 } 8959 r.append(p.info.name); 8960 } 8961 } 8962 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8963 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 8964 if (appOpPkgs != null) { 8965 appOpPkgs.remove(pkg.packageName); 8966 } 8967 } 8968 } 8969 if (r != null) { 8970 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8971 } 8972 8973 N = pkg.requestedPermissions.size(); 8974 r = null; 8975 for (i=0; i<N; i++) { 8976 String perm = pkg.requestedPermissions.get(i); 8977 BasePermission bp = mSettings.mPermissions.get(perm); 8978 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8979 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 8980 if (appOpPkgs != null) { 8981 appOpPkgs.remove(pkg.packageName); 8982 if (appOpPkgs.isEmpty()) { 8983 mAppOpPermissionPackages.remove(perm); 8984 } 8985 } 8986 } 8987 } 8988 if (r != null) { 8989 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8990 } 8991 8992 N = pkg.instrumentation.size(); 8993 r = null; 8994 for (i=0; i<N; i++) { 8995 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8996 mInstrumentation.remove(a.getComponentName()); 8997 if (DEBUG_REMOVE && chatty) { 8998 if (r == null) { 8999 r = new StringBuilder(256); 9000 } else { 9001 r.append(' '); 9002 } 9003 r.append(a.info.name); 9004 } 9005 } 9006 if (r != null) { 9007 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9008 } 9009 9010 r = null; 9011 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9012 // Only system apps can hold shared libraries. 9013 if (pkg.libraryNames != null) { 9014 for (i=0; i<pkg.libraryNames.size(); i++) { 9015 String name = pkg.libraryNames.get(i); 9016 SharedLibraryEntry cur = mSharedLibraries.get(name); 9017 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9018 mSharedLibraries.remove(name); 9019 if (DEBUG_REMOVE && chatty) { 9020 if (r == null) { 9021 r = new StringBuilder(256); 9022 } else { 9023 r.append(' '); 9024 } 9025 r.append(name); 9026 } 9027 } 9028 } 9029 } 9030 } 9031 if (r != null) { 9032 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9033 } 9034 } 9035 9036 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9037 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9038 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9039 return true; 9040 } 9041 } 9042 return false; 9043 } 9044 9045 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9046 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9047 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9048 9049 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9050 // Update the parent permissions 9051 updatePermissionsLPw(pkg.packageName, pkg, flags); 9052 // Update the child permissions 9053 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9054 for (int i = 0; i < childCount; i++) { 9055 PackageParser.Package childPkg = pkg.childPackages.get(i); 9056 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9057 } 9058 } 9059 9060 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9061 int flags) { 9062 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9063 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9064 } 9065 9066 private void updatePermissionsLPw(String changingPkg, 9067 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9068 // Make sure there are no dangling permission trees. 9069 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9070 while (it.hasNext()) { 9071 final BasePermission bp = it.next(); 9072 if (bp.packageSetting == null) { 9073 // We may not yet have parsed the package, so just see if 9074 // we still know about its settings. 9075 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9076 } 9077 if (bp.packageSetting == null) { 9078 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9079 + " from package " + bp.sourcePackage); 9080 it.remove(); 9081 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9082 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9083 Slog.i(TAG, "Removing old permission tree: " + bp.name 9084 + " from package " + bp.sourcePackage); 9085 flags |= UPDATE_PERMISSIONS_ALL; 9086 it.remove(); 9087 } 9088 } 9089 } 9090 9091 // Make sure all dynamic permissions have been assigned to a package, 9092 // and make sure there are no dangling permissions. 9093 it = mSettings.mPermissions.values().iterator(); 9094 while (it.hasNext()) { 9095 final BasePermission bp = it.next(); 9096 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9097 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9098 + bp.name + " pkg=" + bp.sourcePackage 9099 + " info=" + bp.pendingInfo); 9100 if (bp.packageSetting == null && bp.pendingInfo != null) { 9101 final BasePermission tree = findPermissionTreeLP(bp.name); 9102 if (tree != null && tree.perm != null) { 9103 bp.packageSetting = tree.packageSetting; 9104 bp.perm = new PackageParser.Permission(tree.perm.owner, 9105 new PermissionInfo(bp.pendingInfo)); 9106 bp.perm.info.packageName = tree.perm.info.packageName; 9107 bp.perm.info.name = bp.name; 9108 bp.uid = tree.uid; 9109 } 9110 } 9111 } 9112 if (bp.packageSetting == null) { 9113 // We may not yet have parsed the package, so just see if 9114 // we still know about its settings. 9115 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9116 } 9117 if (bp.packageSetting == null) { 9118 Slog.w(TAG, "Removing dangling permission: " + bp.name 9119 + " from package " + bp.sourcePackage); 9120 it.remove(); 9121 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9122 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9123 Slog.i(TAG, "Removing old permission: " + bp.name 9124 + " from package " + bp.sourcePackage); 9125 flags |= UPDATE_PERMISSIONS_ALL; 9126 it.remove(); 9127 } 9128 } 9129 } 9130 9131 // Now update the permissions for all packages, in particular 9132 // replace the granted permissions of the system packages. 9133 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9134 for (PackageParser.Package pkg : mPackages.values()) { 9135 if (pkg != pkgInfo) { 9136 // Only replace for packages on requested volume 9137 final String volumeUuid = getVolumeUuidForPackage(pkg); 9138 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9139 && Objects.equals(replaceVolumeUuid, volumeUuid); 9140 grantPermissionsLPw(pkg, replace, changingPkg); 9141 } 9142 } 9143 } 9144 9145 if (pkgInfo != null) { 9146 // Only replace for packages on requested volume 9147 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9148 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9149 && Objects.equals(replaceVolumeUuid, volumeUuid); 9150 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9151 } 9152 } 9153 9154 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9155 String packageOfInterest) { 9156 // IMPORTANT: There are two types of permissions: install and runtime. 9157 // Install time permissions are granted when the app is installed to 9158 // all device users and users added in the future. Runtime permissions 9159 // are granted at runtime explicitly to specific users. Normal and signature 9160 // protected permissions are install time permissions. Dangerous permissions 9161 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9162 // otherwise they are runtime permissions. This function does not manage 9163 // runtime permissions except for the case an app targeting Lollipop MR1 9164 // being upgraded to target a newer SDK, in which case dangerous permissions 9165 // are transformed from install time to runtime ones. 9166 9167 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9168 if (ps == null) { 9169 return; 9170 } 9171 9172 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9173 9174 PermissionsState permissionsState = ps.getPermissionsState(); 9175 PermissionsState origPermissions = permissionsState; 9176 9177 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9178 9179 boolean runtimePermissionsRevoked = false; 9180 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9181 9182 boolean changedInstallPermission = false; 9183 9184 if (replace) { 9185 ps.installPermissionsFixed = false; 9186 if (!ps.isSharedUser()) { 9187 origPermissions = new PermissionsState(permissionsState); 9188 permissionsState.reset(); 9189 } else { 9190 // We need to know only about runtime permission changes since the 9191 // calling code always writes the install permissions state but 9192 // the runtime ones are written only if changed. The only cases of 9193 // changed runtime permissions here are promotion of an install to 9194 // runtime and revocation of a runtime from a shared user. 9195 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9196 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9197 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9198 runtimePermissionsRevoked = true; 9199 } 9200 } 9201 } 9202 9203 permissionsState.setGlobalGids(mGlobalGids); 9204 9205 final int N = pkg.requestedPermissions.size(); 9206 for (int i=0; i<N; i++) { 9207 final String name = pkg.requestedPermissions.get(i); 9208 final BasePermission bp = mSettings.mPermissions.get(name); 9209 9210 if (DEBUG_INSTALL) { 9211 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9212 } 9213 9214 if (bp == null || bp.packageSetting == null) { 9215 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9216 Slog.w(TAG, "Unknown permission " + name 9217 + " in package " + pkg.packageName); 9218 } 9219 continue; 9220 } 9221 9222 final String perm = bp.name; 9223 boolean allowedSig = false; 9224 int grant = GRANT_DENIED; 9225 9226 // Keep track of app op permissions. 9227 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9228 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9229 if (pkgs == null) { 9230 pkgs = new ArraySet<>(); 9231 mAppOpPermissionPackages.put(bp.name, pkgs); 9232 } 9233 pkgs.add(pkg.packageName); 9234 } 9235 9236 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9237 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9238 >= Build.VERSION_CODES.M; 9239 switch (level) { 9240 case PermissionInfo.PROTECTION_NORMAL: { 9241 // For all apps normal permissions are install time ones. 9242 grant = GRANT_INSTALL; 9243 } break; 9244 9245 case PermissionInfo.PROTECTION_DANGEROUS: { 9246 // If a permission review is required for legacy apps we represent 9247 // their permissions as always granted runtime ones since we need 9248 // to keep the review required permission flag per user while an 9249 // install permission's state is shared across all users. 9250 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9251 // For legacy apps dangerous permissions are install time ones. 9252 grant = GRANT_INSTALL; 9253 } else if (origPermissions.hasInstallPermission(bp.name)) { 9254 // For legacy apps that became modern, install becomes runtime. 9255 grant = GRANT_UPGRADE; 9256 } else if (mPromoteSystemApps 9257 && isSystemApp(ps) 9258 && mExistingSystemPackages.contains(ps.name)) { 9259 // For legacy system apps, install becomes runtime. 9260 // We cannot check hasInstallPermission() for system apps since those 9261 // permissions were granted implicitly and not persisted pre-M. 9262 grant = GRANT_UPGRADE; 9263 } else { 9264 // For modern apps keep runtime permissions unchanged. 9265 grant = GRANT_RUNTIME; 9266 } 9267 } break; 9268 9269 case PermissionInfo.PROTECTION_SIGNATURE: { 9270 // For all apps signature permissions are install time ones. 9271 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9272 if (allowedSig) { 9273 grant = GRANT_INSTALL; 9274 } 9275 } break; 9276 } 9277 9278 if (DEBUG_INSTALL) { 9279 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9280 } 9281 9282 if (grant != GRANT_DENIED) { 9283 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9284 // If this is an existing, non-system package, then 9285 // we can't add any new permissions to it. 9286 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9287 // Except... if this is a permission that was added 9288 // to the platform (note: need to only do this when 9289 // updating the platform). 9290 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9291 grant = GRANT_DENIED; 9292 } 9293 } 9294 } 9295 9296 switch (grant) { 9297 case GRANT_INSTALL: { 9298 // Revoke this as runtime permission to handle the case of 9299 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 9300 for (int userId : UserManagerService.getInstance().getUserIds()) { 9301 if (origPermissions.getRuntimePermissionState( 9302 bp.name, userId) != null) { 9303 // Revoke the runtime permission and clear the flags. 9304 origPermissions.revokeRuntimePermission(bp, userId); 9305 origPermissions.updatePermissionFlags(bp, userId, 9306 PackageManager.MASK_PERMISSION_FLAGS, 0); 9307 // If we revoked a permission permission, we have to write. 9308 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9309 changedRuntimePermissionUserIds, userId); 9310 } 9311 } 9312 // Grant an install permission. 9313 if (permissionsState.grantInstallPermission(bp) != 9314 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9315 changedInstallPermission = true; 9316 } 9317 } break; 9318 9319 case GRANT_RUNTIME: { 9320 // Grant previously granted runtime permissions. 9321 for (int userId : UserManagerService.getInstance().getUserIds()) { 9322 PermissionState permissionState = origPermissions 9323 .getRuntimePermissionState(bp.name, userId); 9324 int flags = permissionState != null 9325 ? permissionState.getFlags() : 0; 9326 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9327 if (permissionsState.grantRuntimePermission(bp, userId) == 9328 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9329 // If we cannot put the permission as it was, we have to write. 9330 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9331 changedRuntimePermissionUserIds, userId); 9332 } 9333 // If the app supports runtime permissions no need for a review. 9334 if (Build.PERMISSIONS_REVIEW_REQUIRED 9335 && appSupportsRuntimePermissions 9336 && (flags & PackageManager 9337 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9338 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9339 // Since we changed the flags, we have to write. 9340 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9341 changedRuntimePermissionUserIds, userId); 9342 } 9343 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9344 && !appSupportsRuntimePermissions) { 9345 // For legacy apps that need a permission review, every new 9346 // runtime permission is granted but it is pending a review. 9347 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9348 permissionsState.grantRuntimePermission(bp, userId); 9349 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9350 // We changed the permission and flags, hence have to write. 9351 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9352 changedRuntimePermissionUserIds, userId); 9353 } 9354 } 9355 // Propagate the permission flags. 9356 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9357 } 9358 } break; 9359 9360 case GRANT_UPGRADE: { 9361 // Grant runtime permissions for a previously held install permission. 9362 PermissionState permissionState = origPermissions 9363 .getInstallPermissionState(bp.name); 9364 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9365 9366 if (origPermissions.revokeInstallPermission(bp) 9367 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9368 // We will be transferring the permission flags, so clear them. 9369 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9370 PackageManager.MASK_PERMISSION_FLAGS, 0); 9371 changedInstallPermission = true; 9372 } 9373 9374 // If the permission is not to be promoted to runtime we ignore it and 9375 // also its other flags as they are not applicable to install permissions. 9376 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9377 for (int userId : currentUserIds) { 9378 if (permissionsState.grantRuntimePermission(bp, userId) != 9379 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9380 // Transfer the permission flags. 9381 permissionsState.updatePermissionFlags(bp, userId, 9382 flags, flags); 9383 // If we granted the permission, we have to write. 9384 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9385 changedRuntimePermissionUserIds, userId); 9386 } 9387 } 9388 } 9389 } break; 9390 9391 default: { 9392 if (packageOfInterest == null 9393 || packageOfInterest.equals(pkg.packageName)) { 9394 Slog.w(TAG, "Not granting permission " + perm 9395 + " to package " + pkg.packageName 9396 + " because it was previously installed without"); 9397 } 9398 } break; 9399 } 9400 } else { 9401 if (permissionsState.revokeInstallPermission(bp) != 9402 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9403 // Also drop the permission flags. 9404 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9405 PackageManager.MASK_PERMISSION_FLAGS, 0); 9406 changedInstallPermission = true; 9407 Slog.i(TAG, "Un-granting permission " + perm 9408 + " from package " + pkg.packageName 9409 + " (protectionLevel=" + bp.protectionLevel 9410 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9411 + ")"); 9412 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9413 // Don't print warning for app op permissions, since it is fine for them 9414 // not to be granted, there is a UI for the user to decide. 9415 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9416 Slog.w(TAG, "Not granting permission " + perm 9417 + " to package " + pkg.packageName 9418 + " (protectionLevel=" + bp.protectionLevel 9419 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9420 + ")"); 9421 } 9422 } 9423 } 9424 } 9425 9426 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9427 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9428 // This is the first that we have heard about this package, so the 9429 // permissions we have now selected are fixed until explicitly 9430 // changed. 9431 ps.installPermissionsFixed = true; 9432 } 9433 9434 // Persist the runtime permissions state for users with changes. If permissions 9435 // were revoked because no app in the shared user declares them we have to 9436 // write synchronously to avoid losing runtime permissions state. 9437 for (int userId : changedRuntimePermissionUserIds) { 9438 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9439 } 9440 9441 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9442 } 9443 9444 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9445 boolean allowed = false; 9446 final int NP = PackageParser.NEW_PERMISSIONS.length; 9447 for (int ip=0; ip<NP; ip++) { 9448 final PackageParser.NewPermissionInfo npi 9449 = PackageParser.NEW_PERMISSIONS[ip]; 9450 if (npi.name.equals(perm) 9451 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9452 allowed = true; 9453 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9454 + pkg.packageName); 9455 break; 9456 } 9457 } 9458 return allowed; 9459 } 9460 9461 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9462 BasePermission bp, PermissionsState origPermissions) { 9463 boolean allowed; 9464 allowed = (compareSignatures( 9465 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9466 == PackageManager.SIGNATURE_MATCH) 9467 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9468 == PackageManager.SIGNATURE_MATCH); 9469 if (!allowed && (bp.protectionLevel 9470 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9471 if (isSystemApp(pkg)) { 9472 // For updated system applications, a system permission 9473 // is granted only if it had been defined by the original application. 9474 if (pkg.isUpdatedSystemApp()) { 9475 final PackageSetting sysPs = mSettings 9476 .getDisabledSystemPkgLPr(pkg.packageName); 9477 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9478 // If the original was granted this permission, we take 9479 // that grant decision as read and propagate it to the 9480 // update. 9481 if (sysPs.isPrivileged()) { 9482 allowed = true; 9483 } 9484 } else { 9485 // The system apk may have been updated with an older 9486 // version of the one on the data partition, but which 9487 // granted a new system permission that it didn't have 9488 // before. In this case we do want to allow the app to 9489 // now get the new permission if the ancestral apk is 9490 // privileged to get it. 9491 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9492 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9493 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9494 allowed = true; 9495 break; 9496 } 9497 } 9498 } 9499 // Also if a privileged parent package on the system image or any of 9500 // its children requested a privileged permission, the updated child 9501 // packages can also get the permission. 9502 if (pkg.parentPackage != null) { 9503 final PackageSetting disabledSysParentPs = mSettings 9504 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 9505 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 9506 && disabledSysParentPs.isPrivileged()) { 9507 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 9508 allowed = true; 9509 } else if (disabledSysParentPs.pkg.childPackages != null) { 9510 final int count = disabledSysParentPs.pkg.childPackages.size(); 9511 for (int i = 0; i < count; i++) { 9512 PackageParser.Package disabledSysChildPkg = 9513 disabledSysParentPs.pkg.childPackages.get(i); 9514 if (isPackageRequestingPermission(disabledSysChildPkg, 9515 perm)) { 9516 allowed = true; 9517 break; 9518 } 9519 } 9520 } 9521 } 9522 } 9523 } 9524 } else { 9525 allowed = isPrivilegedApp(pkg); 9526 } 9527 } 9528 } 9529 if (!allowed) { 9530 if (!allowed && (bp.protectionLevel 9531 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9532 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9533 // If this was a previously normal/dangerous permission that got moved 9534 // to a system permission as part of the runtime permission redesign, then 9535 // we still want to blindly grant it to old apps. 9536 allowed = true; 9537 } 9538 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9539 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9540 // If this permission is to be granted to the system installer and 9541 // this app is an installer, then it gets the permission. 9542 allowed = true; 9543 } 9544 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9545 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9546 // If this permission is to be granted to the system verifier and 9547 // this app is a verifier, then it gets the permission. 9548 allowed = true; 9549 } 9550 if (!allowed && (bp.protectionLevel 9551 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9552 && isSystemApp(pkg)) { 9553 // Any pre-installed system app is allowed to get this permission. 9554 allowed = true; 9555 } 9556 if (!allowed && (bp.protectionLevel 9557 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9558 // For development permissions, a development permission 9559 // is granted only if it was already granted. 9560 allowed = origPermissions.hasInstallPermission(perm); 9561 } 9562 } 9563 return allowed; 9564 } 9565 9566 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 9567 final int permCount = pkg.requestedPermissions.size(); 9568 for (int j = 0; j < permCount; j++) { 9569 String requestedPermission = pkg.requestedPermissions.get(j); 9570 if (permission.equals(requestedPermission)) { 9571 return true; 9572 } 9573 } 9574 return false; 9575 } 9576 9577 final class ActivityIntentResolver 9578 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9579 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9580 boolean defaultOnly, int userId) { 9581 if (!sUserManager.exists(userId)) return null; 9582 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9583 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9584 } 9585 9586 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9587 int userId) { 9588 if (!sUserManager.exists(userId)) return null; 9589 mFlags = flags; 9590 return super.queryIntent(intent, resolvedType, 9591 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9592 } 9593 9594 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9595 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9596 if (!sUserManager.exists(userId)) return null; 9597 if (packageActivities == null) { 9598 return null; 9599 } 9600 mFlags = flags; 9601 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9602 final int N = packageActivities.size(); 9603 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9604 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9605 9606 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9607 for (int i = 0; i < N; ++i) { 9608 intentFilters = packageActivities.get(i).intents; 9609 if (intentFilters != null && intentFilters.size() > 0) { 9610 PackageParser.ActivityIntentInfo[] array = 9611 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9612 intentFilters.toArray(array); 9613 listCut.add(array); 9614 } 9615 } 9616 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9617 } 9618 9619 public final void addActivity(PackageParser.Activity a, String type) { 9620 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 9621 mActivities.put(a.getComponentName(), a); 9622 if (DEBUG_SHOW_INFO) 9623 Log.v( 9624 TAG, " " + type + " " + 9625 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 9626 if (DEBUG_SHOW_INFO) 9627 Log.v(TAG, " Class=" + a.info.name); 9628 final int NI = a.intents.size(); 9629 for (int j=0; j<NI; j++) { 9630 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9631 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 9632 intent.setPriority(0); 9633 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 9634 + a.className + " with priority > 0, forcing to 0"); 9635 } 9636 if (DEBUG_SHOW_INFO) { 9637 Log.v(TAG, " IntentFilter:"); 9638 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9639 } 9640 if (!intent.debugCheck()) { 9641 Log.w(TAG, "==> For Activity " + a.info.name); 9642 } 9643 addFilter(intent); 9644 } 9645 } 9646 9647 public final void removeActivity(PackageParser.Activity a, String type) { 9648 mActivities.remove(a.getComponentName()); 9649 if (DEBUG_SHOW_INFO) { 9650 Log.v(TAG, " " + type + " " 9651 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 9652 : a.info.name) + ":"); 9653 Log.v(TAG, " Class=" + a.info.name); 9654 } 9655 final int NI = a.intents.size(); 9656 for (int j=0; j<NI; j++) { 9657 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9658 if (DEBUG_SHOW_INFO) { 9659 Log.v(TAG, " IntentFilter:"); 9660 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9661 } 9662 removeFilter(intent); 9663 } 9664 } 9665 9666 @Override 9667 protected boolean allowFilterResult( 9668 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 9669 ActivityInfo filterAi = filter.activity.info; 9670 for (int i=dest.size()-1; i>=0; i--) { 9671 ActivityInfo destAi = dest.get(i).activityInfo; 9672 if (destAi.name == filterAi.name 9673 && destAi.packageName == filterAi.packageName) { 9674 return false; 9675 } 9676 } 9677 return true; 9678 } 9679 9680 @Override 9681 protected ActivityIntentInfo[] newArray(int size) { 9682 return new ActivityIntentInfo[size]; 9683 } 9684 9685 @Override 9686 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 9687 if (!sUserManager.exists(userId)) return true; 9688 PackageParser.Package p = filter.activity.owner; 9689 if (p != null) { 9690 PackageSetting ps = (PackageSetting)p.mExtras; 9691 if (ps != null) { 9692 // System apps are never considered stopped for purposes of 9693 // filtering, because there may be no way for the user to 9694 // actually re-launch them. 9695 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 9696 && ps.getStopped(userId); 9697 } 9698 } 9699 return false; 9700 } 9701 9702 @Override 9703 protected boolean isPackageForFilter(String packageName, 9704 PackageParser.ActivityIntentInfo info) { 9705 return packageName.equals(info.activity.owner.packageName); 9706 } 9707 9708 @Override 9709 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 9710 int match, int userId) { 9711 if (!sUserManager.exists(userId)) return null; 9712 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 9713 return null; 9714 } 9715 final PackageParser.Activity activity = info.activity; 9716 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 9717 if (ps == null) { 9718 return null; 9719 } 9720 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 9721 ps.readUserState(userId), userId); 9722 if (ai == null) { 9723 return null; 9724 } 9725 final ResolveInfo res = new ResolveInfo(); 9726 res.activityInfo = ai; 9727 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9728 res.filter = info; 9729 } 9730 if (info != null) { 9731 res.handleAllWebDataURI = info.handleAllWebDataURI(); 9732 } 9733 res.priority = info.getPriority(); 9734 res.preferredOrder = activity.owner.mPreferredOrder; 9735 //System.out.println("Result: " + res.activityInfo.className + 9736 // " = " + res.priority); 9737 res.match = match; 9738 res.isDefault = info.hasDefault; 9739 res.labelRes = info.labelRes; 9740 res.nonLocalizedLabel = info.nonLocalizedLabel; 9741 if (userNeedsBadging(userId)) { 9742 res.noResourceId = true; 9743 } else { 9744 res.icon = info.icon; 9745 } 9746 res.iconResourceId = info.icon; 9747 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9748 return res; 9749 } 9750 9751 @Override 9752 protected void sortResults(List<ResolveInfo> results) { 9753 Collections.sort(results, mResolvePrioritySorter); 9754 } 9755 9756 @Override 9757 protected void dumpFilter(PrintWriter out, String prefix, 9758 PackageParser.ActivityIntentInfo filter) { 9759 out.print(prefix); out.print( 9760 Integer.toHexString(System.identityHashCode(filter.activity))); 9761 out.print(' '); 9762 filter.activity.printComponentShortName(out); 9763 out.print(" filter "); 9764 out.println(Integer.toHexString(System.identityHashCode(filter))); 9765 } 9766 9767 @Override 9768 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9769 return filter.activity; 9770 } 9771 9772 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9773 PackageParser.Activity activity = (PackageParser.Activity)label; 9774 out.print(prefix); out.print( 9775 Integer.toHexString(System.identityHashCode(activity))); 9776 out.print(' '); 9777 activity.printComponentShortName(out); 9778 if (count > 1) { 9779 out.print(" ("); out.print(count); out.print(" filters)"); 9780 } 9781 out.println(); 9782 } 9783 9784// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9785// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9786// final List<ResolveInfo> retList = Lists.newArrayList(); 9787// while (i.hasNext()) { 9788// final ResolveInfo resolveInfo = i.next(); 9789// if (isEnabledLP(resolveInfo.activityInfo)) { 9790// retList.add(resolveInfo); 9791// } 9792// } 9793// return retList; 9794// } 9795 9796 // Keys are String (activity class name), values are Activity. 9797 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9798 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9799 private int mFlags; 9800 } 9801 9802 private final class ServiceIntentResolver 9803 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9804 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9805 boolean defaultOnly, int userId) { 9806 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9807 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9808 } 9809 9810 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9811 int userId) { 9812 if (!sUserManager.exists(userId)) return null; 9813 mFlags = flags; 9814 return super.queryIntent(intent, resolvedType, 9815 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9816 } 9817 9818 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9819 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9820 if (!sUserManager.exists(userId)) return null; 9821 if (packageServices == null) { 9822 return null; 9823 } 9824 mFlags = flags; 9825 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9826 final int N = packageServices.size(); 9827 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9828 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9829 9830 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9831 for (int i = 0; i < N; ++i) { 9832 intentFilters = packageServices.get(i).intents; 9833 if (intentFilters != null && intentFilters.size() > 0) { 9834 PackageParser.ServiceIntentInfo[] array = 9835 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9836 intentFilters.toArray(array); 9837 listCut.add(array); 9838 } 9839 } 9840 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9841 } 9842 9843 public final void addService(PackageParser.Service s) { 9844 mServices.put(s.getComponentName(), s); 9845 if (DEBUG_SHOW_INFO) { 9846 Log.v(TAG, " " 9847 + (s.info.nonLocalizedLabel != null 9848 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9849 Log.v(TAG, " Class=" + s.info.name); 9850 } 9851 final int NI = s.intents.size(); 9852 int j; 9853 for (j=0; j<NI; j++) { 9854 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9855 if (DEBUG_SHOW_INFO) { 9856 Log.v(TAG, " IntentFilter:"); 9857 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9858 } 9859 if (!intent.debugCheck()) { 9860 Log.w(TAG, "==> For Service " + s.info.name); 9861 } 9862 addFilter(intent); 9863 } 9864 } 9865 9866 public final void removeService(PackageParser.Service s) { 9867 mServices.remove(s.getComponentName()); 9868 if (DEBUG_SHOW_INFO) { 9869 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9870 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9871 Log.v(TAG, " Class=" + s.info.name); 9872 } 9873 final int NI = s.intents.size(); 9874 int j; 9875 for (j=0; j<NI; j++) { 9876 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9877 if (DEBUG_SHOW_INFO) { 9878 Log.v(TAG, " IntentFilter:"); 9879 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9880 } 9881 removeFilter(intent); 9882 } 9883 } 9884 9885 @Override 9886 protected boolean allowFilterResult( 9887 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9888 ServiceInfo filterSi = filter.service.info; 9889 for (int i=dest.size()-1; i>=0; i--) { 9890 ServiceInfo destAi = dest.get(i).serviceInfo; 9891 if (destAi.name == filterSi.name 9892 && destAi.packageName == filterSi.packageName) { 9893 return false; 9894 } 9895 } 9896 return true; 9897 } 9898 9899 @Override 9900 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9901 return new PackageParser.ServiceIntentInfo[size]; 9902 } 9903 9904 @Override 9905 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9906 if (!sUserManager.exists(userId)) return true; 9907 PackageParser.Package p = filter.service.owner; 9908 if (p != null) { 9909 PackageSetting ps = (PackageSetting)p.mExtras; 9910 if (ps != null) { 9911 // System apps are never considered stopped for purposes of 9912 // filtering, because there may be no way for the user to 9913 // actually re-launch them. 9914 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9915 && ps.getStopped(userId); 9916 } 9917 } 9918 return false; 9919 } 9920 9921 @Override 9922 protected boolean isPackageForFilter(String packageName, 9923 PackageParser.ServiceIntentInfo info) { 9924 return packageName.equals(info.service.owner.packageName); 9925 } 9926 9927 @Override 9928 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9929 int match, int userId) { 9930 if (!sUserManager.exists(userId)) return null; 9931 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9932 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 9933 return null; 9934 } 9935 final PackageParser.Service service = info.service; 9936 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9937 if (ps == null) { 9938 return null; 9939 } 9940 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9941 ps.readUserState(userId), userId); 9942 if (si == null) { 9943 return null; 9944 } 9945 final ResolveInfo res = new ResolveInfo(); 9946 res.serviceInfo = si; 9947 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9948 res.filter = filter; 9949 } 9950 res.priority = info.getPriority(); 9951 res.preferredOrder = service.owner.mPreferredOrder; 9952 res.match = match; 9953 res.isDefault = info.hasDefault; 9954 res.labelRes = info.labelRes; 9955 res.nonLocalizedLabel = info.nonLocalizedLabel; 9956 res.icon = info.icon; 9957 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9958 return res; 9959 } 9960 9961 @Override 9962 protected void sortResults(List<ResolveInfo> results) { 9963 Collections.sort(results, mResolvePrioritySorter); 9964 } 9965 9966 @Override 9967 protected void dumpFilter(PrintWriter out, String prefix, 9968 PackageParser.ServiceIntentInfo filter) { 9969 out.print(prefix); out.print( 9970 Integer.toHexString(System.identityHashCode(filter.service))); 9971 out.print(' '); 9972 filter.service.printComponentShortName(out); 9973 out.print(" filter "); 9974 out.println(Integer.toHexString(System.identityHashCode(filter))); 9975 } 9976 9977 @Override 9978 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9979 return filter.service; 9980 } 9981 9982 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9983 PackageParser.Service service = (PackageParser.Service)label; 9984 out.print(prefix); out.print( 9985 Integer.toHexString(System.identityHashCode(service))); 9986 out.print(' '); 9987 service.printComponentShortName(out); 9988 if (count > 1) { 9989 out.print(" ("); out.print(count); out.print(" filters)"); 9990 } 9991 out.println(); 9992 } 9993 9994// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9995// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9996// final List<ResolveInfo> retList = Lists.newArrayList(); 9997// while (i.hasNext()) { 9998// final ResolveInfo resolveInfo = (ResolveInfo) i; 9999// if (isEnabledLP(resolveInfo.serviceInfo)) { 10000// retList.add(resolveInfo); 10001// } 10002// } 10003// return retList; 10004// } 10005 10006 // Keys are String (activity class name), values are Activity. 10007 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10008 = new ArrayMap<ComponentName, PackageParser.Service>(); 10009 private int mFlags; 10010 }; 10011 10012 private final class ProviderIntentResolver 10013 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10014 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10015 boolean defaultOnly, int userId) { 10016 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10017 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10018 } 10019 10020 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10021 int userId) { 10022 if (!sUserManager.exists(userId)) 10023 return null; 10024 mFlags = flags; 10025 return super.queryIntent(intent, resolvedType, 10026 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10027 } 10028 10029 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10030 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10031 if (!sUserManager.exists(userId)) 10032 return null; 10033 if (packageProviders == null) { 10034 return null; 10035 } 10036 mFlags = flags; 10037 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10038 final int N = packageProviders.size(); 10039 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10040 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10041 10042 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10043 for (int i = 0; i < N; ++i) { 10044 intentFilters = packageProviders.get(i).intents; 10045 if (intentFilters != null && intentFilters.size() > 0) { 10046 PackageParser.ProviderIntentInfo[] array = 10047 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10048 intentFilters.toArray(array); 10049 listCut.add(array); 10050 } 10051 } 10052 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10053 } 10054 10055 public final void addProvider(PackageParser.Provider p) { 10056 if (mProviders.containsKey(p.getComponentName())) { 10057 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10058 return; 10059 } 10060 10061 mProviders.put(p.getComponentName(), p); 10062 if (DEBUG_SHOW_INFO) { 10063 Log.v(TAG, " " 10064 + (p.info.nonLocalizedLabel != null 10065 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10066 Log.v(TAG, " Class=" + p.info.name); 10067 } 10068 final int NI = p.intents.size(); 10069 int j; 10070 for (j = 0; j < NI; j++) { 10071 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10072 if (DEBUG_SHOW_INFO) { 10073 Log.v(TAG, " IntentFilter:"); 10074 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10075 } 10076 if (!intent.debugCheck()) { 10077 Log.w(TAG, "==> For Provider " + p.info.name); 10078 } 10079 addFilter(intent); 10080 } 10081 } 10082 10083 public final void removeProvider(PackageParser.Provider p) { 10084 mProviders.remove(p.getComponentName()); 10085 if (DEBUG_SHOW_INFO) { 10086 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10087 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10088 Log.v(TAG, " Class=" + p.info.name); 10089 } 10090 final int NI = p.intents.size(); 10091 int j; 10092 for (j = 0; j < NI; j++) { 10093 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10094 if (DEBUG_SHOW_INFO) { 10095 Log.v(TAG, " IntentFilter:"); 10096 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10097 } 10098 removeFilter(intent); 10099 } 10100 } 10101 10102 @Override 10103 protected boolean allowFilterResult( 10104 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10105 ProviderInfo filterPi = filter.provider.info; 10106 for (int i = dest.size() - 1; i >= 0; i--) { 10107 ProviderInfo destPi = dest.get(i).providerInfo; 10108 if (destPi.name == filterPi.name 10109 && destPi.packageName == filterPi.packageName) { 10110 return false; 10111 } 10112 } 10113 return true; 10114 } 10115 10116 @Override 10117 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10118 return new PackageParser.ProviderIntentInfo[size]; 10119 } 10120 10121 @Override 10122 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10123 if (!sUserManager.exists(userId)) 10124 return true; 10125 PackageParser.Package p = filter.provider.owner; 10126 if (p != null) { 10127 PackageSetting ps = (PackageSetting) p.mExtras; 10128 if (ps != null) { 10129 // System apps are never considered stopped for purposes of 10130 // filtering, because there may be no way for the user to 10131 // actually re-launch them. 10132 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10133 && ps.getStopped(userId); 10134 } 10135 } 10136 return false; 10137 } 10138 10139 @Override 10140 protected boolean isPackageForFilter(String packageName, 10141 PackageParser.ProviderIntentInfo info) { 10142 return packageName.equals(info.provider.owner.packageName); 10143 } 10144 10145 @Override 10146 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10147 int match, int userId) { 10148 if (!sUserManager.exists(userId)) 10149 return null; 10150 final PackageParser.ProviderIntentInfo info = filter; 10151 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10152 return null; 10153 } 10154 final PackageParser.Provider provider = info.provider; 10155 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10156 if (ps == null) { 10157 return null; 10158 } 10159 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10160 ps.readUserState(userId), userId); 10161 if (pi == null) { 10162 return null; 10163 } 10164 final ResolveInfo res = new ResolveInfo(); 10165 res.providerInfo = pi; 10166 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10167 res.filter = filter; 10168 } 10169 res.priority = info.getPriority(); 10170 res.preferredOrder = provider.owner.mPreferredOrder; 10171 res.match = match; 10172 res.isDefault = info.hasDefault; 10173 res.labelRes = info.labelRes; 10174 res.nonLocalizedLabel = info.nonLocalizedLabel; 10175 res.icon = info.icon; 10176 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10177 return res; 10178 } 10179 10180 @Override 10181 protected void sortResults(List<ResolveInfo> results) { 10182 Collections.sort(results, mResolvePrioritySorter); 10183 } 10184 10185 @Override 10186 protected void dumpFilter(PrintWriter out, String prefix, 10187 PackageParser.ProviderIntentInfo filter) { 10188 out.print(prefix); 10189 out.print( 10190 Integer.toHexString(System.identityHashCode(filter.provider))); 10191 out.print(' '); 10192 filter.provider.printComponentShortName(out); 10193 out.print(" filter "); 10194 out.println(Integer.toHexString(System.identityHashCode(filter))); 10195 } 10196 10197 @Override 10198 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 10199 return filter.provider; 10200 } 10201 10202 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10203 PackageParser.Provider provider = (PackageParser.Provider)label; 10204 out.print(prefix); out.print( 10205 Integer.toHexString(System.identityHashCode(provider))); 10206 out.print(' '); 10207 provider.printComponentShortName(out); 10208 if (count > 1) { 10209 out.print(" ("); out.print(count); out.print(" filters)"); 10210 } 10211 out.println(); 10212 } 10213 10214 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 10215 = new ArrayMap<ComponentName, PackageParser.Provider>(); 10216 private int mFlags; 10217 } 10218 10219 private static final class EphemeralIntentResolver 10220 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 10221 @Override 10222 protected EphemeralResolveIntentInfo[] newArray(int size) { 10223 return new EphemeralResolveIntentInfo[size]; 10224 } 10225 10226 @Override 10227 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 10228 return true; 10229 } 10230 10231 @Override 10232 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 10233 int userId) { 10234 if (!sUserManager.exists(userId)) { 10235 return null; 10236 } 10237 return info.getEphemeralResolveInfo(); 10238 } 10239 } 10240 10241 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 10242 new Comparator<ResolveInfo>() { 10243 public int compare(ResolveInfo r1, ResolveInfo r2) { 10244 int v1 = r1.priority; 10245 int v2 = r2.priority; 10246 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 10247 if (v1 != v2) { 10248 return (v1 > v2) ? -1 : 1; 10249 } 10250 v1 = r1.preferredOrder; 10251 v2 = r2.preferredOrder; 10252 if (v1 != v2) { 10253 return (v1 > v2) ? -1 : 1; 10254 } 10255 if (r1.isDefault != r2.isDefault) { 10256 return r1.isDefault ? -1 : 1; 10257 } 10258 v1 = r1.match; 10259 v2 = r2.match; 10260 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 10261 if (v1 != v2) { 10262 return (v1 > v2) ? -1 : 1; 10263 } 10264 if (r1.system != r2.system) { 10265 return r1.system ? -1 : 1; 10266 } 10267 if (r1.activityInfo != null) { 10268 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 10269 } 10270 if (r1.serviceInfo != null) { 10271 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 10272 } 10273 if (r1.providerInfo != null) { 10274 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 10275 } 10276 return 0; 10277 } 10278 }; 10279 10280 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 10281 new Comparator<ProviderInfo>() { 10282 public int compare(ProviderInfo p1, ProviderInfo p2) { 10283 final int v1 = p1.initOrder; 10284 final int v2 = p2.initOrder; 10285 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 10286 } 10287 }; 10288 10289 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 10290 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 10291 final int[] userIds) { 10292 mHandler.post(new Runnable() { 10293 @Override 10294 public void run() { 10295 try { 10296 final IActivityManager am = ActivityManagerNative.getDefault(); 10297 if (am == null) return; 10298 final int[] resolvedUserIds; 10299 if (userIds == null) { 10300 resolvedUserIds = am.getRunningUserIds(); 10301 } else { 10302 resolvedUserIds = userIds; 10303 } 10304 for (int id : resolvedUserIds) { 10305 final Intent intent = new Intent(action, 10306 pkg != null ? Uri.fromParts("package", pkg, null) : null); 10307 if (extras != null) { 10308 intent.putExtras(extras); 10309 } 10310 if (targetPkg != null) { 10311 intent.setPackage(targetPkg); 10312 } 10313 // Modify the UID when posting to other users 10314 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 10315 if (uid > 0 && UserHandle.getUserId(uid) != id) { 10316 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 10317 intent.putExtra(Intent.EXTRA_UID, uid); 10318 } 10319 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 10320 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 10321 if (DEBUG_BROADCASTS) { 10322 RuntimeException here = new RuntimeException("here"); 10323 here.fillInStackTrace(); 10324 Slog.d(TAG, "Sending to user " + id + ": " 10325 + intent.toShortString(false, true, false, false) 10326 + " " + intent.getExtras(), here); 10327 } 10328 am.broadcastIntent(null, intent, null, finishedReceiver, 10329 0, null, null, null, android.app.AppOpsManager.OP_NONE, 10330 null, finishedReceiver != null, false, id); 10331 } 10332 } catch (RemoteException ex) { 10333 } 10334 } 10335 }); 10336 } 10337 10338 /** 10339 * Check if the external storage media is available. This is true if there 10340 * is a mounted external storage medium or if the external storage is 10341 * emulated. 10342 */ 10343 private boolean isExternalMediaAvailable() { 10344 return mMediaMounted || Environment.isExternalStorageEmulated(); 10345 } 10346 10347 @Override 10348 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 10349 // writer 10350 synchronized (mPackages) { 10351 if (!isExternalMediaAvailable()) { 10352 // If the external storage is no longer mounted at this point, 10353 // the caller may not have been able to delete all of this 10354 // packages files and can not delete any more. Bail. 10355 return null; 10356 } 10357 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 10358 if (lastPackage != null) { 10359 pkgs.remove(lastPackage); 10360 } 10361 if (pkgs.size() > 0) { 10362 return pkgs.get(0); 10363 } 10364 } 10365 return null; 10366 } 10367 10368 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 10369 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 10370 userId, andCode ? 1 : 0, packageName); 10371 if (mSystemReady) { 10372 msg.sendToTarget(); 10373 } else { 10374 if (mPostSystemReadyMessages == null) { 10375 mPostSystemReadyMessages = new ArrayList<>(); 10376 } 10377 mPostSystemReadyMessages.add(msg); 10378 } 10379 } 10380 10381 void startCleaningPackages() { 10382 // reader 10383 synchronized (mPackages) { 10384 if (!isExternalMediaAvailable()) { 10385 return; 10386 } 10387 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 10388 return; 10389 } 10390 } 10391 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 10392 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 10393 IActivityManager am = ActivityManagerNative.getDefault(); 10394 if (am != null) { 10395 try { 10396 am.startService(null, intent, null, mContext.getOpPackageName(), 10397 UserHandle.USER_SYSTEM); 10398 } catch (RemoteException e) { 10399 } 10400 } 10401 } 10402 10403 @Override 10404 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 10405 int installFlags, String installerPackageName, int userId) { 10406 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 10407 10408 final int callingUid = Binder.getCallingUid(); 10409 enforceCrossUserPermission(callingUid, userId, 10410 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 10411 10412 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10413 try { 10414 if (observer != null) { 10415 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 10416 } 10417 } catch (RemoteException re) { 10418 } 10419 return; 10420 } 10421 10422 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 10423 installFlags |= PackageManager.INSTALL_FROM_ADB; 10424 10425 } else { 10426 // Caller holds INSTALL_PACKAGES permission, so we're less strict 10427 // about installerPackageName. 10428 10429 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 10430 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 10431 } 10432 10433 UserHandle user; 10434 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 10435 user = UserHandle.ALL; 10436 } else { 10437 user = new UserHandle(userId); 10438 } 10439 10440 // Only system components can circumvent runtime permissions when installing. 10441 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 10442 && mContext.checkCallingOrSelfPermission(Manifest.permission 10443 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 10444 throw new SecurityException("You need the " 10445 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 10446 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 10447 } 10448 10449 final File originFile = new File(originPath); 10450 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 10451 10452 final Message msg = mHandler.obtainMessage(INIT_COPY); 10453 final VerificationInfo verificationInfo = new VerificationInfo( 10454 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 10455 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 10456 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 10457 null /*packageAbiOverride*/, null /*grantedPermissions*/); 10458 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 10459 msg.obj = params; 10460 10461 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 10462 System.identityHashCode(msg.obj)); 10463 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10464 System.identityHashCode(msg.obj)); 10465 10466 mHandler.sendMessage(msg); 10467 } 10468 10469 void installStage(String packageName, File stagedDir, String stagedCid, 10470 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 10471 String installerPackageName, int installerUid, UserHandle user) { 10472 if (DEBUG_EPHEMERAL) { 10473 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10474 Slog.d(TAG, "Ephemeral install of " + packageName); 10475 } 10476 } 10477 final VerificationInfo verificationInfo = new VerificationInfo( 10478 sessionParams.originatingUri, sessionParams.referrerUri, 10479 sessionParams.originatingUid, installerUid); 10480 10481 final OriginInfo origin; 10482 if (stagedDir != null) { 10483 origin = OriginInfo.fromStagedFile(stagedDir); 10484 } else { 10485 origin = OriginInfo.fromStagedContainer(stagedCid); 10486 } 10487 10488 final Message msg = mHandler.obtainMessage(INIT_COPY); 10489 final InstallParams params = new InstallParams(origin, null, observer, 10490 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 10491 verificationInfo, user, sessionParams.abiOverride, 10492 sessionParams.grantedRuntimePermissions); 10493 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 10494 msg.obj = params; 10495 10496 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 10497 System.identityHashCode(msg.obj)); 10498 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10499 System.identityHashCode(msg.obj)); 10500 10501 mHandler.sendMessage(msg); 10502 } 10503 10504 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 10505 int userId) { 10506 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 10507 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 10508 } 10509 10510 private void sendPackageAddedForUser(String packageName, boolean isSystem, 10511 int appId, int userId) { 10512 Bundle extras = new Bundle(1); 10513 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 10514 10515 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 10516 packageName, extras, 0, null, null, new int[] {userId}); 10517 try { 10518 IActivityManager am = ActivityManagerNative.getDefault(); 10519 if (isSystem && am.isUserRunning(userId, 0)) { 10520 // The just-installed/enabled app is bundled on the system, so presumed 10521 // to be able to run automatically without needing an explicit launch. 10522 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 10523 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 10524 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 10525 .setPackage(packageName); 10526 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 10527 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 10528 } 10529 } catch (RemoteException e) { 10530 // shouldn't happen 10531 Slog.w(TAG, "Unable to bootstrap installed package", e); 10532 } 10533 } 10534 10535 @Override 10536 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 10537 int userId) { 10538 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10539 PackageSetting pkgSetting; 10540 final int uid = Binder.getCallingUid(); 10541 enforceCrossUserPermission(uid, userId, 10542 true /* requireFullPermission */, true /* checkShell */, 10543 "setApplicationHiddenSetting for user " + userId); 10544 10545 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 10546 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 10547 return false; 10548 } 10549 10550 long callingId = Binder.clearCallingIdentity(); 10551 try { 10552 boolean sendAdded = false; 10553 boolean sendRemoved = false; 10554 // writer 10555 synchronized (mPackages) { 10556 pkgSetting = mSettings.mPackages.get(packageName); 10557 if (pkgSetting == null) { 10558 return false; 10559 } 10560 if (pkgSetting.getHidden(userId) != hidden) { 10561 pkgSetting.setHidden(hidden, userId); 10562 mSettings.writePackageRestrictionsLPr(userId); 10563 if (hidden) { 10564 sendRemoved = true; 10565 } else { 10566 sendAdded = true; 10567 } 10568 } 10569 } 10570 if (sendAdded) { 10571 sendPackageAddedForUser(packageName, pkgSetting, userId); 10572 return true; 10573 } 10574 if (sendRemoved) { 10575 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 10576 "hiding pkg"); 10577 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 10578 return true; 10579 } 10580 } finally { 10581 Binder.restoreCallingIdentity(callingId); 10582 } 10583 return false; 10584 } 10585 10586 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 10587 int userId) { 10588 final PackageRemovedInfo info = new PackageRemovedInfo(); 10589 info.removedPackage = packageName; 10590 info.removedUsers = new int[] {userId}; 10591 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 10592 info.sendPackageRemovedBroadcasts(); 10593 } 10594 10595 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 10596 if (pkgList.length > 0) { 10597 Bundle extras = new Bundle(1); 10598 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 10599 10600 sendPackageBroadcast( 10601 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 10602 : Intent.ACTION_PACKAGES_UNSUSPENDED, 10603 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 10604 new int[] {userId}); 10605 } 10606 } 10607 10608 /** 10609 * Returns true if application is not found or there was an error. Otherwise it returns 10610 * the hidden state of the package for the given user. 10611 */ 10612 @Override 10613 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 10614 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10615 enforceCrossUserPermission(Binder.getCallingUid(), userId, 10616 true /* requireFullPermission */, false /* checkShell */, 10617 "getApplicationHidden for user " + userId); 10618 PackageSetting pkgSetting; 10619 long callingId = Binder.clearCallingIdentity(); 10620 try { 10621 // writer 10622 synchronized (mPackages) { 10623 pkgSetting = mSettings.mPackages.get(packageName); 10624 if (pkgSetting == null) { 10625 return true; 10626 } 10627 return pkgSetting.getHidden(userId); 10628 } 10629 } finally { 10630 Binder.restoreCallingIdentity(callingId); 10631 } 10632 } 10633 10634 /** 10635 * @hide 10636 */ 10637 @Override 10638 public int installExistingPackageAsUser(String packageName, int userId) { 10639 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 10640 null); 10641 PackageSetting pkgSetting; 10642 final int uid = Binder.getCallingUid(); 10643 enforceCrossUserPermission(uid, userId, 10644 true /* requireFullPermission */, true /* checkShell */, 10645 "installExistingPackage for user " + userId); 10646 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10647 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 10648 } 10649 10650 long callingId = Binder.clearCallingIdentity(); 10651 try { 10652 boolean installed = false; 10653 10654 // writer 10655 synchronized (mPackages) { 10656 pkgSetting = mSettings.mPackages.get(packageName); 10657 if (pkgSetting == null) { 10658 return PackageManager.INSTALL_FAILED_INVALID_URI; 10659 } 10660 if (!pkgSetting.getInstalled(userId)) { 10661 pkgSetting.setInstalled(true, userId); 10662 pkgSetting.setHidden(false, userId); 10663 mSettings.writePackageRestrictionsLPr(userId); 10664 installed = true; 10665 } 10666 } 10667 10668 if (installed) { 10669 if (pkgSetting.pkg != null) { 10670 prepareAppDataAfterInstall(pkgSetting.pkg); 10671 } 10672 sendPackageAddedForUser(packageName, pkgSetting, userId); 10673 } 10674 } finally { 10675 Binder.restoreCallingIdentity(callingId); 10676 } 10677 10678 return PackageManager.INSTALL_SUCCEEDED; 10679 } 10680 10681 boolean isUserRestricted(int userId, String restrictionKey) { 10682 Bundle restrictions = sUserManager.getUserRestrictions(userId); 10683 if (restrictions.getBoolean(restrictionKey, false)) { 10684 Log.w(TAG, "User is restricted: " + restrictionKey); 10685 return true; 10686 } 10687 return false; 10688 } 10689 10690 @Override 10691 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 10692 int userId) { 10693 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10694 enforceCrossUserPermission(Binder.getCallingUid(), userId, 10695 true /* requireFullPermission */, true /* checkShell */, 10696 "setPackagesSuspended for user " + userId); 10697 10698 if (ArrayUtils.isEmpty(packageNames)) { 10699 return packageNames; 10700 } 10701 10702 // List of package names for whom the suspended state has changed. 10703 List<String> changedPackages = new ArrayList<>(packageNames.length); 10704 // List of package names for whom the suspended state is not set as requested in this 10705 // method. 10706 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 10707 for (int i = 0; i < packageNames.length; i++) { 10708 String packageName = packageNames[i]; 10709 long callingId = Binder.clearCallingIdentity(); 10710 try { 10711 boolean changed = false; 10712 final int appId; 10713 synchronized (mPackages) { 10714 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10715 if (pkgSetting == null) { 10716 Slog.w(TAG, "Could not find package setting for package \"" + packageName 10717 + "\". Skipping suspending/un-suspending."); 10718 unactionedPackages.add(packageName); 10719 continue; 10720 } 10721 appId = pkgSetting.appId; 10722 if (pkgSetting.getSuspended(userId) != suspended) { 10723 if (!canSuspendPackageForUserLocked(packageName, userId)) { 10724 unactionedPackages.add(packageName); 10725 continue; 10726 } 10727 pkgSetting.setSuspended(suspended, userId); 10728 mSettings.writePackageRestrictionsLPr(userId); 10729 changed = true; 10730 changedPackages.add(packageName); 10731 } 10732 } 10733 10734 if (changed && suspended) { 10735 killApplication(packageName, UserHandle.getUid(userId, appId), 10736 "suspending package"); 10737 } 10738 } finally { 10739 Binder.restoreCallingIdentity(callingId); 10740 } 10741 } 10742 10743 if (!changedPackages.isEmpty()) { 10744 sendPackagesSuspendedForUser(changedPackages.toArray( 10745 new String[changedPackages.size()]), userId, suspended); 10746 } 10747 10748 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 10749 } 10750 10751 @Override 10752 public boolean isPackageSuspendedForUser(String packageName, int userId) { 10753 enforceCrossUserPermission(Binder.getCallingUid(), userId, 10754 true /* requireFullPermission */, false /* checkShell */, 10755 "isPackageSuspendedForUser for user " + userId); 10756 synchronized (mPackages) { 10757 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10758 return pkgSetting != null && pkgSetting.getSuspended(userId); 10759 } 10760 } 10761 10762 // TODO: investigate and add more restrictions for suspending crucial packages. 10763 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 10764 if (isPackageDeviceAdmin(packageName, userId)) { 10765 Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName 10766 + "\": has active device admin"); 10767 return false; 10768 } 10769 10770 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 10771 if (packageName.equals(activeLauncherPackageName)) { 10772 Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName 10773 + "\" because it is set as the active launcher"); 10774 return false; 10775 } 10776 10777 final PackageParser.Package pkg = mPackages.get(packageName); 10778 if (pkg != null && isPrivilegedApp(pkg)) { 10779 Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName 10780 + "\" because it is a privileged app"); 10781 return false; 10782 } 10783 10784 return true; 10785 } 10786 10787 private String getActiveLauncherPackageName(int userId) { 10788 Intent intent = new Intent(Intent.ACTION_MAIN); 10789 intent.addCategory(Intent.CATEGORY_HOME); 10790 ResolveInfo resolveInfo = resolveIntent( 10791 intent, 10792 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 10793 PackageManager.MATCH_DEFAULT_ONLY, 10794 userId); 10795 10796 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 10797 } 10798 10799 @Override 10800 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 10801 mContext.enforceCallingOrSelfPermission( 10802 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10803 "Only package verification agents can verify applications"); 10804 10805 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10806 final PackageVerificationResponse response = new PackageVerificationResponse( 10807 verificationCode, Binder.getCallingUid()); 10808 msg.arg1 = id; 10809 msg.obj = response; 10810 mHandler.sendMessage(msg); 10811 } 10812 10813 @Override 10814 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 10815 long millisecondsToDelay) { 10816 mContext.enforceCallingOrSelfPermission( 10817 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10818 "Only package verification agents can extend verification timeouts"); 10819 10820 final PackageVerificationState state = mPendingVerification.get(id); 10821 final PackageVerificationResponse response = new PackageVerificationResponse( 10822 verificationCodeAtTimeout, Binder.getCallingUid()); 10823 10824 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 10825 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 10826 } 10827 if (millisecondsToDelay < 0) { 10828 millisecondsToDelay = 0; 10829 } 10830 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 10831 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 10832 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 10833 } 10834 10835 if ((state != null) && !state.timeoutExtended()) { 10836 state.extendTimeout(); 10837 10838 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10839 msg.arg1 = id; 10840 msg.obj = response; 10841 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 10842 } 10843 } 10844 10845 private void broadcastPackageVerified(int verificationId, Uri packageUri, 10846 int verificationCode, UserHandle user) { 10847 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 10848 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 10849 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10850 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10851 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 10852 10853 mContext.sendBroadcastAsUser(intent, user, 10854 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 10855 } 10856 10857 private ComponentName matchComponentForVerifier(String packageName, 10858 List<ResolveInfo> receivers) { 10859 ActivityInfo targetReceiver = null; 10860 10861 final int NR = receivers.size(); 10862 for (int i = 0; i < NR; i++) { 10863 final ResolveInfo info = receivers.get(i); 10864 if (info.activityInfo == null) { 10865 continue; 10866 } 10867 10868 if (packageName.equals(info.activityInfo.packageName)) { 10869 targetReceiver = info.activityInfo; 10870 break; 10871 } 10872 } 10873 10874 if (targetReceiver == null) { 10875 return null; 10876 } 10877 10878 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 10879 } 10880 10881 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 10882 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 10883 if (pkgInfo.verifiers.length == 0) { 10884 return null; 10885 } 10886 10887 final int N = pkgInfo.verifiers.length; 10888 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 10889 for (int i = 0; i < N; i++) { 10890 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 10891 10892 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 10893 receivers); 10894 if (comp == null) { 10895 continue; 10896 } 10897 10898 final int verifierUid = getUidForVerifier(verifierInfo); 10899 if (verifierUid == -1) { 10900 continue; 10901 } 10902 10903 if (DEBUG_VERIFY) { 10904 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 10905 + " with the correct signature"); 10906 } 10907 sufficientVerifiers.add(comp); 10908 verificationState.addSufficientVerifier(verifierUid); 10909 } 10910 10911 return sufficientVerifiers; 10912 } 10913 10914 private int getUidForVerifier(VerifierInfo verifierInfo) { 10915 synchronized (mPackages) { 10916 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 10917 if (pkg == null) { 10918 return -1; 10919 } else if (pkg.mSignatures.length != 1) { 10920 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10921 + " has more than one signature; ignoring"); 10922 return -1; 10923 } 10924 10925 /* 10926 * If the public key of the package's signature does not match 10927 * our expected public key, then this is a different package and 10928 * we should skip. 10929 */ 10930 10931 final byte[] expectedPublicKey; 10932 try { 10933 final Signature verifierSig = pkg.mSignatures[0]; 10934 final PublicKey publicKey = verifierSig.getPublicKey(); 10935 expectedPublicKey = publicKey.getEncoded(); 10936 } catch (CertificateException e) { 10937 return -1; 10938 } 10939 10940 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 10941 10942 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 10943 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10944 + " does not have the expected public key; ignoring"); 10945 return -1; 10946 } 10947 10948 return pkg.applicationInfo.uid; 10949 } 10950 } 10951 10952 @Override 10953 public void finishPackageInstall(int token) { 10954 enforceSystemOrRoot("Only the system is allowed to finish installs"); 10955 10956 if (DEBUG_INSTALL) { 10957 Slog.v(TAG, "BM finishing package install for " + token); 10958 } 10959 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10960 10961 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10962 mHandler.sendMessage(msg); 10963 } 10964 10965 /** 10966 * Get the verification agent timeout. 10967 * 10968 * @return verification timeout in milliseconds 10969 */ 10970 private long getVerificationTimeout() { 10971 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 10972 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 10973 DEFAULT_VERIFICATION_TIMEOUT); 10974 } 10975 10976 /** 10977 * Get the default verification agent response code. 10978 * 10979 * @return default verification response code 10980 */ 10981 private int getDefaultVerificationResponse() { 10982 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10983 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 10984 DEFAULT_VERIFICATION_RESPONSE); 10985 } 10986 10987 /** 10988 * Check whether or not package verification has been enabled. 10989 * 10990 * @return true if verification should be performed 10991 */ 10992 private boolean isVerificationEnabled(int userId, int installFlags) { 10993 if (!DEFAULT_VERIFY_ENABLE) { 10994 return false; 10995 } 10996 // Ephemeral apps don't get the full verification treatment 10997 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10998 if (DEBUG_EPHEMERAL) { 10999 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11000 } 11001 return false; 11002 } 11003 11004 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11005 11006 // Check if installing from ADB 11007 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11008 // Do not run verification in a test harness environment 11009 if (ActivityManager.isRunningInTestHarness()) { 11010 return false; 11011 } 11012 if (ensureVerifyAppsEnabled) { 11013 return true; 11014 } 11015 // Check if the developer does not want package verification for ADB installs 11016 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11017 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11018 return false; 11019 } 11020 } 11021 11022 if (ensureVerifyAppsEnabled) { 11023 return true; 11024 } 11025 11026 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11027 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11028 } 11029 11030 @Override 11031 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11032 throws RemoteException { 11033 mContext.enforceCallingOrSelfPermission( 11034 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11035 "Only intentfilter verification agents can verify applications"); 11036 11037 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11038 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11039 Binder.getCallingUid(), verificationCode, failedDomains); 11040 msg.arg1 = id; 11041 msg.obj = response; 11042 mHandler.sendMessage(msg); 11043 } 11044 11045 @Override 11046 public int getIntentVerificationStatus(String packageName, int userId) { 11047 synchronized (mPackages) { 11048 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11049 } 11050 } 11051 11052 @Override 11053 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11054 mContext.enforceCallingOrSelfPermission( 11055 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11056 11057 boolean result = false; 11058 synchronized (mPackages) { 11059 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11060 } 11061 if (result) { 11062 scheduleWritePackageRestrictionsLocked(userId); 11063 } 11064 return result; 11065 } 11066 11067 @Override 11068 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 11069 synchronized (mPackages) { 11070 return mSettings.getIntentFilterVerificationsLPr(packageName); 11071 } 11072 } 11073 11074 @Override 11075 public List<IntentFilter> getAllIntentFilters(String packageName) { 11076 if (TextUtils.isEmpty(packageName)) { 11077 return Collections.<IntentFilter>emptyList(); 11078 } 11079 synchronized (mPackages) { 11080 PackageParser.Package pkg = mPackages.get(packageName); 11081 if (pkg == null || pkg.activities == null) { 11082 return Collections.<IntentFilter>emptyList(); 11083 } 11084 final int count = pkg.activities.size(); 11085 ArrayList<IntentFilter> result = new ArrayList<>(); 11086 for (int n=0; n<count; n++) { 11087 PackageParser.Activity activity = pkg.activities.get(n); 11088 if (activity.intents != null && activity.intents.size() > 0) { 11089 result.addAll(activity.intents); 11090 } 11091 } 11092 return result; 11093 } 11094 } 11095 11096 @Override 11097 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11098 mContext.enforceCallingOrSelfPermission( 11099 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11100 11101 synchronized (mPackages) { 11102 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11103 if (packageName != null) { 11104 result |= updateIntentVerificationStatus(packageName, 11105 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11106 userId); 11107 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11108 packageName, userId); 11109 } 11110 return result; 11111 } 11112 } 11113 11114 @Override 11115 public String getDefaultBrowserPackageName(int userId) { 11116 synchronized (mPackages) { 11117 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11118 } 11119 } 11120 11121 /** 11122 * Get the "allow unknown sources" setting. 11123 * 11124 * @return the current "allow unknown sources" setting 11125 */ 11126 private int getUnknownSourcesSettings() { 11127 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11128 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 11129 -1); 11130 } 11131 11132 @Override 11133 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11134 final int uid = Binder.getCallingUid(); 11135 // writer 11136 synchronized (mPackages) { 11137 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11138 if (targetPackageSetting == null) { 11139 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11140 } 11141 11142 PackageSetting installerPackageSetting; 11143 if (installerPackageName != null) { 11144 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11145 if (installerPackageSetting == null) { 11146 throw new IllegalArgumentException("Unknown installer package: " 11147 + installerPackageName); 11148 } 11149 } else { 11150 installerPackageSetting = null; 11151 } 11152 11153 Signature[] callerSignature; 11154 Object obj = mSettings.getUserIdLPr(uid); 11155 if (obj != null) { 11156 if (obj instanceof SharedUserSetting) { 11157 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11158 } else if (obj instanceof PackageSetting) { 11159 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11160 } else { 11161 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11162 } 11163 } else { 11164 throw new SecurityException("Unknown calling UID: " + uid); 11165 } 11166 11167 // Verify: can't set installerPackageName to a package that is 11168 // not signed with the same cert as the caller. 11169 if (installerPackageSetting != null) { 11170 if (compareSignatures(callerSignature, 11171 installerPackageSetting.signatures.mSignatures) 11172 != PackageManager.SIGNATURE_MATCH) { 11173 throw new SecurityException( 11174 "Caller does not have same cert as new installer package " 11175 + installerPackageName); 11176 } 11177 } 11178 11179 // Verify: if target already has an installer package, it must 11180 // be signed with the same cert as the caller. 11181 if (targetPackageSetting.installerPackageName != null) { 11182 PackageSetting setting = mSettings.mPackages.get( 11183 targetPackageSetting.installerPackageName); 11184 // If the currently set package isn't valid, then it's always 11185 // okay to change it. 11186 if (setting != null) { 11187 if (compareSignatures(callerSignature, 11188 setting.signatures.mSignatures) 11189 != PackageManager.SIGNATURE_MATCH) { 11190 throw new SecurityException( 11191 "Caller does not have same cert as old installer package " 11192 + targetPackageSetting.installerPackageName); 11193 } 11194 } 11195 } 11196 11197 // Okay! 11198 targetPackageSetting.installerPackageName = installerPackageName; 11199 scheduleWriteSettingsLocked(); 11200 } 11201 } 11202 11203 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 11204 // Queue up an async operation since the package installation may take a little while. 11205 mHandler.post(new Runnable() { 11206 public void run() { 11207 mHandler.removeCallbacks(this); 11208 // Result object to be returned 11209 PackageInstalledInfo res = new PackageInstalledInfo(); 11210 res.setReturnCode(currentStatus); 11211 res.uid = -1; 11212 res.pkg = null; 11213 res.removedInfo = null; 11214 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11215 args.doPreInstall(res.returnCode); 11216 synchronized (mInstallLock) { 11217 installPackageTracedLI(args, res); 11218 } 11219 args.doPostInstall(res.returnCode, res.uid); 11220 } 11221 11222 // A restore should be performed at this point if (a) the install 11223 // succeeded, (b) the operation is not an update, and (c) the new 11224 // package has not opted out of backup participation. 11225 final boolean update = res.removedInfo != null 11226 && res.removedInfo.removedPackage != null; 11227 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 11228 boolean doRestore = !update 11229 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 11230 11231 // Set up the post-install work request bookkeeping. This will be used 11232 // and cleaned up by the post-install event handling regardless of whether 11233 // there's a restore pass performed. Token values are >= 1. 11234 int token; 11235 if (mNextInstallToken < 0) mNextInstallToken = 1; 11236 token = mNextInstallToken++; 11237 11238 PostInstallData data = new PostInstallData(args, res); 11239 mRunningInstalls.put(token, data); 11240 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 11241 11242 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 11243 // Pass responsibility to the Backup Manager. It will perform a 11244 // restore if appropriate, then pass responsibility back to the 11245 // Package Manager to run the post-install observer callbacks 11246 // and broadcasts. 11247 IBackupManager bm = IBackupManager.Stub.asInterface( 11248 ServiceManager.getService(Context.BACKUP_SERVICE)); 11249 if (bm != null) { 11250 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 11251 + " to BM for possible restore"); 11252 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11253 try { 11254 // TODO: http://b/22388012 11255 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 11256 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 11257 } else { 11258 doRestore = false; 11259 } 11260 } catch (RemoteException e) { 11261 // can't happen; the backup manager is local 11262 } catch (Exception e) { 11263 Slog.e(TAG, "Exception trying to enqueue restore", e); 11264 doRestore = false; 11265 } 11266 } else { 11267 Slog.e(TAG, "Backup Manager not found!"); 11268 doRestore = false; 11269 } 11270 } 11271 11272 if (!doRestore) { 11273 // No restore possible, or the Backup Manager was mysteriously not 11274 // available -- just fire the post-install work request directly. 11275 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 11276 11277 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 11278 11279 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11280 mHandler.sendMessage(msg); 11281 } 11282 } 11283 }); 11284 } 11285 11286 private abstract class HandlerParams { 11287 private static final int MAX_RETRIES = 4; 11288 11289 /** 11290 * Number of times startCopy() has been attempted and had a non-fatal 11291 * error. 11292 */ 11293 private int mRetries = 0; 11294 11295 /** User handle for the user requesting the information or installation. */ 11296 private final UserHandle mUser; 11297 String traceMethod; 11298 int traceCookie; 11299 11300 HandlerParams(UserHandle user) { 11301 mUser = user; 11302 } 11303 11304 UserHandle getUser() { 11305 return mUser; 11306 } 11307 11308 HandlerParams setTraceMethod(String traceMethod) { 11309 this.traceMethod = traceMethod; 11310 return this; 11311 } 11312 11313 HandlerParams setTraceCookie(int traceCookie) { 11314 this.traceCookie = traceCookie; 11315 return this; 11316 } 11317 11318 final boolean startCopy() { 11319 boolean res; 11320 try { 11321 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 11322 11323 if (++mRetries > MAX_RETRIES) { 11324 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 11325 mHandler.sendEmptyMessage(MCS_GIVE_UP); 11326 handleServiceError(); 11327 return false; 11328 } else { 11329 handleStartCopy(); 11330 res = true; 11331 } 11332 } catch (RemoteException e) { 11333 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 11334 mHandler.sendEmptyMessage(MCS_RECONNECT); 11335 res = false; 11336 } 11337 handleReturnCode(); 11338 return res; 11339 } 11340 11341 final void serviceError() { 11342 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 11343 handleServiceError(); 11344 handleReturnCode(); 11345 } 11346 11347 abstract void handleStartCopy() throws RemoteException; 11348 abstract void handleServiceError(); 11349 abstract void handleReturnCode(); 11350 } 11351 11352 class MeasureParams extends HandlerParams { 11353 private final PackageStats mStats; 11354 private boolean mSuccess; 11355 11356 private final IPackageStatsObserver mObserver; 11357 11358 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 11359 super(new UserHandle(stats.userHandle)); 11360 mObserver = observer; 11361 mStats = stats; 11362 } 11363 11364 @Override 11365 public String toString() { 11366 return "MeasureParams{" 11367 + Integer.toHexString(System.identityHashCode(this)) 11368 + " " + mStats.packageName + "}"; 11369 } 11370 11371 @Override 11372 void handleStartCopy() throws RemoteException { 11373 synchronized (mInstallLock) { 11374 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 11375 } 11376 11377 if (mSuccess) { 11378 final boolean mounted; 11379 if (Environment.isExternalStorageEmulated()) { 11380 mounted = true; 11381 } else { 11382 final String status = Environment.getExternalStorageState(); 11383 mounted = (Environment.MEDIA_MOUNTED.equals(status) 11384 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 11385 } 11386 11387 if (mounted) { 11388 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 11389 11390 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 11391 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 11392 11393 mStats.externalDataSize = calculateDirectorySize(mContainerService, 11394 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 11395 11396 // Always subtract cache size, since it's a subdirectory 11397 mStats.externalDataSize -= mStats.externalCacheSize; 11398 11399 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 11400 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 11401 11402 mStats.externalObbSize = calculateDirectorySize(mContainerService, 11403 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 11404 } 11405 } 11406 } 11407 11408 @Override 11409 void handleReturnCode() { 11410 if (mObserver != null) { 11411 try { 11412 mObserver.onGetStatsCompleted(mStats, mSuccess); 11413 } catch (RemoteException e) { 11414 Slog.i(TAG, "Observer no longer exists."); 11415 } 11416 } 11417 } 11418 11419 @Override 11420 void handleServiceError() { 11421 Slog.e(TAG, "Could not measure application " + mStats.packageName 11422 + " external storage"); 11423 } 11424 } 11425 11426 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 11427 throws RemoteException { 11428 long result = 0; 11429 for (File path : paths) { 11430 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 11431 } 11432 return result; 11433 } 11434 11435 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 11436 for (File path : paths) { 11437 try { 11438 mcs.clearDirectory(path.getAbsolutePath()); 11439 } catch (RemoteException e) { 11440 } 11441 } 11442 } 11443 11444 static class OriginInfo { 11445 /** 11446 * Location where install is coming from, before it has been 11447 * copied/renamed into place. This could be a single monolithic APK 11448 * file, or a cluster directory. This location may be untrusted. 11449 */ 11450 final File file; 11451 final String cid; 11452 11453 /** 11454 * Flag indicating that {@link #file} or {@link #cid} has already been 11455 * staged, meaning downstream users don't need to defensively copy the 11456 * contents. 11457 */ 11458 final boolean staged; 11459 11460 /** 11461 * Flag indicating that {@link #file} or {@link #cid} is an already 11462 * installed app that is being moved. 11463 */ 11464 final boolean existing; 11465 11466 final String resolvedPath; 11467 final File resolvedFile; 11468 11469 static OriginInfo fromNothing() { 11470 return new OriginInfo(null, null, false, false); 11471 } 11472 11473 static OriginInfo fromUntrustedFile(File file) { 11474 return new OriginInfo(file, null, false, false); 11475 } 11476 11477 static OriginInfo fromExistingFile(File file) { 11478 return new OriginInfo(file, null, false, true); 11479 } 11480 11481 static OriginInfo fromStagedFile(File file) { 11482 return new OriginInfo(file, null, true, false); 11483 } 11484 11485 static OriginInfo fromStagedContainer(String cid) { 11486 return new OriginInfo(null, cid, true, false); 11487 } 11488 11489 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 11490 this.file = file; 11491 this.cid = cid; 11492 this.staged = staged; 11493 this.existing = existing; 11494 11495 if (cid != null) { 11496 resolvedPath = PackageHelper.getSdDir(cid); 11497 resolvedFile = new File(resolvedPath); 11498 } else if (file != null) { 11499 resolvedPath = file.getAbsolutePath(); 11500 resolvedFile = file; 11501 } else { 11502 resolvedPath = null; 11503 resolvedFile = null; 11504 } 11505 } 11506 } 11507 11508 static class MoveInfo { 11509 final int moveId; 11510 final String fromUuid; 11511 final String toUuid; 11512 final String packageName; 11513 final String dataAppName; 11514 final int appId; 11515 final String seinfo; 11516 final int targetSdkVersion; 11517 11518 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 11519 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 11520 this.moveId = moveId; 11521 this.fromUuid = fromUuid; 11522 this.toUuid = toUuid; 11523 this.packageName = packageName; 11524 this.dataAppName = dataAppName; 11525 this.appId = appId; 11526 this.seinfo = seinfo; 11527 this.targetSdkVersion = targetSdkVersion; 11528 } 11529 } 11530 11531 static class VerificationInfo { 11532 /** A constant used to indicate that a uid value is not present. */ 11533 public static final int NO_UID = -1; 11534 11535 /** URI referencing where the package was downloaded from. */ 11536 final Uri originatingUri; 11537 11538 /** HTTP referrer URI associated with the originatingURI. */ 11539 final Uri referrer; 11540 11541 /** UID of the application that the install request originated from. */ 11542 final int originatingUid; 11543 11544 /** UID of application requesting the install */ 11545 final int installerUid; 11546 11547 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 11548 this.originatingUri = originatingUri; 11549 this.referrer = referrer; 11550 this.originatingUid = originatingUid; 11551 this.installerUid = installerUid; 11552 } 11553 } 11554 11555 class InstallParams extends HandlerParams { 11556 final OriginInfo origin; 11557 final MoveInfo move; 11558 final IPackageInstallObserver2 observer; 11559 int installFlags; 11560 final String installerPackageName; 11561 final String volumeUuid; 11562 private InstallArgs mArgs; 11563 private int mRet; 11564 final String packageAbiOverride; 11565 final String[] grantedRuntimePermissions; 11566 final VerificationInfo verificationInfo; 11567 11568 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11569 int installFlags, String installerPackageName, String volumeUuid, 11570 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 11571 String[] grantedPermissions) { 11572 super(user); 11573 this.origin = origin; 11574 this.move = move; 11575 this.observer = observer; 11576 this.installFlags = installFlags; 11577 this.installerPackageName = installerPackageName; 11578 this.volumeUuid = volumeUuid; 11579 this.verificationInfo = verificationInfo; 11580 this.packageAbiOverride = packageAbiOverride; 11581 this.grantedRuntimePermissions = grantedPermissions; 11582 } 11583 11584 @Override 11585 public String toString() { 11586 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 11587 + " file=" + origin.file + " cid=" + origin.cid + "}"; 11588 } 11589 11590 private int installLocationPolicy(PackageInfoLite pkgLite) { 11591 String packageName = pkgLite.packageName; 11592 int installLocation = pkgLite.installLocation; 11593 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11594 // reader 11595 synchronized (mPackages) { 11596 // Currently installed package which the new package is attempting to replace or 11597 // null if no such package is installed. 11598 PackageParser.Package installedPkg = mPackages.get(packageName); 11599 // Package which currently owns the data which the new package will own if installed. 11600 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 11601 // will be null whereas dataOwnerPkg will contain information about the package 11602 // which was uninstalled while keeping its data. 11603 PackageParser.Package dataOwnerPkg = installedPkg; 11604 if (dataOwnerPkg == null) { 11605 PackageSetting ps = mSettings.mPackages.get(packageName); 11606 if (ps != null) { 11607 dataOwnerPkg = ps.pkg; 11608 } 11609 } 11610 11611 if (dataOwnerPkg != null) { 11612 // If installed, the package will get access to data left on the device by its 11613 // predecessor. As a security measure, this is permited only if this is not a 11614 // version downgrade or if the predecessor package is marked as debuggable and 11615 // a downgrade is explicitly requested. 11616 if (((dataOwnerPkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) 11617 || ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0)) { 11618 try { 11619 checkDowngrade(dataOwnerPkg, pkgLite); 11620 } catch (PackageManagerException e) { 11621 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 11622 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 11623 } 11624 } 11625 } 11626 11627 if (installedPkg != null) { 11628 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11629 // Check for updated system application. 11630 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11631 if (onSd) { 11632 Slog.w(TAG, "Cannot install update to system app on sdcard"); 11633 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 11634 } 11635 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11636 } else { 11637 if (onSd) { 11638 // Install flag overrides everything. 11639 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11640 } 11641 // If current upgrade specifies particular preference 11642 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 11643 // Application explicitly specified internal. 11644 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11645 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 11646 // App explictly prefers external. Let policy decide 11647 } else { 11648 // Prefer previous location 11649 if (isExternal(installedPkg)) { 11650 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11651 } 11652 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11653 } 11654 } 11655 } else { 11656 // Invalid install. Return error code 11657 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 11658 } 11659 } 11660 } 11661 // All the special cases have been taken care of. 11662 // Return result based on recommended install location. 11663 if (onSd) { 11664 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11665 } 11666 return pkgLite.recommendedInstallLocation; 11667 } 11668 11669 /* 11670 * Invoke remote method to get package information and install 11671 * location values. Override install location based on default 11672 * policy if needed and then create install arguments based 11673 * on the install location. 11674 */ 11675 public void handleStartCopy() throws RemoteException { 11676 int ret = PackageManager.INSTALL_SUCCEEDED; 11677 11678 // If we're already staged, we've firmly committed to an install location 11679 if (origin.staged) { 11680 if (origin.file != null) { 11681 installFlags |= PackageManager.INSTALL_INTERNAL; 11682 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11683 } else if (origin.cid != null) { 11684 installFlags |= PackageManager.INSTALL_EXTERNAL; 11685 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11686 } else { 11687 throw new IllegalStateException("Invalid stage location"); 11688 } 11689 } 11690 11691 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11692 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 11693 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11694 PackageInfoLite pkgLite = null; 11695 11696 if (onInt && onSd) { 11697 // Check if both bits are set. 11698 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 11699 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11700 } else if (onSd && ephemeral) { 11701 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 11702 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11703 } else { 11704 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 11705 packageAbiOverride); 11706 11707 if (DEBUG_EPHEMERAL && ephemeral) { 11708 Slog.v(TAG, "pkgLite for install: " + pkgLite); 11709 } 11710 11711 /* 11712 * If we have too little free space, try to free cache 11713 * before giving up. 11714 */ 11715 if (!origin.staged && pkgLite.recommendedInstallLocation 11716 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11717 // TODO: focus freeing disk space on the target device 11718 final StorageManager storage = StorageManager.from(mContext); 11719 final long lowThreshold = storage.getStorageLowBytes( 11720 Environment.getDataDirectory()); 11721 11722 final long sizeBytes = mContainerService.calculateInstalledSize( 11723 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 11724 11725 try { 11726 mInstaller.freeCache(null, sizeBytes + lowThreshold); 11727 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 11728 installFlags, packageAbiOverride); 11729 } catch (InstallerException e) { 11730 Slog.w(TAG, "Failed to free cache", e); 11731 } 11732 11733 /* 11734 * The cache free must have deleted the file we 11735 * downloaded to install. 11736 * 11737 * TODO: fix the "freeCache" call to not delete 11738 * the file we care about. 11739 */ 11740 if (pkgLite.recommendedInstallLocation 11741 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11742 pkgLite.recommendedInstallLocation 11743 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 11744 } 11745 } 11746 } 11747 11748 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11749 int loc = pkgLite.recommendedInstallLocation; 11750 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 11751 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11752 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 11753 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 11754 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11755 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11756 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 11757 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 11758 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11759 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 11760 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 11761 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 11762 } else { 11763 // Override with defaults if needed. 11764 loc = installLocationPolicy(pkgLite); 11765 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 11766 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 11767 } else if (!onSd && !onInt) { 11768 // Override install location with flags 11769 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 11770 // Set the flag to install on external media. 11771 installFlags |= PackageManager.INSTALL_EXTERNAL; 11772 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11773 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 11774 if (DEBUG_EPHEMERAL) { 11775 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 11776 } 11777 installFlags |= PackageManager.INSTALL_EPHEMERAL; 11778 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 11779 |PackageManager.INSTALL_INTERNAL); 11780 } else { 11781 // Make sure the flag for installing on external 11782 // media is unset 11783 installFlags |= PackageManager.INSTALL_INTERNAL; 11784 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11785 } 11786 } 11787 } 11788 } 11789 11790 final InstallArgs args = createInstallArgs(this); 11791 mArgs = args; 11792 11793 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11794 // TODO: http://b/22976637 11795 // Apps installed for "all" users use the device owner to verify the app 11796 UserHandle verifierUser = getUser(); 11797 if (verifierUser == UserHandle.ALL) { 11798 verifierUser = UserHandle.SYSTEM; 11799 } 11800 11801 /* 11802 * Determine if we have any installed package verifiers. If we 11803 * do, then we'll defer to them to verify the packages. 11804 */ 11805 final int requiredUid = mRequiredVerifierPackage == null ? -1 11806 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 11807 verifierUser.getIdentifier()); 11808 if (!origin.existing && requiredUid != -1 11809 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 11810 final Intent verification = new Intent( 11811 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 11812 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 11813 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 11814 PACKAGE_MIME_TYPE); 11815 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11816 11817 // Query all live verifiers based on current user state 11818 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 11819 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 11820 11821 if (DEBUG_VERIFY) { 11822 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 11823 + verification.toString() + " with " + pkgLite.verifiers.length 11824 + " optional verifiers"); 11825 } 11826 11827 final int verificationId = mPendingVerificationToken++; 11828 11829 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11830 11831 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 11832 installerPackageName); 11833 11834 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 11835 installFlags); 11836 11837 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 11838 pkgLite.packageName); 11839 11840 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 11841 pkgLite.versionCode); 11842 11843 if (verificationInfo != null) { 11844 if (verificationInfo.originatingUri != null) { 11845 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 11846 verificationInfo.originatingUri); 11847 } 11848 if (verificationInfo.referrer != null) { 11849 verification.putExtra(Intent.EXTRA_REFERRER, 11850 verificationInfo.referrer); 11851 } 11852 if (verificationInfo.originatingUid >= 0) { 11853 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 11854 verificationInfo.originatingUid); 11855 } 11856 if (verificationInfo.installerUid >= 0) { 11857 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 11858 verificationInfo.installerUid); 11859 } 11860 } 11861 11862 final PackageVerificationState verificationState = new PackageVerificationState( 11863 requiredUid, args); 11864 11865 mPendingVerification.append(verificationId, verificationState); 11866 11867 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 11868 receivers, verificationState); 11869 11870 /* 11871 * If any sufficient verifiers were listed in the package 11872 * manifest, attempt to ask them. 11873 */ 11874 if (sufficientVerifiers != null) { 11875 final int N = sufficientVerifiers.size(); 11876 if (N == 0) { 11877 Slog.i(TAG, "Additional verifiers required, but none installed."); 11878 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 11879 } else { 11880 for (int i = 0; i < N; i++) { 11881 final ComponentName verifierComponent = sufficientVerifiers.get(i); 11882 11883 final Intent sufficientIntent = new Intent(verification); 11884 sufficientIntent.setComponent(verifierComponent); 11885 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 11886 } 11887 } 11888 } 11889 11890 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 11891 mRequiredVerifierPackage, receivers); 11892 if (ret == PackageManager.INSTALL_SUCCEEDED 11893 && mRequiredVerifierPackage != null) { 11894 Trace.asyncTraceBegin( 11895 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 11896 /* 11897 * Send the intent to the required verification agent, 11898 * but only start the verification timeout after the 11899 * target BroadcastReceivers have run. 11900 */ 11901 verification.setComponent(requiredVerifierComponent); 11902 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 11903 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11904 new BroadcastReceiver() { 11905 @Override 11906 public void onReceive(Context context, Intent intent) { 11907 final Message msg = mHandler 11908 .obtainMessage(CHECK_PENDING_VERIFICATION); 11909 msg.arg1 = verificationId; 11910 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 11911 } 11912 }, null, 0, null, null); 11913 11914 /* 11915 * We don't want the copy to proceed until verification 11916 * succeeds, so null out this field. 11917 */ 11918 mArgs = null; 11919 } 11920 } else { 11921 /* 11922 * No package verification is enabled, so immediately start 11923 * the remote call to initiate copy using temporary file. 11924 */ 11925 ret = args.copyApk(mContainerService, true); 11926 } 11927 } 11928 11929 mRet = ret; 11930 } 11931 11932 @Override 11933 void handleReturnCode() { 11934 // If mArgs is null, then MCS couldn't be reached. When it 11935 // reconnects, it will try again to install. At that point, this 11936 // will succeed. 11937 if (mArgs != null) { 11938 processPendingInstall(mArgs, mRet); 11939 } 11940 } 11941 11942 @Override 11943 void handleServiceError() { 11944 mArgs = createInstallArgs(this); 11945 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11946 } 11947 11948 public boolean isForwardLocked() { 11949 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11950 } 11951 } 11952 11953 /** 11954 * Used during creation of InstallArgs 11955 * 11956 * @param installFlags package installation flags 11957 * @return true if should be installed on external storage 11958 */ 11959 private static boolean installOnExternalAsec(int installFlags) { 11960 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 11961 return false; 11962 } 11963 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 11964 return true; 11965 } 11966 return false; 11967 } 11968 11969 /** 11970 * Used during creation of InstallArgs 11971 * 11972 * @param installFlags package installation flags 11973 * @return true if should be installed as forward locked 11974 */ 11975 private static boolean installForwardLocked(int installFlags) { 11976 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11977 } 11978 11979 private InstallArgs createInstallArgs(InstallParams params) { 11980 if (params.move != null) { 11981 return new MoveInstallArgs(params); 11982 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 11983 return new AsecInstallArgs(params); 11984 } else { 11985 return new FileInstallArgs(params); 11986 } 11987 } 11988 11989 /** 11990 * Create args that describe an existing installed package. Typically used 11991 * when cleaning up old installs, or used as a move source. 11992 */ 11993 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 11994 String resourcePath, String[] instructionSets) { 11995 final boolean isInAsec; 11996 if (installOnExternalAsec(installFlags)) { 11997 /* Apps on SD card are always in ASEC containers. */ 11998 isInAsec = true; 11999 } else if (installForwardLocked(installFlags) 12000 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12001 /* 12002 * Forward-locked apps are only in ASEC containers if they're the 12003 * new style 12004 */ 12005 isInAsec = true; 12006 } else { 12007 isInAsec = false; 12008 } 12009 12010 if (isInAsec) { 12011 return new AsecInstallArgs(codePath, instructionSets, 12012 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12013 } else { 12014 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12015 } 12016 } 12017 12018 static abstract class InstallArgs { 12019 /** @see InstallParams#origin */ 12020 final OriginInfo origin; 12021 /** @see InstallParams#move */ 12022 final MoveInfo move; 12023 12024 final IPackageInstallObserver2 observer; 12025 // Always refers to PackageManager flags only 12026 final int installFlags; 12027 final String installerPackageName; 12028 final String volumeUuid; 12029 final UserHandle user; 12030 final String abiOverride; 12031 final String[] installGrantPermissions; 12032 /** If non-null, drop an async trace when the install completes */ 12033 final String traceMethod; 12034 final int traceCookie; 12035 12036 // The list of instruction sets supported by this app. This is currently 12037 // only used during the rmdex() phase to clean up resources. We can get rid of this 12038 // if we move dex files under the common app path. 12039 /* nullable */ String[] instructionSets; 12040 12041 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12042 int installFlags, String installerPackageName, String volumeUuid, 12043 UserHandle user, String[] instructionSets, 12044 String abiOverride, String[] installGrantPermissions, 12045 String traceMethod, int traceCookie) { 12046 this.origin = origin; 12047 this.move = move; 12048 this.installFlags = installFlags; 12049 this.observer = observer; 12050 this.installerPackageName = installerPackageName; 12051 this.volumeUuid = volumeUuid; 12052 this.user = user; 12053 this.instructionSets = instructionSets; 12054 this.abiOverride = abiOverride; 12055 this.installGrantPermissions = installGrantPermissions; 12056 this.traceMethod = traceMethod; 12057 this.traceCookie = traceCookie; 12058 } 12059 12060 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12061 abstract int doPreInstall(int status); 12062 12063 /** 12064 * Rename package into final resting place. All paths on the given 12065 * scanned package should be updated to reflect the rename. 12066 */ 12067 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12068 abstract int doPostInstall(int status, int uid); 12069 12070 /** @see PackageSettingBase#codePathString */ 12071 abstract String getCodePath(); 12072 /** @see PackageSettingBase#resourcePathString */ 12073 abstract String getResourcePath(); 12074 12075 // Need installer lock especially for dex file removal. 12076 abstract void cleanUpResourcesLI(); 12077 abstract boolean doPostDeleteLI(boolean delete); 12078 12079 /** 12080 * Called before the source arguments are copied. This is used mostly 12081 * for MoveParams when it needs to read the source file to put it in the 12082 * destination. 12083 */ 12084 int doPreCopy() { 12085 return PackageManager.INSTALL_SUCCEEDED; 12086 } 12087 12088 /** 12089 * Called after the source arguments are copied. This is used mostly for 12090 * MoveParams when it needs to read the source file to put it in the 12091 * destination. 12092 * 12093 * @return 12094 */ 12095 int doPostCopy(int uid) { 12096 return PackageManager.INSTALL_SUCCEEDED; 12097 } 12098 12099 protected boolean isFwdLocked() { 12100 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12101 } 12102 12103 protected boolean isExternalAsec() { 12104 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12105 } 12106 12107 protected boolean isEphemeral() { 12108 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12109 } 12110 12111 UserHandle getUser() { 12112 return user; 12113 } 12114 } 12115 12116 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 12117 if (!allCodePaths.isEmpty()) { 12118 if (instructionSets == null) { 12119 throw new IllegalStateException("instructionSet == null"); 12120 } 12121 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 12122 for (String codePath : allCodePaths) { 12123 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 12124 try { 12125 mInstaller.rmdex(codePath, dexCodeInstructionSet); 12126 } catch (InstallerException ignored) { 12127 } 12128 } 12129 } 12130 } 12131 } 12132 12133 /** 12134 * Logic to handle installation of non-ASEC applications, including copying 12135 * and renaming logic. 12136 */ 12137 class FileInstallArgs extends InstallArgs { 12138 private File codeFile; 12139 private File resourceFile; 12140 12141 // Example topology: 12142 // /data/app/com.example/base.apk 12143 // /data/app/com.example/split_foo.apk 12144 // /data/app/com.example/lib/arm/libfoo.so 12145 // /data/app/com.example/lib/arm64/libfoo.so 12146 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 12147 12148 /** New install */ 12149 FileInstallArgs(InstallParams params) { 12150 super(params.origin, params.move, params.observer, params.installFlags, 12151 params.installerPackageName, params.volumeUuid, 12152 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12153 params.grantedRuntimePermissions, 12154 params.traceMethod, params.traceCookie); 12155 if (isFwdLocked()) { 12156 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 12157 } 12158 } 12159 12160 /** Existing install */ 12161 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 12162 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 12163 null, null, null, 0); 12164 this.codeFile = (codePath != null) ? new File(codePath) : null; 12165 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 12166 } 12167 12168 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12169 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 12170 try { 12171 return doCopyApk(imcs, temp); 12172 } finally { 12173 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12174 } 12175 } 12176 12177 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12178 if (origin.staged) { 12179 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 12180 codeFile = origin.file; 12181 resourceFile = origin.file; 12182 return PackageManager.INSTALL_SUCCEEDED; 12183 } 12184 12185 try { 12186 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12187 final File tempDir = 12188 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 12189 codeFile = tempDir; 12190 resourceFile = tempDir; 12191 } catch (IOException e) { 12192 Slog.w(TAG, "Failed to create copy file: " + e); 12193 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12194 } 12195 12196 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 12197 @Override 12198 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 12199 if (!FileUtils.isValidExtFilename(name)) { 12200 throw new IllegalArgumentException("Invalid filename: " + name); 12201 } 12202 try { 12203 final File file = new File(codeFile, name); 12204 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 12205 O_RDWR | O_CREAT, 0644); 12206 Os.chmod(file.getAbsolutePath(), 0644); 12207 return new ParcelFileDescriptor(fd); 12208 } catch (ErrnoException e) { 12209 throw new RemoteException("Failed to open: " + e.getMessage()); 12210 } 12211 } 12212 }; 12213 12214 int ret = PackageManager.INSTALL_SUCCEEDED; 12215 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 12216 if (ret != PackageManager.INSTALL_SUCCEEDED) { 12217 Slog.e(TAG, "Failed to copy package"); 12218 return ret; 12219 } 12220 12221 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 12222 NativeLibraryHelper.Handle handle = null; 12223 try { 12224 handle = NativeLibraryHelper.Handle.create(codeFile); 12225 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 12226 abiOverride); 12227 } catch (IOException e) { 12228 Slog.e(TAG, "Copying native libraries failed", e); 12229 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12230 } finally { 12231 IoUtils.closeQuietly(handle); 12232 } 12233 12234 return ret; 12235 } 12236 12237 int doPreInstall(int status) { 12238 if (status != PackageManager.INSTALL_SUCCEEDED) { 12239 cleanUp(); 12240 } 12241 return status; 12242 } 12243 12244 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12245 if (status != PackageManager.INSTALL_SUCCEEDED) { 12246 cleanUp(); 12247 return false; 12248 } 12249 12250 final File targetDir = codeFile.getParentFile(); 12251 final File beforeCodeFile = codeFile; 12252 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 12253 12254 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 12255 try { 12256 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 12257 } catch (ErrnoException e) { 12258 Slog.w(TAG, "Failed to rename", e); 12259 return false; 12260 } 12261 12262 if (!SELinux.restoreconRecursive(afterCodeFile)) { 12263 Slog.w(TAG, "Failed to restorecon"); 12264 return false; 12265 } 12266 12267 // Reflect the rename internally 12268 codeFile = afterCodeFile; 12269 resourceFile = afterCodeFile; 12270 12271 // Reflect the rename in scanned details 12272 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12273 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12274 afterCodeFile, pkg.baseCodePath)); 12275 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12276 afterCodeFile, pkg.splitCodePaths)); 12277 12278 // Reflect the rename in app info 12279 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12280 pkg.setApplicationInfoCodePath(pkg.codePath); 12281 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12282 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12283 pkg.setApplicationInfoResourcePath(pkg.codePath); 12284 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12285 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12286 12287 return true; 12288 } 12289 12290 int doPostInstall(int status, int uid) { 12291 if (status != PackageManager.INSTALL_SUCCEEDED) { 12292 cleanUp(); 12293 } 12294 return status; 12295 } 12296 12297 @Override 12298 String getCodePath() { 12299 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12300 } 12301 12302 @Override 12303 String getResourcePath() { 12304 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12305 } 12306 12307 private boolean cleanUp() { 12308 if (codeFile == null || !codeFile.exists()) { 12309 return false; 12310 } 12311 12312 removeCodePathLI(codeFile); 12313 12314 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 12315 resourceFile.delete(); 12316 } 12317 12318 return true; 12319 } 12320 12321 void cleanUpResourcesLI() { 12322 // Try enumerating all code paths before deleting 12323 List<String> allCodePaths = Collections.EMPTY_LIST; 12324 if (codeFile != null && codeFile.exists()) { 12325 try { 12326 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12327 allCodePaths = pkg.getAllCodePaths(); 12328 } catch (PackageParserException e) { 12329 // Ignored; we tried our best 12330 } 12331 } 12332 12333 cleanUp(); 12334 removeDexFiles(allCodePaths, instructionSets); 12335 } 12336 12337 boolean doPostDeleteLI(boolean delete) { 12338 // XXX err, shouldn't we respect the delete flag? 12339 cleanUpResourcesLI(); 12340 return true; 12341 } 12342 } 12343 12344 private boolean isAsecExternal(String cid) { 12345 final String asecPath = PackageHelper.getSdFilesystem(cid); 12346 return !asecPath.startsWith(mAsecInternalPath); 12347 } 12348 12349 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 12350 PackageManagerException { 12351 if (copyRet < 0) { 12352 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 12353 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 12354 throw new PackageManagerException(copyRet, message); 12355 } 12356 } 12357 } 12358 12359 /** 12360 * Extract the MountService "container ID" from the full code path of an 12361 * .apk. 12362 */ 12363 static String cidFromCodePath(String fullCodePath) { 12364 int eidx = fullCodePath.lastIndexOf("/"); 12365 String subStr1 = fullCodePath.substring(0, eidx); 12366 int sidx = subStr1.lastIndexOf("/"); 12367 return subStr1.substring(sidx+1, eidx); 12368 } 12369 12370 /** 12371 * Logic to handle installation of ASEC applications, including copying and 12372 * renaming logic. 12373 */ 12374 class AsecInstallArgs extends InstallArgs { 12375 static final String RES_FILE_NAME = "pkg.apk"; 12376 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 12377 12378 String cid; 12379 String packagePath; 12380 String resourcePath; 12381 12382 /** New install */ 12383 AsecInstallArgs(InstallParams params) { 12384 super(params.origin, params.move, params.observer, params.installFlags, 12385 params.installerPackageName, params.volumeUuid, 12386 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12387 params.grantedRuntimePermissions, 12388 params.traceMethod, params.traceCookie); 12389 } 12390 12391 /** Existing install */ 12392 AsecInstallArgs(String fullCodePath, String[] instructionSets, 12393 boolean isExternal, boolean isForwardLocked) { 12394 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 12395 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12396 instructionSets, null, null, null, 0); 12397 // Hackily pretend we're still looking at a full code path 12398 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 12399 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 12400 } 12401 12402 // Extract cid from fullCodePath 12403 int eidx = fullCodePath.lastIndexOf("/"); 12404 String subStr1 = fullCodePath.substring(0, eidx); 12405 int sidx = subStr1.lastIndexOf("/"); 12406 cid = subStr1.substring(sidx+1, eidx); 12407 setMountPath(subStr1); 12408 } 12409 12410 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 12411 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 12412 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12413 instructionSets, null, null, null, 0); 12414 this.cid = cid; 12415 setMountPath(PackageHelper.getSdDir(cid)); 12416 } 12417 12418 void createCopyFile() { 12419 cid = mInstallerService.allocateExternalStageCidLegacy(); 12420 } 12421 12422 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12423 if (origin.staged && origin.cid != null) { 12424 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 12425 cid = origin.cid; 12426 setMountPath(PackageHelper.getSdDir(cid)); 12427 return PackageManager.INSTALL_SUCCEEDED; 12428 } 12429 12430 if (temp) { 12431 createCopyFile(); 12432 } else { 12433 /* 12434 * Pre-emptively destroy the container since it's destroyed if 12435 * copying fails due to it existing anyway. 12436 */ 12437 PackageHelper.destroySdDir(cid); 12438 } 12439 12440 final String newMountPath = imcs.copyPackageToContainer( 12441 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 12442 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 12443 12444 if (newMountPath != null) { 12445 setMountPath(newMountPath); 12446 return PackageManager.INSTALL_SUCCEEDED; 12447 } else { 12448 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12449 } 12450 } 12451 12452 @Override 12453 String getCodePath() { 12454 return packagePath; 12455 } 12456 12457 @Override 12458 String getResourcePath() { 12459 return resourcePath; 12460 } 12461 12462 int doPreInstall(int status) { 12463 if (status != PackageManager.INSTALL_SUCCEEDED) { 12464 // Destroy container 12465 PackageHelper.destroySdDir(cid); 12466 } else { 12467 boolean mounted = PackageHelper.isContainerMounted(cid); 12468 if (!mounted) { 12469 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 12470 Process.SYSTEM_UID); 12471 if (newMountPath != null) { 12472 setMountPath(newMountPath); 12473 } else { 12474 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12475 } 12476 } 12477 } 12478 return status; 12479 } 12480 12481 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12482 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 12483 String newMountPath = null; 12484 if (PackageHelper.isContainerMounted(cid)) { 12485 // Unmount the container 12486 if (!PackageHelper.unMountSdDir(cid)) { 12487 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 12488 return false; 12489 } 12490 } 12491 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 12492 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 12493 " which might be stale. Will try to clean up."); 12494 // Clean up the stale container and proceed to recreate. 12495 if (!PackageHelper.destroySdDir(newCacheId)) { 12496 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 12497 return false; 12498 } 12499 // Successfully cleaned up stale container. Try to rename again. 12500 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 12501 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 12502 + " inspite of cleaning it up."); 12503 return false; 12504 } 12505 } 12506 if (!PackageHelper.isContainerMounted(newCacheId)) { 12507 Slog.w(TAG, "Mounting container " + newCacheId); 12508 newMountPath = PackageHelper.mountSdDir(newCacheId, 12509 getEncryptKey(), Process.SYSTEM_UID); 12510 } else { 12511 newMountPath = PackageHelper.getSdDir(newCacheId); 12512 } 12513 if (newMountPath == null) { 12514 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 12515 return false; 12516 } 12517 Log.i(TAG, "Succesfully renamed " + cid + 12518 " to " + newCacheId + 12519 " at new path: " + newMountPath); 12520 cid = newCacheId; 12521 12522 final File beforeCodeFile = new File(packagePath); 12523 setMountPath(newMountPath); 12524 final File afterCodeFile = new File(packagePath); 12525 12526 // Reflect the rename in scanned details 12527 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12528 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12529 afterCodeFile, pkg.baseCodePath)); 12530 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12531 afterCodeFile, pkg.splitCodePaths)); 12532 12533 // Reflect the rename in app info 12534 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12535 pkg.setApplicationInfoCodePath(pkg.codePath); 12536 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12537 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12538 pkg.setApplicationInfoResourcePath(pkg.codePath); 12539 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12540 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12541 12542 return true; 12543 } 12544 12545 private void setMountPath(String mountPath) { 12546 final File mountFile = new File(mountPath); 12547 12548 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 12549 if (monolithicFile.exists()) { 12550 packagePath = monolithicFile.getAbsolutePath(); 12551 if (isFwdLocked()) { 12552 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 12553 } else { 12554 resourcePath = packagePath; 12555 } 12556 } else { 12557 packagePath = mountFile.getAbsolutePath(); 12558 resourcePath = packagePath; 12559 } 12560 } 12561 12562 int doPostInstall(int status, int uid) { 12563 if (status != PackageManager.INSTALL_SUCCEEDED) { 12564 cleanUp(); 12565 } else { 12566 final int groupOwner; 12567 final String protectedFile; 12568 if (isFwdLocked()) { 12569 groupOwner = UserHandle.getSharedAppGid(uid); 12570 protectedFile = RES_FILE_NAME; 12571 } else { 12572 groupOwner = -1; 12573 protectedFile = null; 12574 } 12575 12576 if (uid < Process.FIRST_APPLICATION_UID 12577 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 12578 Slog.e(TAG, "Failed to finalize " + cid); 12579 PackageHelper.destroySdDir(cid); 12580 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12581 } 12582 12583 boolean mounted = PackageHelper.isContainerMounted(cid); 12584 if (!mounted) { 12585 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 12586 } 12587 } 12588 return status; 12589 } 12590 12591 private void cleanUp() { 12592 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 12593 12594 // Destroy secure container 12595 PackageHelper.destroySdDir(cid); 12596 } 12597 12598 private List<String> getAllCodePaths() { 12599 final File codeFile = new File(getCodePath()); 12600 if (codeFile != null && codeFile.exists()) { 12601 try { 12602 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12603 return pkg.getAllCodePaths(); 12604 } catch (PackageParserException e) { 12605 // Ignored; we tried our best 12606 } 12607 } 12608 return Collections.EMPTY_LIST; 12609 } 12610 12611 void cleanUpResourcesLI() { 12612 // Enumerate all code paths before deleting 12613 cleanUpResourcesLI(getAllCodePaths()); 12614 } 12615 12616 private void cleanUpResourcesLI(List<String> allCodePaths) { 12617 cleanUp(); 12618 removeDexFiles(allCodePaths, instructionSets); 12619 } 12620 12621 String getPackageName() { 12622 return getAsecPackageName(cid); 12623 } 12624 12625 boolean doPostDeleteLI(boolean delete) { 12626 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 12627 final List<String> allCodePaths = getAllCodePaths(); 12628 boolean mounted = PackageHelper.isContainerMounted(cid); 12629 if (mounted) { 12630 // Unmount first 12631 if (PackageHelper.unMountSdDir(cid)) { 12632 mounted = false; 12633 } 12634 } 12635 if (!mounted && delete) { 12636 cleanUpResourcesLI(allCodePaths); 12637 } 12638 return !mounted; 12639 } 12640 12641 @Override 12642 int doPreCopy() { 12643 if (isFwdLocked()) { 12644 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 12645 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 12646 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12647 } 12648 } 12649 12650 return PackageManager.INSTALL_SUCCEEDED; 12651 } 12652 12653 @Override 12654 int doPostCopy(int uid) { 12655 if (isFwdLocked()) { 12656 if (uid < Process.FIRST_APPLICATION_UID 12657 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 12658 RES_FILE_NAME)) { 12659 Slog.e(TAG, "Failed to finalize " + cid); 12660 PackageHelper.destroySdDir(cid); 12661 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12662 } 12663 } 12664 12665 return PackageManager.INSTALL_SUCCEEDED; 12666 } 12667 } 12668 12669 /** 12670 * Logic to handle movement of existing installed applications. 12671 */ 12672 class MoveInstallArgs extends InstallArgs { 12673 private File codeFile; 12674 private File resourceFile; 12675 12676 /** New install */ 12677 MoveInstallArgs(InstallParams params) { 12678 super(params.origin, params.move, params.observer, params.installFlags, 12679 params.installerPackageName, params.volumeUuid, 12680 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12681 params.grantedRuntimePermissions, 12682 params.traceMethod, params.traceCookie); 12683 } 12684 12685 int copyApk(IMediaContainerService imcs, boolean temp) { 12686 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 12687 + move.fromUuid + " to " + move.toUuid); 12688 synchronized (mInstaller) { 12689 try { 12690 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 12691 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 12692 } catch (InstallerException e) { 12693 Slog.w(TAG, "Failed to move app", e); 12694 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12695 } 12696 } 12697 12698 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 12699 resourceFile = codeFile; 12700 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 12701 12702 return PackageManager.INSTALL_SUCCEEDED; 12703 } 12704 12705 int doPreInstall(int status) { 12706 if (status != PackageManager.INSTALL_SUCCEEDED) { 12707 cleanUp(move.toUuid); 12708 } 12709 return status; 12710 } 12711 12712 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12713 if (status != PackageManager.INSTALL_SUCCEEDED) { 12714 cleanUp(move.toUuid); 12715 return false; 12716 } 12717 12718 // Reflect the move in app info 12719 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12720 pkg.setApplicationInfoCodePath(pkg.codePath); 12721 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12722 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12723 pkg.setApplicationInfoResourcePath(pkg.codePath); 12724 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12725 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12726 12727 return true; 12728 } 12729 12730 int doPostInstall(int status, int uid) { 12731 if (status == PackageManager.INSTALL_SUCCEEDED) { 12732 cleanUp(move.fromUuid); 12733 } else { 12734 cleanUp(move.toUuid); 12735 } 12736 return status; 12737 } 12738 12739 @Override 12740 String getCodePath() { 12741 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12742 } 12743 12744 @Override 12745 String getResourcePath() { 12746 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12747 } 12748 12749 private boolean cleanUp(String volumeUuid) { 12750 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 12751 move.dataAppName); 12752 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 12753 synchronized (mInstallLock) { 12754 // Clean up both app data and code 12755 removeDataDirsLI(volumeUuid, move.packageName); 12756 removeCodePathLI(codeFile); 12757 } 12758 return true; 12759 } 12760 12761 void cleanUpResourcesLI() { 12762 throw new UnsupportedOperationException(); 12763 } 12764 12765 boolean doPostDeleteLI(boolean delete) { 12766 throw new UnsupportedOperationException(); 12767 } 12768 } 12769 12770 static String getAsecPackageName(String packageCid) { 12771 int idx = packageCid.lastIndexOf("-"); 12772 if (idx == -1) { 12773 return packageCid; 12774 } 12775 return packageCid.substring(0, idx); 12776 } 12777 12778 // Utility method used to create code paths based on package name and available index. 12779 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 12780 String idxStr = ""; 12781 int idx = 1; 12782 // Fall back to default value of idx=1 if prefix is not 12783 // part of oldCodePath 12784 if (oldCodePath != null) { 12785 String subStr = oldCodePath; 12786 // Drop the suffix right away 12787 if (suffix != null && subStr.endsWith(suffix)) { 12788 subStr = subStr.substring(0, subStr.length() - suffix.length()); 12789 } 12790 // If oldCodePath already contains prefix find out the 12791 // ending index to either increment or decrement. 12792 int sidx = subStr.lastIndexOf(prefix); 12793 if (sidx != -1) { 12794 subStr = subStr.substring(sidx + prefix.length()); 12795 if (subStr != null) { 12796 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 12797 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 12798 } 12799 try { 12800 idx = Integer.parseInt(subStr); 12801 if (idx <= 1) { 12802 idx++; 12803 } else { 12804 idx--; 12805 } 12806 } catch(NumberFormatException e) { 12807 } 12808 } 12809 } 12810 } 12811 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 12812 return prefix + idxStr; 12813 } 12814 12815 private File getNextCodePath(File targetDir, String packageName) { 12816 int suffix = 1; 12817 File result; 12818 do { 12819 result = new File(targetDir, packageName + "-" + suffix); 12820 suffix++; 12821 } while (result.exists()); 12822 return result; 12823 } 12824 12825 // Utility method that returns the relative package path with respect 12826 // to the installation directory. Like say for /data/data/com.test-1.apk 12827 // string com.test-1 is returned. 12828 static String deriveCodePathName(String codePath) { 12829 if (codePath == null) { 12830 return null; 12831 } 12832 final File codeFile = new File(codePath); 12833 final String name = codeFile.getName(); 12834 if (codeFile.isDirectory()) { 12835 return name; 12836 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 12837 final int lastDot = name.lastIndexOf('.'); 12838 return name.substring(0, lastDot); 12839 } else { 12840 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 12841 return null; 12842 } 12843 } 12844 12845 static class PackageInstalledInfo { 12846 String name; 12847 int uid; 12848 // The set of users that originally had this package installed. 12849 int[] origUsers; 12850 // The set of users that now have this package installed. 12851 int[] newUsers; 12852 PackageParser.Package pkg; 12853 int returnCode; 12854 String returnMsg; 12855 PackageRemovedInfo removedInfo; 12856 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 12857 12858 public void setError(int code, String msg) { 12859 setReturnCode(code); 12860 setReturnMessage(msg); 12861 Slog.w(TAG, msg); 12862 } 12863 12864 public void setError(String msg, PackageParserException e) { 12865 setReturnCode(e.error); 12866 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 12867 Slog.w(TAG, msg, e); 12868 } 12869 12870 public void setError(String msg, PackageManagerException e) { 12871 returnCode = e.error; 12872 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 12873 Slog.w(TAG, msg, e); 12874 } 12875 12876 public void setReturnCode(int returnCode) { 12877 this.returnCode = returnCode; 12878 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 12879 for (int i = 0; i < childCount; i++) { 12880 addedChildPackages.valueAt(i).returnCode = returnCode; 12881 } 12882 } 12883 12884 private void setReturnMessage(String returnMsg) { 12885 this.returnMsg = returnMsg; 12886 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 12887 for (int i = 0; i < childCount; i++) { 12888 addedChildPackages.valueAt(i).returnMsg = returnMsg; 12889 } 12890 } 12891 12892 // In some error cases we want to convey more info back to the observer 12893 String origPackage; 12894 String origPermission; 12895 } 12896 12897 /* 12898 * Install a non-existing package. 12899 */ 12900 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12901 UserHandle user, String installerPackageName, String volumeUuid, 12902 PackageInstalledInfo res) { 12903 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 12904 12905 // Remember this for later, in case we need to rollback this install 12906 String pkgName = pkg.packageName; 12907 12908 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 12909 12910 synchronized(mPackages) { 12911 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 12912 // A package with the same name is already installed, though 12913 // it has been renamed to an older name. The package we 12914 // are trying to install should be installed as an update to 12915 // the existing one, but that has not been requested, so bail. 12916 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12917 + " without first uninstalling package running as " 12918 + mSettings.mRenamedPackages.get(pkgName)); 12919 return; 12920 } 12921 if (mPackages.containsKey(pkgName)) { 12922 // Don't allow installation over an existing package with the same name. 12923 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12924 + " without first uninstalling."); 12925 return; 12926 } 12927 } 12928 12929 try { 12930 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 12931 System.currentTimeMillis(), user); 12932 12933 updateSettingsLI(newPackage, installerPackageName, null, res, user); 12934 12935 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12936 prepareAppDataAfterInstall(newPackage); 12937 12938 } else { 12939 // Remove package from internal structures, but keep around any 12940 // data that might have already existed 12941 deletePackageLI(pkgName, UserHandle.ALL, false, null, 12942 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 12943 } 12944 } catch (PackageManagerException e) { 12945 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12946 } 12947 12948 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12949 } 12950 12951 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 12952 // Can't rotate keys during boot or if sharedUser. 12953 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 12954 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 12955 return false; 12956 } 12957 // app is using upgradeKeySets; make sure all are valid 12958 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12959 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 12960 for (int i = 0; i < upgradeKeySets.length; i++) { 12961 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 12962 Slog.wtf(TAG, "Package " 12963 + (oldPs.name != null ? oldPs.name : "<null>") 12964 + " contains upgrade-key-set reference to unknown key-set: " 12965 + upgradeKeySets[i] 12966 + " reverting to signatures check."); 12967 return false; 12968 } 12969 } 12970 return true; 12971 } 12972 12973 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 12974 // Upgrade keysets are being used. Determine if new package has a superset of the 12975 // required keys. 12976 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 12977 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12978 for (int i = 0; i < upgradeKeySets.length; i++) { 12979 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 12980 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 12981 return true; 12982 } 12983 } 12984 return false; 12985 } 12986 12987 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12988 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 12989 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 12990 12991 final PackageParser.Package oldPackage; 12992 final String pkgName = pkg.packageName; 12993 final int[] allUsers; 12994 12995 // First find the old package info and check signatures 12996 synchronized(mPackages) { 12997 oldPackage = mPackages.get(pkgName); 12998 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 12999 if (isEphemeral && !oldIsEphemeral) { 13000 // can't downgrade from full to ephemeral 13001 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13002 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13003 return; 13004 } 13005 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13006 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13007 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13008 if (!checkUpgradeKeySetLP(ps, pkg)) { 13009 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13010 "New package not signed by keys specified by upgrade-keysets: " 13011 + pkgName); 13012 return; 13013 } 13014 } else { 13015 // default to original signature matching 13016 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13017 != PackageManager.SIGNATURE_MATCH) { 13018 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13019 "New package has a different signature: " + pkgName); 13020 return; 13021 } 13022 } 13023 13024 // In case of rollback, remember per-user/profile install state 13025 allUsers = sUserManager.getUserIds(); 13026 } 13027 13028 // Update what is removed 13029 res.removedInfo = new PackageRemovedInfo(); 13030 res.removedInfo.uid = oldPackage.applicationInfo.uid; 13031 res.removedInfo.removedPackage = oldPackage.packageName; 13032 res.removedInfo.isUpdate = true; 13033 final int childCount = (oldPackage.childPackages != null) 13034 ? oldPackage.childPackages.size() : 0; 13035 for (int i = 0; i < childCount; i++) { 13036 boolean childPackageUpdated = false; 13037 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 13038 if (res.addedChildPackages != null) { 13039 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13040 if (childRes != null) { 13041 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 13042 childRes.removedInfo.removedPackage = childPkg.packageName; 13043 childRes.removedInfo.isUpdate = true; 13044 childPackageUpdated = true; 13045 } 13046 } 13047 if (!childPackageUpdated) { 13048 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 13049 childRemovedRes.removedPackage = childPkg.packageName; 13050 childRemovedRes.isUpdate = false; 13051 childRemovedRes.dataRemoved = true; 13052 synchronized (mPackages) { 13053 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13054 if (childPs != null) { 13055 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 13056 } 13057 } 13058 if (res.removedInfo.removedChildPackages == null) { 13059 res.removedInfo.removedChildPackages = new ArrayMap<>(); 13060 } 13061 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 13062 } 13063 } 13064 13065 boolean sysPkg = (isSystemApp(oldPackage)); 13066 if (sysPkg) { 13067 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 13068 user, allUsers, installerPackageName, res); 13069 } else { 13070 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 13071 user, allUsers, installerPackageName, res); 13072 } 13073 } 13074 13075 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 13076 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13077 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13078 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 13079 + deletedPackage); 13080 13081 String pkgName = deletedPackage.packageName; 13082 boolean deletedPkg = true; 13083 boolean addedPkg = false; 13084 13085 final long origUpdateTime = (pkg.mExtras != null) 13086 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 13087 13088 // First delete the existing package while retaining the data directory 13089 if (!deletePackageLI(pkgName, null, true, allUsers, PackageManager.DELETE_KEEP_DATA, 13090 res.removedInfo, true, pkg)) { 13091 // If the existing package wasn't successfully deleted 13092 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 13093 deletedPkg = false; 13094 } else { 13095 // Successfully deleted the old package; proceed with replace. 13096 13097 // If deleted package lived in a container, give users a chance to 13098 // relinquish resources before killing. 13099 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 13100 if (DEBUG_INSTALL) { 13101 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 13102 } 13103 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 13104 final ArrayList<String> pkgList = new ArrayList<String>(1); 13105 pkgList.add(deletedPackage.applicationInfo.packageName); 13106 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 13107 } 13108 13109 deleteCodeCacheDirsLI(pkg); 13110 13111 try { 13112 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 13113 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 13114 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13115 prepareAppDataAfterInstall(newPackage); 13116 addedPkg = true; 13117 } catch (PackageManagerException e) { 13118 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13119 } 13120 } 13121 13122 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13123 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 13124 13125 // Revert all internal state mutations and added folders for the failed install 13126 if (addedPkg) { 13127 deletePackageLI(pkgName, null, true, allUsers, PackageManager.DELETE_KEEP_DATA, 13128 res.removedInfo, true, null); 13129 } 13130 13131 // Restore the old package 13132 if (deletedPkg) { 13133 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 13134 File restoreFile = new File(deletedPackage.codePath); 13135 // Parse old package 13136 boolean oldExternal = isExternal(deletedPackage); 13137 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 13138 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 13139 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 13140 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 13141 try { 13142 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 13143 null); 13144 } catch (PackageManagerException e) { 13145 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 13146 + e.getMessage()); 13147 return; 13148 } 13149 13150 synchronized (mPackages) { 13151 // Ensure the installer package name up to date 13152 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13153 13154 // Update permissions for restored package 13155 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13156 13157 mSettings.writeLPr(); 13158 } 13159 13160 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 13161 } 13162 } else { 13163 synchronized (mPackages) { 13164 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 13165 if (ps != null) { 13166 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 13167 if (res.removedInfo.removedChildPackages != null) { 13168 final int childCount = res.removedInfo.removedChildPackages.size(); 13169 // Iterate in reverse as we may modify the collection 13170 for (int i = childCount - 1; i >= 0; i--) { 13171 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 13172 if (res.addedChildPackages.containsKey(childPackageName)) { 13173 res.removedInfo.removedChildPackages.removeAt(i); 13174 } else { 13175 PackageRemovedInfo childInfo = res.removedInfo 13176 .removedChildPackages.valueAt(i); 13177 childInfo.removedForAllUsers = mPackages.get( 13178 childInfo.removedPackage) == null; 13179 } 13180 } 13181 } 13182 } 13183 } 13184 } 13185 } 13186 13187 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 13188 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13189 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13190 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 13191 + ", old=" + deletedPackage); 13192 13193 final boolean disabledSystem; 13194 13195 // Set the system/privileged flags as needed 13196 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 13197 if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 13198 != 0) { 13199 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13200 } 13201 13202 // Kill package processes including services, providers, etc. 13203 killPackage(deletedPackage, "replace sys pkg"); 13204 13205 // Remove existing system package 13206 removePackageLI(deletedPackage, true); 13207 13208 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 13209 if (!disabledSystem) { 13210 // We didn't need to disable the .apk as a current system package, 13211 // which means we are replacing another update that is already 13212 // installed. We need to make sure to delete the older one's .apk. 13213 res.removedInfo.args = createInstallArgsForExisting(0, 13214 deletedPackage.applicationInfo.getCodePath(), 13215 deletedPackage.applicationInfo.getResourcePath(), 13216 getAppDexInstructionSets(deletedPackage.applicationInfo)); 13217 } else { 13218 res.removedInfo.args = null; 13219 } 13220 13221 // Successfully disabled the old package. Now proceed with re-installation 13222 deleteCodeCacheDirsLI(pkg); 13223 13224 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13225 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 13226 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 13227 13228 PackageParser.Package newPackage = null; 13229 try { 13230 // Add the package to the internal data structures 13231 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 13232 13233 // Set the update and install times 13234 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 13235 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 13236 System.currentTimeMillis()); 13237 13238 // Check for shared user id changes 13239 String invalidPackageName = getParentOrChildPackageChangedSharedUser( 13240 deletedPackage, newPackage); 13241 if (invalidPackageName != null) { 13242 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13243 "Forbidding shared user change from " + deletedPkgSetting.sharedUser 13244 + " to " + invalidPackageName); 13245 } 13246 13247 // Update the package dynamic state if succeeded 13248 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13249 // Now that the install succeeded make sure we remove data 13250 // directories for any child package the update removed. 13251 final int deletedChildCount = (deletedPackage.childPackages != null) 13252 ? deletedPackage.childPackages.size() : 0; 13253 final int newChildCount = (newPackage.childPackages != null) 13254 ? newPackage.childPackages.size() : 0; 13255 for (int i = 0; i < deletedChildCount; i++) { 13256 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 13257 boolean childPackageDeleted = true; 13258 for (int j = 0; j < newChildCount; j++) { 13259 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 13260 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 13261 childPackageDeleted = false; 13262 break; 13263 } 13264 } 13265 if (childPackageDeleted) { 13266 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 13267 deletedChildPkg.packageName); 13268 if (ps != null && res.removedInfo.removedChildPackages != null) { 13269 PackageRemovedInfo removedChildRes = res.removedInfo 13270 .removedChildPackages.get(deletedChildPkg.packageName); 13271 removePackageDataLI(ps, allUsers, removedChildRes, 0, false); 13272 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 13273 } 13274 } 13275 } 13276 13277 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13278 prepareAppDataAfterInstall(newPackage); 13279 } 13280 } catch (PackageManagerException e) { 13281 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 13282 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13283 } 13284 13285 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13286 // Re installation failed. Restore old information 13287 // Remove new pkg information 13288 if (newPackage != null) { 13289 removeInstalledPackageLI(newPackage, true); 13290 } 13291 // Add back the old system package 13292 try { 13293 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 13294 } catch (PackageManagerException e) { 13295 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 13296 } 13297 13298 synchronized (mPackages) { 13299 if (disabledSystem) { 13300 enableSystemPackageLPw(deletedPackage); 13301 } 13302 13303 // Ensure the installer package name up to date 13304 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13305 13306 // Update permissions for restored package 13307 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13308 13309 mSettings.writeLPr(); 13310 } 13311 13312 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 13313 + " after failed upgrade"); 13314 } 13315 } 13316 13317 /** 13318 * Checks whether the parent or any of the child packages have a change shared 13319 * user. For a package to be a valid update the shred users of the parent and 13320 * the children should match. We may later support changing child shared users. 13321 * @param oldPkg The updated package. 13322 * @param newPkg The update package. 13323 * @return The shared user that change between the versions. 13324 */ 13325 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 13326 PackageParser.Package newPkg) { 13327 // Check parent shared user 13328 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 13329 return newPkg.packageName; 13330 } 13331 // Check child shared users 13332 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13333 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 13334 for (int i = 0; i < newChildCount; i++) { 13335 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 13336 // If this child was present, did it have the same shared user? 13337 for (int j = 0; j < oldChildCount; j++) { 13338 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 13339 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 13340 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 13341 return newChildPkg.packageName; 13342 } 13343 } 13344 } 13345 return null; 13346 } 13347 13348 private void removeNativeBinariesLI(PackageSetting ps) { 13349 // Remove the lib path for the parent package 13350 if (ps != null) { 13351 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 13352 // Remove the lib path for the child packages 13353 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 13354 for (int i = 0; i < childCount; i++) { 13355 PackageSetting childPs = null; 13356 synchronized (mPackages) { 13357 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 13358 } 13359 if (childPs != null) { 13360 NativeLibraryHelper.removeNativeBinariesLI(childPs 13361 .legacyNativeLibraryPathString); 13362 } 13363 } 13364 } 13365 } 13366 13367 private void enableSystemPackageLPw(PackageParser.Package pkg) { 13368 // Enable the parent package 13369 mSettings.enableSystemPackageLPw(pkg.packageName); 13370 // Enable the child packages 13371 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13372 for (int i = 0; i < childCount; i++) { 13373 PackageParser.Package childPkg = pkg.childPackages.get(i); 13374 mSettings.enableSystemPackageLPw(childPkg.packageName); 13375 } 13376 } 13377 13378 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 13379 PackageParser.Package newPkg) { 13380 // Disable the parent package (parent always replaced) 13381 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 13382 // Disable the child packages 13383 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13384 for (int i = 0; i < childCount; i++) { 13385 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 13386 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 13387 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 13388 } 13389 return disabled; 13390 } 13391 13392 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 13393 String installerPackageName) { 13394 // Enable the parent package 13395 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 13396 // Enable the child packages 13397 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13398 for (int i = 0; i < childCount; i++) { 13399 PackageParser.Package childPkg = pkg.childPackages.get(i); 13400 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 13401 } 13402 } 13403 13404 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 13405 // Collect all used permissions in the UID 13406 ArraySet<String> usedPermissions = new ArraySet<>(); 13407 final int packageCount = su.packages.size(); 13408 for (int i = 0; i < packageCount; i++) { 13409 PackageSetting ps = su.packages.valueAt(i); 13410 if (ps.pkg == null) { 13411 continue; 13412 } 13413 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 13414 for (int j = 0; j < requestedPermCount; j++) { 13415 String permission = ps.pkg.requestedPermissions.get(j); 13416 BasePermission bp = mSettings.mPermissions.get(permission); 13417 if (bp != null) { 13418 usedPermissions.add(permission); 13419 } 13420 } 13421 } 13422 13423 PermissionsState permissionsState = su.getPermissionsState(); 13424 // Prune install permissions 13425 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 13426 final int installPermCount = installPermStates.size(); 13427 for (int i = installPermCount - 1; i >= 0; i--) { 13428 PermissionState permissionState = installPermStates.get(i); 13429 if (!usedPermissions.contains(permissionState.getName())) { 13430 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 13431 if (bp != null) { 13432 permissionsState.revokeInstallPermission(bp); 13433 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 13434 PackageManager.MASK_PERMISSION_FLAGS, 0); 13435 } 13436 } 13437 } 13438 13439 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 13440 13441 // Prune runtime permissions 13442 for (int userId : allUserIds) { 13443 List<PermissionState> runtimePermStates = permissionsState 13444 .getRuntimePermissionStates(userId); 13445 final int runtimePermCount = runtimePermStates.size(); 13446 for (int i = runtimePermCount - 1; i >= 0; i--) { 13447 PermissionState permissionState = runtimePermStates.get(i); 13448 if (!usedPermissions.contains(permissionState.getName())) { 13449 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 13450 if (bp != null) { 13451 permissionsState.revokeRuntimePermission(bp, userId); 13452 permissionsState.updatePermissionFlags(bp, userId, 13453 PackageManager.MASK_PERMISSION_FLAGS, 0); 13454 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 13455 runtimePermissionChangedUserIds, userId); 13456 } 13457 } 13458 } 13459 } 13460 13461 return runtimePermissionChangedUserIds; 13462 } 13463 13464 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 13465 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 13466 // Update the parent package setting 13467 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 13468 res, user); 13469 // Update the child packages setting 13470 final int childCount = (newPackage.childPackages != null) 13471 ? newPackage.childPackages.size() : 0; 13472 for (int i = 0; i < childCount; i++) { 13473 PackageParser.Package childPackage = newPackage.childPackages.get(i); 13474 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 13475 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 13476 childRes.origUsers, childRes, user); 13477 } 13478 } 13479 13480 private void updateSettingsInternalLI(PackageParser.Package newPackage, 13481 String installerPackageName, int[] allUsers, int[] installedForUsers, 13482 PackageInstalledInfo res, UserHandle user) { 13483 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 13484 13485 String pkgName = newPackage.packageName; 13486 synchronized (mPackages) { 13487 //write settings. the installStatus will be incomplete at this stage. 13488 //note that the new package setting would have already been 13489 //added to mPackages. It hasn't been persisted yet. 13490 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 13491 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 13492 mSettings.writeLPr(); 13493 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13494 } 13495 13496 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 13497 synchronized (mPackages) { 13498 updatePermissionsLPw(newPackage.packageName, newPackage, 13499 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 13500 ? UPDATE_PERMISSIONS_ALL : 0)); 13501 // For system-bundled packages, we assume that installing an upgraded version 13502 // of the package implies that the user actually wants to run that new code, 13503 // so we enable the package. 13504 PackageSetting ps = mSettings.mPackages.get(pkgName); 13505 final int userId = user.getIdentifier(); 13506 if (ps != null) { 13507 if (isSystemApp(newPackage)) { 13508 if (DEBUG_INSTALL) { 13509 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 13510 } 13511 // Enable system package for requested users 13512 if (res.origUsers != null) { 13513 for (int origUserId : res.origUsers) { 13514 if (userId == UserHandle.USER_ALL || userId == origUserId) { 13515 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 13516 origUserId, installerPackageName); 13517 } 13518 } 13519 } 13520 // Also convey the prior install/uninstall state 13521 if (allUsers != null && installedForUsers != null) { 13522 for (int currentUserId : allUsers) { 13523 final boolean installed = ArrayUtils.contains( 13524 installedForUsers, currentUserId); 13525 if (DEBUG_INSTALL) { 13526 Slog.d(TAG, " user " + currentUserId + " => " + installed); 13527 } 13528 ps.setInstalled(installed, currentUserId); 13529 } 13530 // these install state changes will be persisted in the 13531 // upcoming call to mSettings.writeLPr(). 13532 } 13533 } 13534 // It's implied that when a user requests installation, they want the app to be 13535 // installed and enabled. 13536 if (userId != UserHandle.USER_ALL) { 13537 ps.setInstalled(true, userId); 13538 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 13539 } 13540 } 13541 res.name = pkgName; 13542 res.uid = newPackage.applicationInfo.uid; 13543 res.pkg = newPackage; 13544 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 13545 mSettings.setInstallerPackageName(pkgName, installerPackageName); 13546 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13547 //to update install status 13548 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 13549 mSettings.writeLPr(); 13550 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13551 } 13552 13553 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13554 } 13555 13556 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 13557 try { 13558 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 13559 installPackageLI(args, res); 13560 } finally { 13561 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13562 } 13563 } 13564 13565 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 13566 final int installFlags = args.installFlags; 13567 final String installerPackageName = args.installerPackageName; 13568 final String volumeUuid = args.volumeUuid; 13569 final File tmpPackageFile = new File(args.getCodePath()); 13570 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 13571 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 13572 || (args.volumeUuid != null)); 13573 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 13574 boolean replace = false; 13575 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 13576 if (args.move != null) { 13577 // moving a complete application; perform an initial scan on the new install location 13578 scanFlags |= SCAN_INITIAL; 13579 } 13580 13581 // Result object to be returned 13582 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13583 13584 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 13585 13586 // Sanity check 13587 if (ephemeral && (forwardLocked || onExternal)) { 13588 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 13589 + " external=" + onExternal); 13590 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13591 return; 13592 } 13593 13594 // Retrieve PackageSettings and parse package 13595 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 13596 | PackageParser.PARSE_ENFORCE_CODE 13597 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 13598 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 13599 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 13600 PackageParser pp = new PackageParser(); 13601 pp.setSeparateProcesses(mSeparateProcesses); 13602 pp.setDisplayMetrics(mMetrics); 13603 13604 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 13605 final PackageParser.Package pkg; 13606 try { 13607 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 13608 } catch (PackageParserException e) { 13609 res.setError("Failed parse during installPackageLI", e); 13610 return; 13611 } finally { 13612 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13613 } 13614 13615 // If we are installing a clustered package add results for the children 13616 if (pkg.childPackages != null) { 13617 synchronized (mPackages) { 13618 final int childCount = pkg.childPackages.size(); 13619 for (int i = 0; i < childCount; i++) { 13620 PackageParser.Package childPkg = pkg.childPackages.get(i); 13621 PackageInstalledInfo childRes = new PackageInstalledInfo(); 13622 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13623 childRes.pkg = childPkg; 13624 childRes.name = childPkg.packageName; 13625 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13626 if (childPs != null) { 13627 childRes.origUsers = childPs.queryInstalledUsers( 13628 sUserManager.getUserIds(), true); 13629 } 13630 if ((mPackages.containsKey(childPkg.packageName))) { 13631 childRes.removedInfo = new PackageRemovedInfo(); 13632 childRes.removedInfo.removedPackage = childPkg.packageName; 13633 } 13634 if (res.addedChildPackages == null) { 13635 res.addedChildPackages = new ArrayMap<>(); 13636 } 13637 res.addedChildPackages.put(childPkg.packageName, childRes); 13638 } 13639 } 13640 } 13641 13642 // If package doesn't declare API override, mark that we have an install 13643 // time CPU ABI override. 13644 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 13645 pkg.cpuAbiOverride = args.abiOverride; 13646 } 13647 13648 String pkgName = res.name = pkg.packageName; 13649 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 13650 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 13651 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 13652 return; 13653 } 13654 } 13655 13656 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 13657 try { 13658 PackageParser.collectCertificates(pkg, parseFlags); 13659 } catch (PackageParserException e) { 13660 res.setError("Failed collect during installPackageLI", e); 13661 return; 13662 } finally { 13663 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13664 } 13665 13666 // Get rid of all references to package scan path via parser. 13667 pp = null; 13668 String oldCodePath = null; 13669 boolean systemApp = false; 13670 synchronized (mPackages) { 13671 // Check if installing already existing package 13672 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 13673 String oldName = mSettings.mRenamedPackages.get(pkgName); 13674 if (pkg.mOriginalPackages != null 13675 && pkg.mOriginalPackages.contains(oldName) 13676 && mPackages.containsKey(oldName)) { 13677 // This package is derived from an original package, 13678 // and this device has been updating from that original 13679 // name. We must continue using the original name, so 13680 // rename the new package here. 13681 pkg.setPackageName(oldName); 13682 pkgName = pkg.packageName; 13683 replace = true; 13684 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 13685 + oldName + " pkgName=" + pkgName); 13686 } else if (mPackages.containsKey(pkgName)) { 13687 // This package, under its official name, already exists 13688 // on the device; we should replace it. 13689 replace = true; 13690 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 13691 } 13692 13693 // Child packages are installed through the parent package 13694 if (pkg.parentPackage != null) { 13695 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 13696 "Package " + pkg.packageName + " is child of package " 13697 + pkg.parentPackage.parentPackage + ". Child packages " 13698 + "can be updated only through the parent package."); 13699 return; 13700 } 13701 13702 if (replace) { 13703 // Prevent apps opting out from runtime permissions 13704 PackageParser.Package oldPackage = mPackages.get(pkgName); 13705 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 13706 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 13707 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 13708 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 13709 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 13710 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 13711 + " doesn't support runtime permissions but the old" 13712 + " target SDK " + oldTargetSdk + " does."); 13713 return; 13714 } 13715 13716 // Prevent installing of child packages 13717 if (oldPackage.parentPackage != null) { 13718 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 13719 "Package " + pkg.packageName + " is child of package " 13720 + oldPackage.parentPackage + ". Child packages " 13721 + "can be updated only through the parent package."); 13722 return; 13723 } 13724 } 13725 } 13726 13727 PackageSetting ps = mSettings.mPackages.get(pkgName); 13728 if (ps != null) { 13729 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 13730 13731 // Quick sanity check that we're signed correctly if updating; 13732 // we'll check this again later when scanning, but we want to 13733 // bail early here before tripping over redefined permissions. 13734 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13735 if (!checkUpgradeKeySetLP(ps, pkg)) { 13736 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 13737 + pkg.packageName + " upgrade keys do not match the " 13738 + "previously installed version"); 13739 return; 13740 } 13741 } else { 13742 try { 13743 verifySignaturesLP(ps, pkg); 13744 } catch (PackageManagerException e) { 13745 res.setError(e.error, e.getMessage()); 13746 return; 13747 } 13748 } 13749 13750 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 13751 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 13752 systemApp = (ps.pkg.applicationInfo.flags & 13753 ApplicationInfo.FLAG_SYSTEM) != 0; 13754 } 13755 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13756 } 13757 13758 // Check whether the newly-scanned package wants to define an already-defined perm 13759 int N = pkg.permissions.size(); 13760 for (int i = N-1; i >= 0; i--) { 13761 PackageParser.Permission perm = pkg.permissions.get(i); 13762 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 13763 if (bp != null) { 13764 // If the defining package is signed with our cert, it's okay. This 13765 // also includes the "updating the same package" case, of course. 13766 // "updating same package" could also involve key-rotation. 13767 final boolean sigsOk; 13768 if (bp.sourcePackage.equals(pkg.packageName) 13769 && (bp.packageSetting instanceof PackageSetting) 13770 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 13771 scanFlags))) { 13772 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 13773 } else { 13774 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 13775 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 13776 } 13777 if (!sigsOk) { 13778 // If the owning package is the system itself, we log but allow 13779 // install to proceed; we fail the install on all other permission 13780 // redefinitions. 13781 if (!bp.sourcePackage.equals("android")) { 13782 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 13783 + pkg.packageName + " attempting to redeclare permission " 13784 + perm.info.name + " already owned by " + bp.sourcePackage); 13785 res.origPermission = perm.info.name; 13786 res.origPackage = bp.sourcePackage; 13787 return; 13788 } else { 13789 Slog.w(TAG, "Package " + pkg.packageName 13790 + " attempting to redeclare system permission " 13791 + perm.info.name + "; ignoring new declaration"); 13792 pkg.permissions.remove(i); 13793 } 13794 } 13795 } 13796 } 13797 } 13798 13799 if (systemApp) { 13800 if (onExternal) { 13801 // Abort update; system app can't be replaced with app on sdcard 13802 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 13803 "Cannot install updates to system apps on sdcard"); 13804 return; 13805 } else if (ephemeral) { 13806 // Abort update; system app can't be replaced with an ephemeral app 13807 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 13808 "Cannot update a system app with an ephemeral app"); 13809 return; 13810 } 13811 } 13812 13813 if (args.move != null) { 13814 // We did an in-place move, so dex is ready to roll 13815 scanFlags |= SCAN_NO_DEX; 13816 scanFlags |= SCAN_MOVE; 13817 13818 synchronized (mPackages) { 13819 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13820 if (ps == null) { 13821 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 13822 "Missing settings for moved package " + pkgName); 13823 } 13824 13825 // We moved the entire application as-is, so bring over the 13826 // previously derived ABI information. 13827 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 13828 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 13829 } 13830 13831 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 13832 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 13833 scanFlags |= SCAN_NO_DEX; 13834 13835 try { 13836 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 13837 args.abiOverride : pkg.cpuAbiOverride); 13838 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 13839 true /* extract libs */); 13840 } catch (PackageManagerException pme) { 13841 Slog.e(TAG, "Error deriving application ABI", pme); 13842 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 13843 return; 13844 } 13845 13846 // Extract package to save the VM unzipping the APK in memory during 13847 // launch. Only do this if profile-guided compilation is enabled because 13848 // otherwise BackgroundDexOptService will not dexopt the package later. 13849 if (mUseJitProfiles) { 13850 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 13851 // Do not run PackageDexOptimizer through the local performDexOpt 13852 // method because `pkg` is not in `mPackages` yet. 13853 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 13854 false /* useProfiles */, true /* extractOnly */); 13855 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13856 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 13857 String msg = "Extracking package failed for " + pkgName; 13858 res.setError(INSTALL_FAILED_DEXOPT, msg); 13859 return; 13860 } 13861 } 13862 } 13863 13864 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 13865 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 13866 return; 13867 } 13868 13869 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 13870 13871 if (replace) { 13872 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 13873 installerPackageName, res); 13874 } else { 13875 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 13876 args.user, installerPackageName, volumeUuid, res); 13877 } 13878 synchronized (mPackages) { 13879 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13880 if (ps != null) { 13881 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13882 } 13883 13884 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13885 for (int i = 0; i < childCount; i++) { 13886 PackageParser.Package childPkg = pkg.childPackages.get(i); 13887 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13888 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13889 if (childPs != null) { 13890 childRes.newUsers = childPs.queryInstalledUsers( 13891 sUserManager.getUserIds(), true); 13892 } 13893 } 13894 } 13895 } 13896 13897 private void startIntentFilterVerifications(int userId, boolean replacing, 13898 PackageParser.Package pkg) { 13899 if (mIntentFilterVerifierComponent == null) { 13900 Slog.w(TAG, "No IntentFilter verification will not be done as " 13901 + "there is no IntentFilterVerifier available!"); 13902 return; 13903 } 13904 13905 final int verifierUid = getPackageUid( 13906 mIntentFilterVerifierComponent.getPackageName(), 13907 MATCH_DEBUG_TRIAGED_MISSING, 13908 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 13909 13910 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 13911 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 13912 mHandler.sendMessage(msg); 13913 13914 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13915 for (int i = 0; i < childCount; i++) { 13916 PackageParser.Package childPkg = pkg.childPackages.get(i); 13917 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 13918 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 13919 mHandler.sendMessage(msg); 13920 } 13921 } 13922 13923 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 13924 PackageParser.Package pkg) { 13925 int size = pkg.activities.size(); 13926 if (size == 0) { 13927 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13928 "No activity, so no need to verify any IntentFilter!"); 13929 return; 13930 } 13931 13932 final boolean hasDomainURLs = hasDomainURLs(pkg); 13933 if (!hasDomainURLs) { 13934 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13935 "No domain URLs, so no need to verify any IntentFilter!"); 13936 return; 13937 } 13938 13939 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 13940 + " if any IntentFilter from the " + size 13941 + " Activities needs verification ..."); 13942 13943 int count = 0; 13944 final String packageName = pkg.packageName; 13945 13946 synchronized (mPackages) { 13947 // If this is a new install and we see that we've already run verification for this 13948 // package, we have nothing to do: it means the state was restored from backup. 13949 if (!replacing) { 13950 IntentFilterVerificationInfo ivi = 13951 mSettings.getIntentFilterVerificationLPr(packageName); 13952 if (ivi != null) { 13953 if (DEBUG_DOMAIN_VERIFICATION) { 13954 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 13955 + ivi.getStatusString()); 13956 } 13957 return; 13958 } 13959 } 13960 13961 // If any filters need to be verified, then all need to be. 13962 boolean needToVerify = false; 13963 for (PackageParser.Activity a : pkg.activities) { 13964 for (ActivityIntentInfo filter : a.intents) { 13965 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 13966 if (DEBUG_DOMAIN_VERIFICATION) { 13967 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 13968 } 13969 needToVerify = true; 13970 break; 13971 } 13972 } 13973 } 13974 13975 if (needToVerify) { 13976 final int verificationId = mIntentFilterVerificationToken++; 13977 for (PackageParser.Activity a : pkg.activities) { 13978 for (ActivityIntentInfo filter : a.intents) { 13979 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 13980 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13981 "Verification needed for IntentFilter:" + filter.toString()); 13982 mIntentFilterVerifier.addOneIntentFilterVerification( 13983 verifierUid, userId, verificationId, filter, packageName); 13984 count++; 13985 } 13986 } 13987 } 13988 } 13989 } 13990 13991 if (count > 0) { 13992 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 13993 + " IntentFilter verification" + (count > 1 ? "s" : "") 13994 + " for userId:" + userId); 13995 mIntentFilterVerifier.startVerifications(userId); 13996 } else { 13997 if (DEBUG_DOMAIN_VERIFICATION) { 13998 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 13999 } 14000 } 14001 } 14002 14003 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 14004 final ComponentName cn = filter.activity.getComponentName(); 14005 final String packageName = cn.getPackageName(); 14006 14007 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 14008 packageName); 14009 if (ivi == null) { 14010 return true; 14011 } 14012 int status = ivi.getStatus(); 14013 switch (status) { 14014 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 14015 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 14016 return true; 14017 14018 default: 14019 // Nothing to do 14020 return false; 14021 } 14022 } 14023 14024 private static boolean isMultiArch(ApplicationInfo info) { 14025 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 14026 } 14027 14028 private static boolean isExternal(PackageParser.Package pkg) { 14029 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14030 } 14031 14032 private static boolean isExternal(PackageSetting ps) { 14033 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14034 } 14035 14036 private static boolean isEphemeral(PackageParser.Package pkg) { 14037 return pkg.applicationInfo.isEphemeralApp(); 14038 } 14039 14040 private static boolean isEphemeral(PackageSetting ps) { 14041 return ps.pkg != null && isEphemeral(ps.pkg); 14042 } 14043 14044 private static boolean isSystemApp(PackageParser.Package pkg) { 14045 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 14046 } 14047 14048 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 14049 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14050 } 14051 14052 private static boolean hasDomainURLs(PackageParser.Package pkg) { 14053 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 14054 } 14055 14056 private static boolean isSystemApp(PackageSetting ps) { 14057 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 14058 } 14059 14060 private static boolean isUpdatedSystemApp(PackageSetting ps) { 14061 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 14062 } 14063 14064 private int packageFlagsToInstallFlags(PackageSetting ps) { 14065 int installFlags = 0; 14066 if (isEphemeral(ps)) { 14067 installFlags |= PackageManager.INSTALL_EPHEMERAL; 14068 } 14069 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 14070 // This existing package was an external ASEC install when we have 14071 // the external flag without a UUID 14072 installFlags |= PackageManager.INSTALL_EXTERNAL; 14073 } 14074 if (ps.isForwardLocked()) { 14075 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 14076 } 14077 return installFlags; 14078 } 14079 14080 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 14081 if (isExternal(pkg)) { 14082 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14083 return StorageManager.UUID_PRIMARY_PHYSICAL; 14084 } else { 14085 return pkg.volumeUuid; 14086 } 14087 } else { 14088 return StorageManager.UUID_PRIVATE_INTERNAL; 14089 } 14090 } 14091 14092 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 14093 if (isExternal(pkg)) { 14094 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14095 return mSettings.getExternalVersion(); 14096 } else { 14097 return mSettings.findOrCreateVersion(pkg.volumeUuid); 14098 } 14099 } else { 14100 return mSettings.getInternalVersion(); 14101 } 14102 } 14103 14104 private void deleteTempPackageFiles() { 14105 final FilenameFilter filter = new FilenameFilter() { 14106 public boolean accept(File dir, String name) { 14107 return name.startsWith("vmdl") && name.endsWith(".tmp"); 14108 } 14109 }; 14110 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 14111 file.delete(); 14112 } 14113 } 14114 14115 @Override 14116 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 14117 int flags) { 14118 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 14119 flags); 14120 } 14121 14122 @Override 14123 public void deletePackage(final String packageName, 14124 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 14125 mContext.enforceCallingOrSelfPermission( 14126 android.Manifest.permission.DELETE_PACKAGES, null); 14127 Preconditions.checkNotNull(packageName); 14128 Preconditions.checkNotNull(observer); 14129 final int uid = Binder.getCallingUid(); 14130 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 14131 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 14132 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 14133 mContext.enforceCallingOrSelfPermission( 14134 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14135 "deletePackage for user " + userId); 14136 } 14137 14138 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 14139 try { 14140 observer.onPackageDeleted(packageName, 14141 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 14142 } catch (RemoteException re) { 14143 } 14144 return; 14145 } 14146 14147 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 14148 try { 14149 observer.onPackageDeleted(packageName, 14150 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 14151 } catch (RemoteException re) { 14152 } 14153 return; 14154 } 14155 14156 if (DEBUG_REMOVE) { 14157 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 14158 + " deleteAllUsers: " + deleteAllUsers ); 14159 } 14160 // Queue up an async operation since the package deletion may take a little while. 14161 mHandler.post(new Runnable() { 14162 public void run() { 14163 mHandler.removeCallbacks(this); 14164 int returnCode; 14165 if (!deleteAllUsers) { 14166 returnCode = deletePackageX(packageName, userId, flags); 14167 } else { 14168 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 14169 // If nobody is blocking uninstall, proceed with delete for all users 14170 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 14171 returnCode = deletePackageX(packageName, userId, flags); 14172 } else { 14173 // Otherwise uninstall individually for users with blockUninstalls=false 14174 final int userFlags = flags & ~PackageManager.DELETE_ALL_USERS; 14175 for (int userId : users) { 14176 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 14177 returnCode = deletePackageX(packageName, userId, userFlags); 14178 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 14179 Slog.w(TAG, "Package delete failed for user " + userId 14180 + ", returnCode " + returnCode); 14181 } 14182 } 14183 } 14184 // The app has only been marked uninstalled for certain users. 14185 // We still need to report that delete was blocked 14186 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 14187 } 14188 } 14189 try { 14190 observer.onPackageDeleted(packageName, returnCode, null); 14191 } catch (RemoteException e) { 14192 Log.i(TAG, "Observer no longer exists."); 14193 } //end catch 14194 } //end run 14195 }); 14196 } 14197 14198 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 14199 int[] result = EMPTY_INT_ARRAY; 14200 for (int userId : userIds) { 14201 if (getBlockUninstallForUser(packageName, userId)) { 14202 result = ArrayUtils.appendInt(result, userId); 14203 } 14204 } 14205 return result; 14206 } 14207 14208 @Override 14209 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 14210 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 14211 } 14212 14213 private boolean isPackageDeviceAdmin(String packageName, int userId) { 14214 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 14215 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 14216 try { 14217 if (dpm != null) { 14218 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 14219 /* callingUserOnly =*/ false); 14220 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 14221 : deviceOwnerComponentName.getPackageName(); 14222 // Does the package contains the device owner? 14223 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 14224 // this check is probably not needed, since DO should be registered as a device 14225 // admin on some user too. (Original bug for this: b/17657954) 14226 if (packageName.equals(deviceOwnerPackageName)) { 14227 return true; 14228 } 14229 // Does it contain a device admin for any user? 14230 int[] users; 14231 if (userId == UserHandle.USER_ALL) { 14232 users = sUserManager.getUserIds(); 14233 } else { 14234 users = new int[]{userId}; 14235 } 14236 for (int i = 0; i < users.length; ++i) { 14237 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 14238 return true; 14239 } 14240 } 14241 } 14242 } catch (RemoteException e) { 14243 } 14244 return false; 14245 } 14246 14247 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 14248 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 14249 } 14250 14251 /** 14252 * This method is an internal method that could be get invoked either 14253 * to delete an installed package or to clean up a failed installation. 14254 * After deleting an installed package, a broadcast is sent to notify any 14255 * listeners that the package has been installed. For cleaning up a failed 14256 * installation, the broadcast is not necessary since the package's 14257 * installation wouldn't have sent the initial broadcast either 14258 * The key steps in deleting a package are 14259 * deleting the package information in internal structures like mPackages, 14260 * deleting the packages base directories through installd 14261 * updating mSettings to reflect current status 14262 * persisting settings for later use 14263 * sending a broadcast if necessary 14264 */ 14265 private int deletePackageX(String packageName, int userId, int flags) { 14266 final PackageRemovedInfo info = new PackageRemovedInfo(); 14267 final boolean res; 14268 14269 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 14270 ? UserHandle.ALL : new UserHandle(userId); 14271 14272 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 14273 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 14274 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 14275 } 14276 14277 PackageSetting uninstalledPs = null; 14278 14279 // for the uninstall-updates case and restricted profiles, remember the per- 14280 // user handle installed state 14281 int[] allUsers; 14282 synchronized (mPackages) { 14283 uninstalledPs = mSettings.mPackages.get(packageName); 14284 if (uninstalledPs == null) { 14285 Slog.w(TAG, "Not removing non-existent package " + packageName); 14286 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14287 } 14288 allUsers = sUserManager.getUserIds(); 14289 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 14290 } 14291 14292 synchronized (mInstallLock) { 14293 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 14294 res = deletePackageLI(packageName, removeForUser, true, allUsers, 14295 flags | REMOVE_CHATTY, info, true, null); 14296 synchronized (mPackages) { 14297 if (res) { 14298 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 14299 } 14300 } 14301 } 14302 14303 if (res) { 14304 info.sendPackageRemovedBroadcasts(); 14305 info.sendSystemPackageUpdatedBroadcasts(); 14306 info.sendSystemPackageAppearedBroadcasts(); 14307 } 14308 // Force a gc here. 14309 Runtime.getRuntime().gc(); 14310 // Delete the resources here after sending the broadcast to let 14311 // other processes clean up before deleting resources. 14312 if (info.args != null) { 14313 synchronized (mInstallLock) { 14314 info.args.doPostDeleteLI(true); 14315 } 14316 } 14317 14318 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14319 } 14320 14321 class PackageRemovedInfo { 14322 String removedPackage; 14323 int uid = -1; 14324 int removedAppId = -1; 14325 int[] origUsers; 14326 int[] removedUsers = null; 14327 boolean isRemovedPackageSystemUpdate = false; 14328 boolean isUpdate; 14329 boolean dataRemoved; 14330 boolean removedForAllUsers; 14331 // Clean up resources deleted packages. 14332 InstallArgs args = null; 14333 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 14334 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 14335 14336 void sendPackageRemovedBroadcasts() { 14337 sendPackageRemovedBroadcastInternal(); 14338 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 14339 for (int i = 0; i < childCount; i++) { 14340 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 14341 childInfo.sendPackageRemovedBroadcastInternal(); 14342 } 14343 } 14344 14345 void sendSystemPackageUpdatedBroadcasts() { 14346 if (isRemovedPackageSystemUpdate) { 14347 sendSystemPackageUpdatedBroadcastsInternal(); 14348 final int childCount = (removedChildPackages != null) 14349 ? removedChildPackages.size() : 0; 14350 for (int i = 0; i < childCount; i++) { 14351 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 14352 if (childInfo.isRemovedPackageSystemUpdate) { 14353 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 14354 } 14355 } 14356 } 14357 } 14358 14359 void sendSystemPackageAppearedBroadcasts() { 14360 final int packageCount = (appearedChildPackages != null) 14361 ? appearedChildPackages.size() : 0; 14362 for (int i = 0; i < packageCount; i++) { 14363 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 14364 for (int userId : installedInfo.newUsers) { 14365 sendPackageAddedForUser(installedInfo.name, true, 14366 UserHandle.getAppId(installedInfo.uid), userId); 14367 } 14368 } 14369 } 14370 14371 private void sendSystemPackageUpdatedBroadcastsInternal() { 14372 Bundle extras = new Bundle(2); 14373 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 14374 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14375 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 14376 extras, 0, null, null, null); 14377 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 14378 extras, 0, null, null, null); 14379 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 14380 null, 0, removedPackage, null, null); 14381 } 14382 14383 private void sendPackageRemovedBroadcastInternal() { 14384 Bundle extras = new Bundle(2); 14385 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 14386 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 14387 if (isUpdate || isRemovedPackageSystemUpdate) { 14388 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14389 } 14390 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 14391 if (removedPackage != null) { 14392 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 14393 extras, 0, null, null, removedUsers); 14394 if (dataRemoved && !isRemovedPackageSystemUpdate) { 14395 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 14396 removedPackage, extras, 0, null, null, removedUsers); 14397 } 14398 } 14399 if (removedAppId >= 0) { 14400 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 14401 removedUsers); 14402 } 14403 } 14404 } 14405 14406 /* 14407 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 14408 * flag is not set, the data directory is removed as well. 14409 * make sure this flag is set for partially installed apps. If not its meaningless to 14410 * delete a partially installed application. 14411 */ 14412 private void removePackageDataLI(PackageSetting ps, int[] allUserHandles, 14413 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 14414 String packageName = ps.name; 14415 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 14416 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 14417 // Retrieve object to delete permissions for shared user later on 14418 final PackageSetting deletedPs; 14419 // reader 14420 synchronized (mPackages) { 14421 deletedPs = mSettings.mPackages.get(packageName); 14422 if (outInfo != null) { 14423 outInfo.removedPackage = packageName; 14424 outInfo.removedUsers = deletedPs != null 14425 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 14426 : null; 14427 } 14428 } 14429 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 14430 removeDataDirsLI(ps.volumeUuid, packageName); 14431 if (outInfo != null) { 14432 outInfo.dataRemoved = true; 14433 } 14434 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 14435 } 14436 // writer 14437 synchronized (mPackages) { 14438 if (deletedPs != null) { 14439 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 14440 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 14441 clearDefaultBrowserIfNeeded(packageName); 14442 if (outInfo != null) { 14443 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 14444 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 14445 } 14446 updatePermissionsLPw(deletedPs.name, null, 0); 14447 if (deletedPs.sharedUser != null) { 14448 // Remove permissions associated with package. Since runtime 14449 // permissions are per user we have to kill the removed package 14450 // or packages running under the shared user of the removed 14451 // package if revoking the permissions requested only by the removed 14452 // package is successful and this causes a change in gids. 14453 for (int userId : UserManagerService.getInstance().getUserIds()) { 14454 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 14455 userId); 14456 if (userIdToKill == UserHandle.USER_ALL 14457 || userIdToKill >= UserHandle.USER_SYSTEM) { 14458 // If gids changed for this user, kill all affected packages. 14459 mHandler.post(new Runnable() { 14460 @Override 14461 public void run() { 14462 // This has to happen with no lock held. 14463 killApplication(deletedPs.name, deletedPs.appId, 14464 KILL_APP_REASON_GIDS_CHANGED); 14465 } 14466 }); 14467 break; 14468 } 14469 } 14470 } 14471 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 14472 } 14473 // make sure to preserve per-user disabled state if this removal was just 14474 // a downgrade of a system app to the factory package 14475 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 14476 if (DEBUG_REMOVE) { 14477 Slog.d(TAG, "Propagating install state across downgrade"); 14478 } 14479 for (int userId : allUserHandles) { 14480 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 14481 if (DEBUG_REMOVE) { 14482 Slog.d(TAG, " user " + userId + " => " + installed); 14483 } 14484 ps.setInstalled(installed, userId); 14485 } 14486 } 14487 } 14488 // can downgrade to reader 14489 if (writeSettings) { 14490 // Save settings now 14491 mSettings.writeLPr(); 14492 } 14493 } 14494 if (outInfo != null) { 14495 // A user ID was deleted here. Go through all users and remove it 14496 // from KeyStore. 14497 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 14498 } 14499 } 14500 14501 static boolean locationIsPrivileged(File path) { 14502 try { 14503 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 14504 .getCanonicalPath(); 14505 return path.getCanonicalPath().startsWith(privilegedAppDir); 14506 } catch (IOException e) { 14507 Slog.e(TAG, "Unable to access code path " + path); 14508 } 14509 return false; 14510 } 14511 14512 /* 14513 * Tries to delete system package. 14514 */ 14515 private boolean deleteSystemPackageLI(PackageParser.Package deletedPkg, 14516 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 14517 boolean writeSettings) { 14518 if (deletedPs.parentPackageName != null) { 14519 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 14520 return false; 14521 } 14522 14523 final boolean applyUserRestrictions 14524 = (allUserHandles != null) && (outInfo.origUsers != null); 14525 final PackageSetting disabledPs; 14526 // Confirm if the system package has been updated 14527 // An updated system app can be deleted. This will also have to restore 14528 // the system pkg from system partition 14529 // reader 14530 synchronized (mPackages) { 14531 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 14532 } 14533 14534 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 14535 + " disabledPs=" + disabledPs); 14536 14537 if (disabledPs == null) { 14538 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 14539 return false; 14540 } else if (DEBUG_REMOVE) { 14541 Slog.d(TAG, "Deleting system pkg from data partition"); 14542 } 14543 14544 if (DEBUG_REMOVE) { 14545 if (applyUserRestrictions) { 14546 Slog.d(TAG, "Remembering install states:"); 14547 for (int userId : allUserHandles) { 14548 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 14549 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 14550 } 14551 } 14552 } 14553 14554 // Delete the updated package 14555 outInfo.isRemovedPackageSystemUpdate = true; 14556 if (outInfo.removedChildPackages != null) { 14557 final int childCount = (deletedPs.childPackageNames != null) 14558 ? deletedPs.childPackageNames.size() : 0; 14559 for (int i = 0; i < childCount; i++) { 14560 String childPackageName = deletedPs.childPackageNames.get(i); 14561 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 14562 .contains(childPackageName)) { 14563 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 14564 childPackageName); 14565 if (childInfo != null) { 14566 childInfo.isRemovedPackageSystemUpdate = true; 14567 } 14568 } 14569 } 14570 } 14571 14572 if (disabledPs.versionCode < deletedPs.versionCode) { 14573 // Delete data for downgrades 14574 flags &= ~PackageManager.DELETE_KEEP_DATA; 14575 } else { 14576 // Preserve data by setting flag 14577 flags |= PackageManager.DELETE_KEEP_DATA; 14578 } 14579 14580 boolean ret = deleteInstalledPackageLI(deletedPs, true, flags, allUserHandles, 14581 outInfo, writeSettings, disabledPs.pkg); 14582 if (!ret) { 14583 return false; 14584 } 14585 14586 // writer 14587 synchronized (mPackages) { 14588 // Reinstate the old system package 14589 enableSystemPackageLPw(disabledPs.pkg); 14590 // Remove any native libraries from the upgraded package. 14591 removeNativeBinariesLI(deletedPs); 14592 } 14593 14594 // Install the system package 14595 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 14596 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 14597 if (locationIsPrivileged(disabledPs.codePath)) { 14598 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 14599 } 14600 14601 final PackageParser.Package newPkg; 14602 try { 14603 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 14604 } catch (PackageManagerException e) { 14605 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 14606 + e.getMessage()); 14607 return false; 14608 } 14609 14610 prepareAppDataAfterInstall(newPkg); 14611 14612 // writer 14613 synchronized (mPackages) { 14614 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 14615 14616 // Propagate the permissions state as we do not want to drop on the floor 14617 // runtime permissions. The update permissions method below will take 14618 // care of removing obsolete permissions and grant install permissions. 14619 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 14620 updatePermissionsLPw(newPkg.packageName, newPkg, 14621 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 14622 14623 if (applyUserRestrictions) { 14624 if (DEBUG_REMOVE) { 14625 Slog.d(TAG, "Propagating install state across reinstall"); 14626 } 14627 for (int userId : allUserHandles) { 14628 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 14629 if (DEBUG_REMOVE) { 14630 Slog.d(TAG, " user " + userId + " => " + installed); 14631 } 14632 ps.setInstalled(installed, userId); 14633 14634 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 14635 } 14636 // Regardless of writeSettings we need to ensure that this restriction 14637 // state propagation is persisted 14638 mSettings.writeAllUsersPackageRestrictionsLPr(); 14639 } 14640 // can downgrade to reader here 14641 if (writeSettings) { 14642 mSettings.writeLPr(); 14643 } 14644 } 14645 return true; 14646 } 14647 14648 private boolean deleteInstalledPackageLI(PackageSetting ps, 14649 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 14650 PackageRemovedInfo outInfo, boolean writeSettings, 14651 PackageParser.Package replacingPackage) { 14652 synchronized (mPackages) { 14653 if (outInfo != null) { 14654 outInfo.uid = ps.appId; 14655 } 14656 14657 if (outInfo != null && outInfo.removedChildPackages != null) { 14658 final int childCount = (ps.childPackageNames != null) 14659 ? ps.childPackageNames.size() : 0; 14660 for (int i = 0; i < childCount; i++) { 14661 String childPackageName = ps.childPackageNames.get(i); 14662 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 14663 if (childPs == null) { 14664 return false; 14665 } 14666 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 14667 childPackageName); 14668 if (childInfo != null) { 14669 childInfo.uid = childPs.appId; 14670 } 14671 } 14672 } 14673 } 14674 14675 // Delete package data from internal structures and also remove data if flag is set 14676 removePackageDataLI(ps, allUserHandles, outInfo, flags, writeSettings); 14677 14678 // Delete the child packages data 14679 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14680 for (int i = 0; i < childCount; i++) { 14681 PackageSetting childPs; 14682 synchronized (mPackages) { 14683 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14684 } 14685 if (childPs != null) { 14686 PackageRemovedInfo childOutInfo = (outInfo != null 14687 && outInfo.removedChildPackages != null) 14688 ? outInfo.removedChildPackages.get(childPs.name) : null; 14689 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 14690 && (replacingPackage != null 14691 && !replacingPackage.hasChildPackage(childPs.name)) 14692 ? flags & ~DELETE_KEEP_DATA : flags; 14693 removePackageDataLI(childPs, allUserHandles, childOutInfo, 14694 deleteFlags, writeSettings); 14695 } 14696 } 14697 14698 // Delete application code and resources only for parent packages 14699 if (ps.parentPackageName == null) { 14700 if (deleteCodeAndResources && (outInfo != null)) { 14701 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 14702 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 14703 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 14704 } 14705 } 14706 14707 return true; 14708 } 14709 14710 @Override 14711 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 14712 int userId) { 14713 mContext.enforceCallingOrSelfPermission( 14714 android.Manifest.permission.DELETE_PACKAGES, null); 14715 synchronized (mPackages) { 14716 PackageSetting ps = mSettings.mPackages.get(packageName); 14717 if (ps == null) { 14718 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 14719 return false; 14720 } 14721 if (!ps.getInstalled(userId)) { 14722 // Can't block uninstall for an app that is not installed or enabled. 14723 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 14724 return false; 14725 } 14726 ps.setBlockUninstall(blockUninstall, userId); 14727 mSettings.writePackageRestrictionsLPr(userId); 14728 } 14729 return true; 14730 } 14731 14732 @Override 14733 public boolean getBlockUninstallForUser(String packageName, int userId) { 14734 synchronized (mPackages) { 14735 PackageSetting ps = mSettings.mPackages.get(packageName); 14736 if (ps == null) { 14737 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 14738 return false; 14739 } 14740 return ps.getBlockUninstall(userId); 14741 } 14742 } 14743 14744 @Override 14745 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 14746 int callingUid = Binder.getCallingUid(); 14747 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 14748 throw new SecurityException( 14749 "setRequiredForSystemUser can only be run by the system or root"); 14750 } 14751 synchronized (mPackages) { 14752 PackageSetting ps = mSettings.mPackages.get(packageName); 14753 if (ps == null) { 14754 Log.w(TAG, "Package doesn't exist: " + packageName); 14755 return false; 14756 } 14757 if (systemUserApp) { 14758 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 14759 } else { 14760 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 14761 } 14762 mSettings.writeLPr(); 14763 } 14764 return true; 14765 } 14766 14767 /* 14768 * This method handles package deletion in general 14769 */ 14770 private boolean deletePackageLI(String packageName, UserHandle user, 14771 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 14772 PackageRemovedInfo outInfo, boolean writeSettings, 14773 PackageParser.Package replacingPackage) { 14774 if (packageName == null) { 14775 Slog.w(TAG, "Attempt to delete null packageName."); 14776 return false; 14777 } 14778 14779 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 14780 14781 PackageSetting ps; 14782 14783 synchronized (mPackages) { 14784 ps = mSettings.mPackages.get(packageName); 14785 if (ps == null) { 14786 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 14787 return false; 14788 } 14789 14790 if (ps.parentPackageName != null && (!isSystemApp(ps) 14791 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 14792 if (DEBUG_REMOVE) { 14793 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 14794 + ((user == null) ? UserHandle.USER_ALL : user)); 14795 } 14796 final int removedUserId = (user != null) ? user.getIdentifier() 14797 : UserHandle.USER_ALL; 14798 if (!clearPackageStateForUser(ps, removedUserId, outInfo)) { 14799 return false; 14800 } 14801 markPackageUninstalledForUserLPw(ps, user); 14802 scheduleWritePackageRestrictionsLocked(user); 14803 return true; 14804 } 14805 } 14806 14807 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 14808 && user.getIdentifier() != UserHandle.USER_ALL)) { 14809 // The caller is asking that the package only be deleted for a single 14810 // user. To do this, we just mark its uninstalled state and delete 14811 // its data. If this is a system app, we only allow this to happen if 14812 // they have set the special DELETE_SYSTEM_APP which requests different 14813 // semantics than normal for uninstalling system apps. 14814 markPackageUninstalledForUserLPw(ps, user); 14815 14816 if (!isSystemApp(ps)) { 14817 // Do not uninstall the APK if an app should be cached 14818 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 14819 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 14820 // Other user still have this package installed, so all 14821 // we need to do is clear this user's data and save that 14822 // it is uninstalled. 14823 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 14824 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 14825 return false; 14826 } 14827 scheduleWritePackageRestrictionsLocked(user); 14828 return true; 14829 } else { 14830 // We need to set it back to 'installed' so the uninstall 14831 // broadcasts will be sent correctly. 14832 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 14833 ps.setInstalled(true, user.getIdentifier()); 14834 } 14835 } else { 14836 // This is a system app, so we assume that the 14837 // other users still have this package installed, so all 14838 // we need to do is clear this user's data and save that 14839 // it is uninstalled. 14840 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 14841 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 14842 return false; 14843 } 14844 scheduleWritePackageRestrictionsLocked(user); 14845 return true; 14846 } 14847 } 14848 14849 // If we are deleting a composite package for all users, keep track 14850 // of result for each child. 14851 if (ps.childPackageNames != null && outInfo != null) { 14852 synchronized (mPackages) { 14853 final int childCount = ps.childPackageNames.size(); 14854 outInfo.removedChildPackages = new ArrayMap<>(childCount); 14855 for (int i = 0; i < childCount; i++) { 14856 String childPackageName = ps.childPackageNames.get(i); 14857 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 14858 childInfo.removedPackage = childPackageName; 14859 outInfo.removedChildPackages.put(childPackageName, childInfo); 14860 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 14861 if (childPs != null) { 14862 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 14863 } 14864 } 14865 } 14866 } 14867 14868 boolean ret = false; 14869 if (isSystemApp(ps)) { 14870 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 14871 // When an updated system application is deleted we delete the existing resources 14872 // as well and fall back to existing code in system partition 14873 ret = deleteSystemPackageLI(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 14874 } else { 14875 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 14876 // Kill application pre-emptively especially for apps on sd. 14877 killApplication(packageName, ps.appId, "uninstall pkg"); 14878 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, allUserHandles, 14879 outInfo, writeSettings, replacingPackage); 14880 } 14881 14882 // Take a note whether we deleted the package for all users 14883 if (outInfo != null) { 14884 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14885 if (outInfo.removedChildPackages != null) { 14886 synchronized (mPackages) { 14887 final int childCount = outInfo.removedChildPackages.size(); 14888 for (int i = 0; i < childCount; i++) { 14889 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 14890 if (childInfo != null) { 14891 childInfo.removedForAllUsers = mPackages.get( 14892 childInfo.removedPackage) == null; 14893 } 14894 } 14895 } 14896 } 14897 // If we uninstalled an update to a system app there may be some 14898 // child packages that appeared as they are declared in the system 14899 // app but were not declared in the update. 14900 if (isSystemApp(ps)) { 14901 synchronized (mPackages) { 14902 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 14903 final int childCount = (updatedPs.childPackageNames != null) 14904 ? updatedPs.childPackageNames.size() : 0; 14905 for (int i = 0; i < childCount; i++) { 14906 String childPackageName = updatedPs.childPackageNames.get(i); 14907 if (outInfo.removedChildPackages == null 14908 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 14909 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 14910 if (childPs == null) { 14911 continue; 14912 } 14913 PackageInstalledInfo installRes = new PackageInstalledInfo(); 14914 installRes.name = childPackageName; 14915 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 14916 installRes.pkg = mPackages.get(childPackageName); 14917 installRes.uid = childPs.pkg.applicationInfo.uid; 14918 if (outInfo.appearedChildPackages == null) { 14919 outInfo.appearedChildPackages = new ArrayMap<>(); 14920 } 14921 outInfo.appearedChildPackages.put(childPackageName, installRes); 14922 } 14923 } 14924 } 14925 } 14926 } 14927 14928 return ret; 14929 } 14930 14931 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 14932 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 14933 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 14934 for (int nextUserId : userIds) { 14935 if (DEBUG_REMOVE) { 14936 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 14937 } 14938 ps.setUserState(nextUserId, COMPONENT_ENABLED_STATE_DEFAULT, 14939 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 14940 false /*hidden*/, false /*suspended*/, null, null, null, 14941 false /*blockUninstall*/, 14942 ps.readUserState(nextUserId).domainVerificationStatus, 0); 14943 } 14944 } 14945 14946 private boolean clearPackageStateForUser(PackageSetting ps, int userId, 14947 PackageRemovedInfo outInfo) { 14948 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 14949 : new int[] {userId}; 14950 for (int nextUserId : userIds) { 14951 if (DEBUG_REMOVE) { 14952 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 14953 + nextUserId); 14954 } 14955 final int flags = StorageManager.FLAG_STORAGE_CE| StorageManager.FLAG_STORAGE_DE; 14956 try { 14957 mInstaller.destroyAppData(ps.volumeUuid, ps.name, nextUserId, flags); 14958 } catch (InstallerException e) { 14959 Slog.w(TAG, "Couldn't remove cache files for package " + ps.name, e); 14960 return false; 14961 } 14962 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 14963 schedulePackageCleaning(ps.name, nextUserId, false); 14964 synchronized (mPackages) { 14965 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 14966 scheduleWritePackageRestrictionsLocked(nextUserId); 14967 } 14968 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 14969 } 14970 } 14971 14972 if (outInfo != null) { 14973 outInfo.removedPackage = ps.name; 14974 outInfo.removedAppId = ps.appId; 14975 outInfo.removedUsers = userIds; 14976 } 14977 14978 return true; 14979 } 14980 14981 private final class ClearStorageConnection implements ServiceConnection { 14982 IMediaContainerService mContainerService; 14983 14984 @Override 14985 public void onServiceConnected(ComponentName name, IBinder service) { 14986 synchronized (this) { 14987 mContainerService = IMediaContainerService.Stub.asInterface(service); 14988 notifyAll(); 14989 } 14990 } 14991 14992 @Override 14993 public void onServiceDisconnected(ComponentName name) { 14994 } 14995 } 14996 14997 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 14998 final boolean mounted; 14999 if (Environment.isExternalStorageEmulated()) { 15000 mounted = true; 15001 } else { 15002 final String status = Environment.getExternalStorageState(); 15003 15004 mounted = status.equals(Environment.MEDIA_MOUNTED) 15005 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 15006 } 15007 15008 if (!mounted) { 15009 return; 15010 } 15011 15012 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 15013 int[] users; 15014 if (userId == UserHandle.USER_ALL) { 15015 users = sUserManager.getUserIds(); 15016 } else { 15017 users = new int[] { userId }; 15018 } 15019 final ClearStorageConnection conn = new ClearStorageConnection(); 15020 if (mContext.bindServiceAsUser( 15021 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 15022 try { 15023 for (int curUser : users) { 15024 long timeout = SystemClock.uptimeMillis() + 5000; 15025 synchronized (conn) { 15026 long now = SystemClock.uptimeMillis(); 15027 while (conn.mContainerService == null && now < timeout) { 15028 try { 15029 conn.wait(timeout - now); 15030 } catch (InterruptedException e) { 15031 } 15032 } 15033 } 15034 if (conn.mContainerService == null) { 15035 return; 15036 } 15037 15038 final UserEnvironment userEnv = new UserEnvironment(curUser); 15039 clearDirectory(conn.mContainerService, 15040 userEnv.buildExternalStorageAppCacheDirs(packageName)); 15041 if (allData) { 15042 clearDirectory(conn.mContainerService, 15043 userEnv.buildExternalStorageAppDataDirs(packageName)); 15044 clearDirectory(conn.mContainerService, 15045 userEnv.buildExternalStorageAppMediaDirs(packageName)); 15046 } 15047 } 15048 } finally { 15049 mContext.unbindService(conn); 15050 } 15051 } 15052 } 15053 15054 @Override 15055 public void clearApplicationUserData(final String packageName, 15056 final IPackageDataObserver observer, final int userId) { 15057 mContext.enforceCallingOrSelfPermission( 15058 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 15059 enforceCrossUserPermission(Binder.getCallingUid(), userId, 15060 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 15061 // Queue up an async operation since the package deletion may take a little while. 15062 mHandler.post(new Runnable() { 15063 public void run() { 15064 mHandler.removeCallbacks(this); 15065 final boolean succeeded; 15066 synchronized (mInstallLock) { 15067 succeeded = clearApplicationUserDataLI(packageName, userId); 15068 } 15069 clearExternalStorageDataSync(packageName, userId, true); 15070 if (succeeded) { 15071 // invoke DeviceStorageMonitor's update method to clear any notifications 15072 DeviceStorageMonitorInternal 15073 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 15074 if (dsm != null) { 15075 dsm.checkMemory(); 15076 } 15077 } 15078 if(observer != null) { 15079 try { 15080 observer.onRemoveCompleted(packageName, succeeded); 15081 } catch (RemoteException e) { 15082 Log.i(TAG, "Observer no longer exists."); 15083 } 15084 } //end if observer 15085 } //end run 15086 }); 15087 } 15088 15089 private boolean clearApplicationUserDataLI(String packageName, int userId) { 15090 if (packageName == null) { 15091 Slog.w(TAG, "Attempt to delete null packageName."); 15092 return false; 15093 } 15094 15095 // Try finding details about the requested package 15096 PackageParser.Package pkg; 15097 synchronized (mPackages) { 15098 pkg = mPackages.get(packageName); 15099 if (pkg == null) { 15100 final PackageSetting ps = mSettings.mPackages.get(packageName); 15101 if (ps != null) { 15102 pkg = ps.pkg; 15103 } 15104 } 15105 15106 if (pkg == null) { 15107 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15108 return false; 15109 } 15110 15111 PackageSetting ps = (PackageSetting) pkg.mExtras; 15112 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15113 } 15114 15115 // Always delete data directories for package, even if we found no other 15116 // record of app. This helps users recover from UID mismatches without 15117 // resorting to a full data wipe. 15118 // TODO: triage flags as part of 26466827 15119 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15120 try { 15121 mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags); 15122 } catch (InstallerException e) { 15123 Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e); 15124 return false; 15125 } 15126 15127 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15128 removeKeystoreDataIfNeeded(userId, appId); 15129 15130 // Create a native library symlink only if we have native libraries 15131 // and if the native libraries are 32 bit libraries. We do not provide 15132 // this symlink for 64 bit libraries. 15133 if (pkg.applicationInfo.primaryCpuAbi != null && 15134 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 15135 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 15136 try { 15137 mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 15138 nativeLibPath, userId); 15139 } catch (InstallerException e) { 15140 Slog.w(TAG, "Failed linking native library dir", e); 15141 return false; 15142 } 15143 } 15144 15145 return true; 15146 } 15147 15148 /** 15149 * Reverts user permission state changes (permissions and flags) in 15150 * all packages for a given user. 15151 * 15152 * @param userId The device user for which to do a reset. 15153 */ 15154 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 15155 final int packageCount = mPackages.size(); 15156 for (int i = 0; i < packageCount; i++) { 15157 PackageParser.Package pkg = mPackages.valueAt(i); 15158 PackageSetting ps = (PackageSetting) pkg.mExtras; 15159 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15160 } 15161 } 15162 15163 /** 15164 * Reverts user permission state changes (permissions and flags). 15165 * 15166 * @param ps The package for which to reset. 15167 * @param userId The device user for which to do a reset. 15168 */ 15169 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 15170 final PackageSetting ps, final int userId) { 15171 if (ps.pkg == null) { 15172 return; 15173 } 15174 15175 // These are flags that can change base on user actions. 15176 final int userSettableMask = FLAG_PERMISSION_USER_SET 15177 | FLAG_PERMISSION_USER_FIXED 15178 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 15179 | FLAG_PERMISSION_REVIEW_REQUIRED; 15180 15181 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 15182 | FLAG_PERMISSION_POLICY_FIXED; 15183 15184 boolean writeInstallPermissions = false; 15185 boolean writeRuntimePermissions = false; 15186 15187 final int permissionCount = ps.pkg.requestedPermissions.size(); 15188 for (int i = 0; i < permissionCount; i++) { 15189 String permission = ps.pkg.requestedPermissions.get(i); 15190 15191 BasePermission bp = mSettings.mPermissions.get(permission); 15192 if (bp == null) { 15193 continue; 15194 } 15195 15196 // If shared user we just reset the state to which only this app contributed. 15197 if (ps.sharedUser != null) { 15198 boolean used = false; 15199 final int packageCount = ps.sharedUser.packages.size(); 15200 for (int j = 0; j < packageCount; j++) { 15201 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 15202 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 15203 && pkg.pkg.requestedPermissions.contains(permission)) { 15204 used = true; 15205 break; 15206 } 15207 } 15208 if (used) { 15209 continue; 15210 } 15211 } 15212 15213 PermissionsState permissionsState = ps.getPermissionsState(); 15214 15215 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 15216 15217 // Always clear the user settable flags. 15218 final boolean hasInstallState = permissionsState.getInstallPermissionState( 15219 bp.name) != null; 15220 // If permission review is enabled and this is a legacy app, mark the 15221 // permission as requiring a review as this is the initial state. 15222 int flags = 0; 15223 if (Build.PERMISSIONS_REVIEW_REQUIRED 15224 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 15225 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 15226 } 15227 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 15228 if (hasInstallState) { 15229 writeInstallPermissions = true; 15230 } else { 15231 writeRuntimePermissions = true; 15232 } 15233 } 15234 15235 // Below is only runtime permission handling. 15236 if (!bp.isRuntime()) { 15237 continue; 15238 } 15239 15240 // Never clobber system or policy. 15241 if ((oldFlags & policyOrSystemFlags) != 0) { 15242 continue; 15243 } 15244 15245 // If this permission was granted by default, make sure it is. 15246 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 15247 if (permissionsState.grantRuntimePermission(bp, userId) 15248 != PERMISSION_OPERATION_FAILURE) { 15249 writeRuntimePermissions = true; 15250 } 15251 // If permission review is enabled the permissions for a legacy apps 15252 // are represented as constantly granted runtime ones, so don't revoke. 15253 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 15254 // Otherwise, reset the permission. 15255 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 15256 switch (revokeResult) { 15257 case PERMISSION_OPERATION_SUCCESS: { 15258 writeRuntimePermissions = true; 15259 } break; 15260 15261 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 15262 writeRuntimePermissions = true; 15263 final int appId = ps.appId; 15264 mHandler.post(new Runnable() { 15265 @Override 15266 public void run() { 15267 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 15268 } 15269 }); 15270 } break; 15271 } 15272 } 15273 } 15274 15275 // Synchronously write as we are taking permissions away. 15276 if (writeRuntimePermissions) { 15277 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 15278 } 15279 15280 // Synchronously write as we are taking permissions away. 15281 if (writeInstallPermissions) { 15282 mSettings.writeLPr(); 15283 } 15284 } 15285 15286 /** 15287 * Remove entries from the keystore daemon. Will only remove it if the 15288 * {@code appId} is valid. 15289 */ 15290 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 15291 if (appId < 0) { 15292 return; 15293 } 15294 15295 final KeyStore keyStore = KeyStore.getInstance(); 15296 if (keyStore != null) { 15297 if (userId == UserHandle.USER_ALL) { 15298 for (final int individual : sUserManager.getUserIds()) { 15299 keyStore.clearUid(UserHandle.getUid(individual, appId)); 15300 } 15301 } else { 15302 keyStore.clearUid(UserHandle.getUid(userId, appId)); 15303 } 15304 } else { 15305 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 15306 } 15307 } 15308 15309 @Override 15310 public void deleteApplicationCacheFiles(final String packageName, 15311 final IPackageDataObserver observer) { 15312 mContext.enforceCallingOrSelfPermission( 15313 android.Manifest.permission.DELETE_CACHE_FILES, null); 15314 // Queue up an async operation since the package deletion may take a little while. 15315 final int userId = UserHandle.getCallingUserId(); 15316 mHandler.post(new Runnable() { 15317 public void run() { 15318 mHandler.removeCallbacks(this); 15319 final boolean succeded; 15320 synchronized (mInstallLock) { 15321 succeded = deleteApplicationCacheFilesLI(packageName, userId); 15322 } 15323 clearExternalStorageDataSync(packageName, userId, false); 15324 if (observer != null) { 15325 try { 15326 observer.onRemoveCompleted(packageName, succeded); 15327 } catch (RemoteException e) { 15328 Log.i(TAG, "Observer no longer exists."); 15329 } 15330 } //end if observer 15331 } //end run 15332 }); 15333 } 15334 15335 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 15336 if (packageName == null) { 15337 Slog.w(TAG, "Attempt to delete null packageName."); 15338 return false; 15339 } 15340 PackageParser.Package p; 15341 synchronized (mPackages) { 15342 p = mPackages.get(packageName); 15343 } 15344 if (p == null) { 15345 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 15346 return false; 15347 } 15348 final ApplicationInfo applicationInfo = p.applicationInfo; 15349 if (applicationInfo == null) { 15350 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 15351 return false; 15352 } 15353 // TODO: triage flags as part of 26466827 15354 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15355 try { 15356 mInstaller.clearAppData(p.volumeUuid, packageName, userId, 15357 flags | Installer.FLAG_CLEAR_CACHE_ONLY); 15358 } catch (InstallerException e) { 15359 Slog.w(TAG, "Couldn't remove cache files for package " 15360 + packageName + " u" + userId, e); 15361 return false; 15362 } 15363 return true; 15364 } 15365 15366 @Override 15367 public void getPackageSizeInfo(final String packageName, int userHandle, 15368 final IPackageStatsObserver observer) { 15369 mContext.enforceCallingOrSelfPermission( 15370 android.Manifest.permission.GET_PACKAGE_SIZE, null); 15371 if (packageName == null) { 15372 throw new IllegalArgumentException("Attempt to get size of null packageName"); 15373 } 15374 15375 PackageStats stats = new PackageStats(packageName, userHandle); 15376 15377 /* 15378 * Queue up an async operation since the package measurement may take a 15379 * little while. 15380 */ 15381 Message msg = mHandler.obtainMessage(INIT_COPY); 15382 msg.obj = new MeasureParams(stats, observer); 15383 mHandler.sendMessage(msg); 15384 } 15385 15386 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 15387 PackageStats pStats) { 15388 if (packageName == null) { 15389 Slog.w(TAG, "Attempt to get size of null packageName."); 15390 return false; 15391 } 15392 PackageParser.Package p; 15393 boolean dataOnly = false; 15394 String libDirRoot = null; 15395 String asecPath = null; 15396 PackageSetting ps = null; 15397 synchronized (mPackages) { 15398 p = mPackages.get(packageName); 15399 ps = mSettings.mPackages.get(packageName); 15400 if(p == null) { 15401 dataOnly = true; 15402 if((ps == null) || (ps.pkg == null)) { 15403 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 15404 return false; 15405 } 15406 p = ps.pkg; 15407 } 15408 if (ps != null) { 15409 libDirRoot = ps.legacyNativeLibraryPathString; 15410 } 15411 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 15412 final long token = Binder.clearCallingIdentity(); 15413 try { 15414 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 15415 if (secureContainerId != null) { 15416 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 15417 } 15418 } finally { 15419 Binder.restoreCallingIdentity(token); 15420 } 15421 } 15422 } 15423 String publicSrcDir = null; 15424 if(!dataOnly) { 15425 final ApplicationInfo applicationInfo = p.applicationInfo; 15426 if (applicationInfo == null) { 15427 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 15428 return false; 15429 } 15430 if (p.isForwardLocked()) { 15431 publicSrcDir = applicationInfo.getBaseResourcePath(); 15432 } 15433 } 15434 // TODO: extend to measure size of split APKs 15435 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 15436 // not just the first level. 15437 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 15438 // just the primary. 15439 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 15440 15441 String apkPath; 15442 File packageDir = new File(p.codePath); 15443 15444 if (packageDir.isDirectory() && p.canHaveOatDir()) { 15445 apkPath = packageDir.getAbsolutePath(); 15446 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 15447 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 15448 libDirRoot = null; 15449 } 15450 } else { 15451 apkPath = p.baseCodePath; 15452 } 15453 15454 // TODO: triage flags as part of 26466827 15455 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15456 try { 15457 mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath, 15458 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 15459 } catch (InstallerException e) { 15460 return false; 15461 } 15462 15463 // Fix-up for forward-locked applications in ASEC containers. 15464 if (!isExternal(p)) { 15465 pStats.codeSize += pStats.externalCodeSize; 15466 pStats.externalCodeSize = 0L; 15467 } 15468 15469 return true; 15470 } 15471 15472 15473 @Override 15474 public void addPackageToPreferred(String packageName) { 15475 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 15476 } 15477 15478 @Override 15479 public void removePackageFromPreferred(String packageName) { 15480 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 15481 } 15482 15483 @Override 15484 public List<PackageInfo> getPreferredPackages(int flags) { 15485 return new ArrayList<PackageInfo>(); 15486 } 15487 15488 private int getUidTargetSdkVersionLockedLPr(int uid) { 15489 Object obj = mSettings.getUserIdLPr(uid); 15490 if (obj instanceof SharedUserSetting) { 15491 final SharedUserSetting sus = (SharedUserSetting) obj; 15492 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 15493 final Iterator<PackageSetting> it = sus.packages.iterator(); 15494 while (it.hasNext()) { 15495 final PackageSetting ps = it.next(); 15496 if (ps.pkg != null) { 15497 int v = ps.pkg.applicationInfo.targetSdkVersion; 15498 if (v < vers) vers = v; 15499 } 15500 } 15501 return vers; 15502 } else if (obj instanceof PackageSetting) { 15503 final PackageSetting ps = (PackageSetting) obj; 15504 if (ps.pkg != null) { 15505 return ps.pkg.applicationInfo.targetSdkVersion; 15506 } 15507 } 15508 return Build.VERSION_CODES.CUR_DEVELOPMENT; 15509 } 15510 15511 @Override 15512 public void addPreferredActivity(IntentFilter filter, int match, 15513 ComponentName[] set, ComponentName activity, int userId) { 15514 addPreferredActivityInternal(filter, match, set, activity, true, userId, 15515 "Adding preferred"); 15516 } 15517 15518 private void addPreferredActivityInternal(IntentFilter filter, int match, 15519 ComponentName[] set, ComponentName activity, boolean always, int userId, 15520 String opname) { 15521 // writer 15522 int callingUid = Binder.getCallingUid(); 15523 enforceCrossUserPermission(callingUid, userId, 15524 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 15525 if (filter.countActions() == 0) { 15526 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 15527 return; 15528 } 15529 synchronized (mPackages) { 15530 if (mContext.checkCallingOrSelfPermission( 15531 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15532 != PackageManager.PERMISSION_GRANTED) { 15533 if (getUidTargetSdkVersionLockedLPr(callingUid) 15534 < Build.VERSION_CODES.FROYO) { 15535 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 15536 + callingUid); 15537 return; 15538 } 15539 mContext.enforceCallingOrSelfPermission( 15540 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15541 } 15542 15543 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 15544 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 15545 + userId + ":"); 15546 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15547 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 15548 scheduleWritePackageRestrictionsLocked(userId); 15549 } 15550 } 15551 15552 @Override 15553 public void replacePreferredActivity(IntentFilter filter, int match, 15554 ComponentName[] set, ComponentName activity, int userId) { 15555 if (filter.countActions() != 1) { 15556 throw new IllegalArgumentException( 15557 "replacePreferredActivity expects filter to have only 1 action."); 15558 } 15559 if (filter.countDataAuthorities() != 0 15560 || filter.countDataPaths() != 0 15561 || filter.countDataSchemes() > 1 15562 || filter.countDataTypes() != 0) { 15563 throw new IllegalArgumentException( 15564 "replacePreferredActivity expects filter to have no data authorities, " + 15565 "paths, or types; and at most one scheme."); 15566 } 15567 15568 final int callingUid = Binder.getCallingUid(); 15569 enforceCrossUserPermission(callingUid, userId, 15570 true /* requireFullPermission */, false /* checkShell */, 15571 "replace preferred activity"); 15572 synchronized (mPackages) { 15573 if (mContext.checkCallingOrSelfPermission( 15574 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15575 != PackageManager.PERMISSION_GRANTED) { 15576 if (getUidTargetSdkVersionLockedLPr(callingUid) 15577 < Build.VERSION_CODES.FROYO) { 15578 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 15579 + Binder.getCallingUid()); 15580 return; 15581 } 15582 mContext.enforceCallingOrSelfPermission( 15583 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15584 } 15585 15586 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 15587 if (pir != null) { 15588 // Get all of the existing entries that exactly match this filter. 15589 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 15590 if (existing != null && existing.size() == 1) { 15591 PreferredActivity cur = existing.get(0); 15592 if (DEBUG_PREFERRED) { 15593 Slog.i(TAG, "Checking replace of preferred:"); 15594 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15595 if (!cur.mPref.mAlways) { 15596 Slog.i(TAG, " -- CUR; not mAlways!"); 15597 } else { 15598 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 15599 Slog.i(TAG, " -- CUR: mSet=" 15600 + Arrays.toString(cur.mPref.mSetComponents)); 15601 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 15602 Slog.i(TAG, " -- NEW: mMatch=" 15603 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 15604 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 15605 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 15606 } 15607 } 15608 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 15609 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 15610 && cur.mPref.sameSet(set)) { 15611 // Setting the preferred activity to what it happens to be already 15612 if (DEBUG_PREFERRED) { 15613 Slog.i(TAG, "Replacing with same preferred activity " 15614 + cur.mPref.mShortComponent + " for user " 15615 + userId + ":"); 15616 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15617 } 15618 return; 15619 } 15620 } 15621 15622 if (existing != null) { 15623 if (DEBUG_PREFERRED) { 15624 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 15625 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15626 } 15627 for (int i = 0; i < existing.size(); i++) { 15628 PreferredActivity pa = existing.get(i); 15629 if (DEBUG_PREFERRED) { 15630 Slog.i(TAG, "Removing existing preferred activity " 15631 + pa.mPref.mComponent + ":"); 15632 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 15633 } 15634 pir.removeFilter(pa); 15635 } 15636 } 15637 } 15638 addPreferredActivityInternal(filter, match, set, activity, true, userId, 15639 "Replacing preferred"); 15640 } 15641 } 15642 15643 @Override 15644 public void clearPackagePreferredActivities(String packageName) { 15645 final int uid = Binder.getCallingUid(); 15646 // writer 15647 synchronized (mPackages) { 15648 PackageParser.Package pkg = mPackages.get(packageName); 15649 if (pkg == null || pkg.applicationInfo.uid != uid) { 15650 if (mContext.checkCallingOrSelfPermission( 15651 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15652 != PackageManager.PERMISSION_GRANTED) { 15653 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 15654 < Build.VERSION_CODES.FROYO) { 15655 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 15656 + Binder.getCallingUid()); 15657 return; 15658 } 15659 mContext.enforceCallingOrSelfPermission( 15660 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15661 } 15662 } 15663 15664 int user = UserHandle.getCallingUserId(); 15665 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 15666 scheduleWritePackageRestrictionsLocked(user); 15667 } 15668 } 15669 } 15670 15671 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15672 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 15673 ArrayList<PreferredActivity> removed = null; 15674 boolean changed = false; 15675 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15676 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 15677 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15678 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 15679 continue; 15680 } 15681 Iterator<PreferredActivity> it = pir.filterIterator(); 15682 while (it.hasNext()) { 15683 PreferredActivity pa = it.next(); 15684 // Mark entry for removal only if it matches the package name 15685 // and the entry is of type "always". 15686 if (packageName == null || 15687 (pa.mPref.mComponent.getPackageName().equals(packageName) 15688 && pa.mPref.mAlways)) { 15689 if (removed == null) { 15690 removed = new ArrayList<PreferredActivity>(); 15691 } 15692 removed.add(pa); 15693 } 15694 } 15695 if (removed != null) { 15696 for (int j=0; j<removed.size(); j++) { 15697 PreferredActivity pa = removed.get(j); 15698 pir.removeFilter(pa); 15699 } 15700 changed = true; 15701 } 15702 } 15703 return changed; 15704 } 15705 15706 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15707 private void clearIntentFilterVerificationsLPw(int userId) { 15708 final int packageCount = mPackages.size(); 15709 for (int i = 0; i < packageCount; i++) { 15710 PackageParser.Package pkg = mPackages.valueAt(i); 15711 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 15712 } 15713 } 15714 15715 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15716 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 15717 if (userId == UserHandle.USER_ALL) { 15718 if (mSettings.removeIntentFilterVerificationLPw(packageName, 15719 sUserManager.getUserIds())) { 15720 for (int oneUserId : sUserManager.getUserIds()) { 15721 scheduleWritePackageRestrictionsLocked(oneUserId); 15722 } 15723 } 15724 } else { 15725 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 15726 scheduleWritePackageRestrictionsLocked(userId); 15727 } 15728 } 15729 } 15730 15731 void clearDefaultBrowserIfNeeded(String packageName) { 15732 for (int oneUserId : sUserManager.getUserIds()) { 15733 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 15734 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 15735 if (packageName.equals(defaultBrowserPackageName)) { 15736 setDefaultBrowserPackageName(null, oneUserId); 15737 } 15738 } 15739 } 15740 15741 @Override 15742 public void resetApplicationPreferences(int userId) { 15743 mContext.enforceCallingOrSelfPermission( 15744 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15745 // writer 15746 synchronized (mPackages) { 15747 final long identity = Binder.clearCallingIdentity(); 15748 try { 15749 clearPackagePreferredActivitiesLPw(null, userId); 15750 mSettings.applyDefaultPreferredAppsLPw(this, userId); 15751 // TODO: We have to reset the default SMS and Phone. This requires 15752 // significant refactoring to keep all default apps in the package 15753 // manager (cleaner but more work) or have the services provide 15754 // callbacks to the package manager to request a default app reset. 15755 applyFactoryDefaultBrowserLPw(userId); 15756 clearIntentFilterVerificationsLPw(userId); 15757 primeDomainVerificationsLPw(userId); 15758 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 15759 scheduleWritePackageRestrictionsLocked(userId); 15760 } finally { 15761 Binder.restoreCallingIdentity(identity); 15762 } 15763 } 15764 } 15765 15766 @Override 15767 public int getPreferredActivities(List<IntentFilter> outFilters, 15768 List<ComponentName> outActivities, String packageName) { 15769 15770 int num = 0; 15771 final int userId = UserHandle.getCallingUserId(); 15772 // reader 15773 synchronized (mPackages) { 15774 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 15775 if (pir != null) { 15776 final Iterator<PreferredActivity> it = pir.filterIterator(); 15777 while (it.hasNext()) { 15778 final PreferredActivity pa = it.next(); 15779 if (packageName == null 15780 || (pa.mPref.mComponent.getPackageName().equals(packageName) 15781 && pa.mPref.mAlways)) { 15782 if (outFilters != null) { 15783 outFilters.add(new IntentFilter(pa)); 15784 } 15785 if (outActivities != null) { 15786 outActivities.add(pa.mPref.mComponent); 15787 } 15788 } 15789 } 15790 } 15791 } 15792 15793 return num; 15794 } 15795 15796 @Override 15797 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 15798 int userId) { 15799 int callingUid = Binder.getCallingUid(); 15800 if (callingUid != Process.SYSTEM_UID) { 15801 throw new SecurityException( 15802 "addPersistentPreferredActivity can only be run by the system"); 15803 } 15804 if (filter.countActions() == 0) { 15805 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 15806 return; 15807 } 15808 synchronized (mPackages) { 15809 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 15810 ":"); 15811 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15812 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 15813 new PersistentPreferredActivity(filter, activity)); 15814 scheduleWritePackageRestrictionsLocked(userId); 15815 } 15816 } 15817 15818 @Override 15819 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 15820 int callingUid = Binder.getCallingUid(); 15821 if (callingUid != Process.SYSTEM_UID) { 15822 throw new SecurityException( 15823 "clearPackagePersistentPreferredActivities can only be run by the system"); 15824 } 15825 ArrayList<PersistentPreferredActivity> removed = null; 15826 boolean changed = false; 15827 synchronized (mPackages) { 15828 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 15829 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 15830 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 15831 .valueAt(i); 15832 if (userId != thisUserId) { 15833 continue; 15834 } 15835 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 15836 while (it.hasNext()) { 15837 PersistentPreferredActivity ppa = it.next(); 15838 // Mark entry for removal only if it matches the package name. 15839 if (ppa.mComponent.getPackageName().equals(packageName)) { 15840 if (removed == null) { 15841 removed = new ArrayList<PersistentPreferredActivity>(); 15842 } 15843 removed.add(ppa); 15844 } 15845 } 15846 if (removed != null) { 15847 for (int j=0; j<removed.size(); j++) { 15848 PersistentPreferredActivity ppa = removed.get(j); 15849 ppir.removeFilter(ppa); 15850 } 15851 changed = true; 15852 } 15853 } 15854 15855 if (changed) { 15856 scheduleWritePackageRestrictionsLocked(userId); 15857 } 15858 } 15859 } 15860 15861 /** 15862 * Common machinery for picking apart a restored XML blob and passing 15863 * it to a caller-supplied functor to be applied to the running system. 15864 */ 15865 private void restoreFromXml(XmlPullParser parser, int userId, 15866 String expectedStartTag, BlobXmlRestorer functor) 15867 throws IOException, XmlPullParserException { 15868 int type; 15869 while ((type = parser.next()) != XmlPullParser.START_TAG 15870 && type != XmlPullParser.END_DOCUMENT) { 15871 } 15872 if (type != XmlPullParser.START_TAG) { 15873 // oops didn't find a start tag?! 15874 if (DEBUG_BACKUP) { 15875 Slog.e(TAG, "Didn't find start tag during restore"); 15876 } 15877 return; 15878 } 15879Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 15880 // this is supposed to be TAG_PREFERRED_BACKUP 15881 if (!expectedStartTag.equals(parser.getName())) { 15882 if (DEBUG_BACKUP) { 15883 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 15884 } 15885 return; 15886 } 15887 15888 // skip interfering stuff, then we're aligned with the backing implementation 15889 while ((type = parser.next()) == XmlPullParser.TEXT) { } 15890Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 15891 functor.apply(parser, userId); 15892 } 15893 15894 private interface BlobXmlRestorer { 15895 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 15896 } 15897 15898 /** 15899 * Non-Binder method, support for the backup/restore mechanism: write the 15900 * full set of preferred activities in its canonical XML format. Returns the 15901 * XML output as a byte array, or null if there is none. 15902 */ 15903 @Override 15904 public byte[] getPreferredActivityBackup(int userId) { 15905 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15906 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 15907 } 15908 15909 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 15910 try { 15911 final XmlSerializer serializer = new FastXmlSerializer(); 15912 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 15913 serializer.startDocument(null, true); 15914 serializer.startTag(null, TAG_PREFERRED_BACKUP); 15915 15916 synchronized (mPackages) { 15917 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 15918 } 15919 15920 serializer.endTag(null, TAG_PREFERRED_BACKUP); 15921 serializer.endDocument(); 15922 serializer.flush(); 15923 } catch (Exception e) { 15924 if (DEBUG_BACKUP) { 15925 Slog.e(TAG, "Unable to write preferred activities for backup", e); 15926 } 15927 return null; 15928 } 15929 15930 return dataStream.toByteArray(); 15931 } 15932 15933 @Override 15934 public void restorePreferredActivities(byte[] backup, int userId) { 15935 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15936 throw new SecurityException("Only the system may call restorePreferredActivities()"); 15937 } 15938 15939 try { 15940 final XmlPullParser parser = Xml.newPullParser(); 15941 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 15942 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 15943 new BlobXmlRestorer() { 15944 @Override 15945 public void apply(XmlPullParser parser, int userId) 15946 throws XmlPullParserException, IOException { 15947 synchronized (mPackages) { 15948 mSettings.readPreferredActivitiesLPw(parser, userId); 15949 } 15950 } 15951 } ); 15952 } catch (Exception e) { 15953 if (DEBUG_BACKUP) { 15954 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 15955 } 15956 } 15957 } 15958 15959 /** 15960 * Non-Binder method, support for the backup/restore mechanism: write the 15961 * default browser (etc) settings in its canonical XML format. Returns the default 15962 * browser XML representation as a byte array, or null if there is none. 15963 */ 15964 @Override 15965 public byte[] getDefaultAppsBackup(int userId) { 15966 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15967 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 15968 } 15969 15970 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 15971 try { 15972 final XmlSerializer serializer = new FastXmlSerializer(); 15973 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 15974 serializer.startDocument(null, true); 15975 serializer.startTag(null, TAG_DEFAULT_APPS); 15976 15977 synchronized (mPackages) { 15978 mSettings.writeDefaultAppsLPr(serializer, userId); 15979 } 15980 15981 serializer.endTag(null, TAG_DEFAULT_APPS); 15982 serializer.endDocument(); 15983 serializer.flush(); 15984 } catch (Exception e) { 15985 if (DEBUG_BACKUP) { 15986 Slog.e(TAG, "Unable to write default apps for backup", e); 15987 } 15988 return null; 15989 } 15990 15991 return dataStream.toByteArray(); 15992 } 15993 15994 @Override 15995 public void restoreDefaultApps(byte[] backup, int userId) { 15996 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15997 throw new SecurityException("Only the system may call restoreDefaultApps()"); 15998 } 15999 16000 try { 16001 final XmlPullParser parser = Xml.newPullParser(); 16002 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16003 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16004 new BlobXmlRestorer() { 16005 @Override 16006 public void apply(XmlPullParser parser, int userId) 16007 throws XmlPullParserException, IOException { 16008 synchronized (mPackages) { 16009 mSettings.readDefaultAppsLPw(parser, userId); 16010 } 16011 } 16012 } ); 16013 } catch (Exception e) { 16014 if (DEBUG_BACKUP) { 16015 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16016 } 16017 } 16018 } 16019 16020 @Override 16021 public byte[] getIntentFilterVerificationBackup(int userId) { 16022 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16023 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 16024 } 16025 16026 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16027 try { 16028 final XmlSerializer serializer = new FastXmlSerializer(); 16029 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16030 serializer.startDocument(null, true); 16031 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 16032 16033 synchronized (mPackages) { 16034 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 16035 } 16036 16037 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 16038 serializer.endDocument(); 16039 serializer.flush(); 16040 } catch (Exception e) { 16041 if (DEBUG_BACKUP) { 16042 Slog.e(TAG, "Unable to write default apps for backup", e); 16043 } 16044 return null; 16045 } 16046 16047 return dataStream.toByteArray(); 16048 } 16049 16050 @Override 16051 public void restoreIntentFilterVerification(byte[] backup, int userId) { 16052 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16053 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16054 } 16055 16056 try { 16057 final XmlPullParser parser = Xml.newPullParser(); 16058 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16059 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 16060 new BlobXmlRestorer() { 16061 @Override 16062 public void apply(XmlPullParser parser, int userId) 16063 throws XmlPullParserException, IOException { 16064 synchronized (mPackages) { 16065 mSettings.readAllDomainVerificationsLPr(parser, userId); 16066 mSettings.writeLPr(); 16067 } 16068 } 16069 } ); 16070 } catch (Exception e) { 16071 if (DEBUG_BACKUP) { 16072 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16073 } 16074 } 16075 } 16076 16077 @Override 16078 public byte[] getPermissionGrantBackup(int userId) { 16079 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16080 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 16081 } 16082 16083 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16084 try { 16085 final XmlSerializer serializer = new FastXmlSerializer(); 16086 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16087 serializer.startDocument(null, true); 16088 serializer.startTag(null, TAG_PERMISSION_BACKUP); 16089 16090 synchronized (mPackages) { 16091 serializeRuntimePermissionGrantsLPr(serializer, userId); 16092 } 16093 16094 serializer.endTag(null, TAG_PERMISSION_BACKUP); 16095 serializer.endDocument(); 16096 serializer.flush(); 16097 } catch (Exception e) { 16098 if (DEBUG_BACKUP) { 16099 Slog.e(TAG, "Unable to write default apps for backup", e); 16100 } 16101 return null; 16102 } 16103 16104 return dataStream.toByteArray(); 16105 } 16106 16107 @Override 16108 public void restorePermissionGrants(byte[] backup, int userId) { 16109 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16110 throw new SecurityException("Only the system may call restorePermissionGrants()"); 16111 } 16112 16113 try { 16114 final XmlPullParser parser = Xml.newPullParser(); 16115 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16116 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 16117 new BlobXmlRestorer() { 16118 @Override 16119 public void apply(XmlPullParser parser, int userId) 16120 throws XmlPullParserException, IOException { 16121 synchronized (mPackages) { 16122 processRestoredPermissionGrantsLPr(parser, userId); 16123 } 16124 } 16125 } ); 16126 } catch (Exception e) { 16127 if (DEBUG_BACKUP) { 16128 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16129 } 16130 } 16131 } 16132 16133 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 16134 throws IOException { 16135 serializer.startTag(null, TAG_ALL_GRANTS); 16136 16137 final int N = mSettings.mPackages.size(); 16138 for (int i = 0; i < N; i++) { 16139 final PackageSetting ps = mSettings.mPackages.valueAt(i); 16140 boolean pkgGrantsKnown = false; 16141 16142 PermissionsState packagePerms = ps.getPermissionsState(); 16143 16144 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 16145 final int grantFlags = state.getFlags(); 16146 // only look at grants that are not system/policy fixed 16147 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 16148 final boolean isGranted = state.isGranted(); 16149 // And only back up the user-twiddled state bits 16150 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 16151 final String packageName = mSettings.mPackages.keyAt(i); 16152 if (!pkgGrantsKnown) { 16153 serializer.startTag(null, TAG_GRANT); 16154 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 16155 pkgGrantsKnown = true; 16156 } 16157 16158 final boolean userSet = 16159 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 16160 final boolean userFixed = 16161 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 16162 final boolean revoke = 16163 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 16164 16165 serializer.startTag(null, TAG_PERMISSION); 16166 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 16167 if (isGranted) { 16168 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 16169 } 16170 if (userSet) { 16171 serializer.attribute(null, ATTR_USER_SET, "true"); 16172 } 16173 if (userFixed) { 16174 serializer.attribute(null, ATTR_USER_FIXED, "true"); 16175 } 16176 if (revoke) { 16177 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 16178 } 16179 serializer.endTag(null, TAG_PERMISSION); 16180 } 16181 } 16182 } 16183 16184 if (pkgGrantsKnown) { 16185 serializer.endTag(null, TAG_GRANT); 16186 } 16187 } 16188 16189 serializer.endTag(null, TAG_ALL_GRANTS); 16190 } 16191 16192 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 16193 throws XmlPullParserException, IOException { 16194 String pkgName = null; 16195 int outerDepth = parser.getDepth(); 16196 int type; 16197 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 16198 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 16199 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 16200 continue; 16201 } 16202 16203 final String tagName = parser.getName(); 16204 if (tagName.equals(TAG_GRANT)) { 16205 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 16206 if (DEBUG_BACKUP) { 16207 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 16208 } 16209 } else if (tagName.equals(TAG_PERMISSION)) { 16210 16211 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 16212 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 16213 16214 int newFlagSet = 0; 16215 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 16216 newFlagSet |= FLAG_PERMISSION_USER_SET; 16217 } 16218 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 16219 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 16220 } 16221 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 16222 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 16223 } 16224 if (DEBUG_BACKUP) { 16225 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 16226 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 16227 } 16228 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16229 if (ps != null) { 16230 // Already installed so we apply the grant immediately 16231 if (DEBUG_BACKUP) { 16232 Slog.v(TAG, " + already installed; applying"); 16233 } 16234 PermissionsState perms = ps.getPermissionsState(); 16235 BasePermission bp = mSettings.mPermissions.get(permName); 16236 if (bp != null) { 16237 if (isGranted) { 16238 perms.grantRuntimePermission(bp, userId); 16239 } 16240 if (newFlagSet != 0) { 16241 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 16242 } 16243 } 16244 } else { 16245 // Need to wait for post-restore install to apply the grant 16246 if (DEBUG_BACKUP) { 16247 Slog.v(TAG, " - not yet installed; saving for later"); 16248 } 16249 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 16250 isGranted, newFlagSet, userId); 16251 } 16252 } else { 16253 PackageManagerService.reportSettingsProblem(Log.WARN, 16254 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 16255 XmlUtils.skipCurrentTag(parser); 16256 } 16257 } 16258 16259 scheduleWriteSettingsLocked(); 16260 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16261 } 16262 16263 @Override 16264 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 16265 int sourceUserId, int targetUserId, int flags) { 16266 mContext.enforceCallingOrSelfPermission( 16267 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16268 int callingUid = Binder.getCallingUid(); 16269 enforceOwnerRights(ownerPackage, callingUid); 16270 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16271 if (intentFilter.countActions() == 0) { 16272 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 16273 return; 16274 } 16275 synchronized (mPackages) { 16276 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 16277 ownerPackage, targetUserId, flags); 16278 CrossProfileIntentResolver resolver = 16279 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16280 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 16281 // We have all those whose filter is equal. Now checking if the rest is equal as well. 16282 if (existing != null) { 16283 int size = existing.size(); 16284 for (int i = 0; i < size; i++) { 16285 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 16286 return; 16287 } 16288 } 16289 } 16290 resolver.addFilter(newFilter); 16291 scheduleWritePackageRestrictionsLocked(sourceUserId); 16292 } 16293 } 16294 16295 @Override 16296 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 16297 mContext.enforceCallingOrSelfPermission( 16298 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16299 int callingUid = Binder.getCallingUid(); 16300 enforceOwnerRights(ownerPackage, callingUid); 16301 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16302 synchronized (mPackages) { 16303 CrossProfileIntentResolver resolver = 16304 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16305 ArraySet<CrossProfileIntentFilter> set = 16306 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 16307 for (CrossProfileIntentFilter filter : set) { 16308 if (filter.getOwnerPackage().equals(ownerPackage)) { 16309 resolver.removeFilter(filter); 16310 } 16311 } 16312 scheduleWritePackageRestrictionsLocked(sourceUserId); 16313 } 16314 } 16315 16316 // Enforcing that callingUid is owning pkg on userId 16317 private void enforceOwnerRights(String pkg, int callingUid) { 16318 // The system owns everything. 16319 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 16320 return; 16321 } 16322 int callingUserId = UserHandle.getUserId(callingUid); 16323 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 16324 if (pi == null) { 16325 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 16326 + callingUserId); 16327 } 16328 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 16329 throw new SecurityException("Calling uid " + callingUid 16330 + " does not own package " + pkg); 16331 } 16332 } 16333 16334 @Override 16335 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 16336 Intent intent = new Intent(Intent.ACTION_MAIN); 16337 intent.addCategory(Intent.CATEGORY_HOME); 16338 16339 final int callingUserId = UserHandle.getCallingUserId(); 16340 List<ResolveInfo> list = queryIntentActivities(intent, null, 16341 PackageManager.GET_META_DATA, callingUserId); 16342 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 16343 true, false, false, callingUserId); 16344 16345 allHomeCandidates.clear(); 16346 if (list != null) { 16347 for (ResolveInfo ri : list) { 16348 allHomeCandidates.add(ri); 16349 } 16350 } 16351 return (preferred == null || preferred.activityInfo == null) 16352 ? null 16353 : new ComponentName(preferred.activityInfo.packageName, 16354 preferred.activityInfo.name); 16355 } 16356 16357 @Override 16358 public void setApplicationEnabledSetting(String appPackageName, 16359 int newState, int flags, int userId, String callingPackage) { 16360 if (!sUserManager.exists(userId)) return; 16361 if (callingPackage == null) { 16362 callingPackage = Integer.toString(Binder.getCallingUid()); 16363 } 16364 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 16365 } 16366 16367 @Override 16368 public void setComponentEnabledSetting(ComponentName componentName, 16369 int newState, int flags, int userId) { 16370 if (!sUserManager.exists(userId)) return; 16371 setEnabledSetting(componentName.getPackageName(), 16372 componentName.getClassName(), newState, flags, userId, null); 16373 } 16374 16375 private void setEnabledSetting(final String packageName, String className, int newState, 16376 final int flags, int userId, String callingPackage) { 16377 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 16378 || newState == COMPONENT_ENABLED_STATE_ENABLED 16379 || newState == COMPONENT_ENABLED_STATE_DISABLED 16380 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 16381 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 16382 throw new IllegalArgumentException("Invalid new component state: " 16383 + newState); 16384 } 16385 PackageSetting pkgSetting; 16386 final int uid = Binder.getCallingUid(); 16387 final int permission = mContext.checkCallingOrSelfPermission( 16388 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 16389 enforceCrossUserPermission(uid, userId, 16390 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 16391 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 16392 boolean sendNow = false; 16393 boolean isApp = (className == null); 16394 String componentName = isApp ? packageName : className; 16395 int packageUid = -1; 16396 ArrayList<String> components; 16397 16398 // writer 16399 synchronized (mPackages) { 16400 pkgSetting = mSettings.mPackages.get(packageName); 16401 if (pkgSetting == null) { 16402 if (className == null) { 16403 throw new IllegalArgumentException("Unknown package: " + packageName); 16404 } 16405 throw new IllegalArgumentException( 16406 "Unknown component: " + packageName + "/" + className); 16407 } 16408 // Allow root and verify that userId is not being specified by a different user 16409 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 16410 throw new SecurityException( 16411 "Permission Denial: attempt to change component state from pid=" 16412 + Binder.getCallingPid() 16413 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 16414 } 16415 if (className == null) { 16416 // We're dealing with an application/package level state change 16417 if (pkgSetting.getEnabled(userId) == newState) { 16418 // Nothing to do 16419 return; 16420 } 16421 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 16422 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 16423 // Don't care about who enables an app. 16424 callingPackage = null; 16425 } 16426 pkgSetting.setEnabled(newState, userId, callingPackage); 16427 // pkgSetting.pkg.mSetEnabled = newState; 16428 } else { 16429 // We're dealing with a component level state change 16430 // First, verify that this is a valid class name. 16431 PackageParser.Package pkg = pkgSetting.pkg; 16432 if (pkg == null || !pkg.hasComponentClassName(className)) { 16433 if (pkg != null && 16434 pkg.applicationInfo.targetSdkVersion >= 16435 Build.VERSION_CODES.JELLY_BEAN) { 16436 throw new IllegalArgumentException("Component class " + className 16437 + " does not exist in " + packageName); 16438 } else { 16439 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 16440 + className + " does not exist in " + packageName); 16441 } 16442 } 16443 switch (newState) { 16444 case COMPONENT_ENABLED_STATE_ENABLED: 16445 if (!pkgSetting.enableComponentLPw(className, userId)) { 16446 return; 16447 } 16448 break; 16449 case COMPONENT_ENABLED_STATE_DISABLED: 16450 if (!pkgSetting.disableComponentLPw(className, userId)) { 16451 return; 16452 } 16453 break; 16454 case COMPONENT_ENABLED_STATE_DEFAULT: 16455 if (!pkgSetting.restoreComponentLPw(className, userId)) { 16456 return; 16457 } 16458 break; 16459 default: 16460 Slog.e(TAG, "Invalid new component state: " + newState); 16461 return; 16462 } 16463 } 16464 scheduleWritePackageRestrictionsLocked(userId); 16465 components = mPendingBroadcasts.get(userId, packageName); 16466 final boolean newPackage = components == null; 16467 if (newPackage) { 16468 components = new ArrayList<String>(); 16469 } 16470 if (!components.contains(componentName)) { 16471 components.add(componentName); 16472 } 16473 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 16474 sendNow = true; 16475 // Purge entry from pending broadcast list if another one exists already 16476 // since we are sending one right away. 16477 mPendingBroadcasts.remove(userId, packageName); 16478 } else { 16479 if (newPackage) { 16480 mPendingBroadcasts.put(userId, packageName, components); 16481 } 16482 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 16483 // Schedule a message 16484 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 16485 } 16486 } 16487 } 16488 16489 long callingId = Binder.clearCallingIdentity(); 16490 try { 16491 if (sendNow) { 16492 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 16493 sendPackageChangedBroadcast(packageName, 16494 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 16495 } 16496 } finally { 16497 Binder.restoreCallingIdentity(callingId); 16498 } 16499 } 16500 16501 private void sendPackageChangedBroadcast(String packageName, 16502 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 16503 if (DEBUG_INSTALL) 16504 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 16505 + componentNames); 16506 Bundle extras = new Bundle(4); 16507 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 16508 String nameList[] = new String[componentNames.size()]; 16509 componentNames.toArray(nameList); 16510 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 16511 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 16512 extras.putInt(Intent.EXTRA_UID, packageUid); 16513 // If this is not reporting a change of the overall package, then only send it 16514 // to registered receivers. We don't want to launch a swath of apps for every 16515 // little component state change. 16516 final int flags = !componentNames.contains(packageName) 16517 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 16518 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 16519 new int[] {UserHandle.getUserId(packageUid)}); 16520 } 16521 16522 @Override 16523 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 16524 if (!sUserManager.exists(userId)) return; 16525 final int uid = Binder.getCallingUid(); 16526 final int permission = mContext.checkCallingOrSelfPermission( 16527 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 16528 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 16529 enforceCrossUserPermission(uid, userId, 16530 true /* requireFullPermission */, true /* checkShell */, "stop package"); 16531 // writer 16532 synchronized (mPackages) { 16533 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 16534 allowedByPermission, uid, userId)) { 16535 scheduleWritePackageRestrictionsLocked(userId); 16536 } 16537 } 16538 } 16539 16540 @Override 16541 public String getInstallerPackageName(String packageName) { 16542 // reader 16543 synchronized (mPackages) { 16544 return mSettings.getInstallerPackageNameLPr(packageName); 16545 } 16546 } 16547 16548 @Override 16549 public int getApplicationEnabledSetting(String packageName, int userId) { 16550 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 16551 int uid = Binder.getCallingUid(); 16552 enforceCrossUserPermission(uid, userId, 16553 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 16554 // reader 16555 synchronized (mPackages) { 16556 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 16557 } 16558 } 16559 16560 @Override 16561 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 16562 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 16563 int uid = Binder.getCallingUid(); 16564 enforceCrossUserPermission(uid, userId, 16565 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 16566 // reader 16567 synchronized (mPackages) { 16568 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 16569 } 16570 } 16571 16572 @Override 16573 public void enterSafeMode() { 16574 enforceSystemOrRoot("Only the system can request entering safe mode"); 16575 16576 if (!mSystemReady) { 16577 mSafeMode = true; 16578 } 16579 } 16580 16581 @Override 16582 public void systemReady() { 16583 mSystemReady = true; 16584 16585 // Read the compatibilty setting when the system is ready. 16586 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 16587 mContext.getContentResolver(), 16588 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 16589 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 16590 if (DEBUG_SETTINGS) { 16591 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 16592 } 16593 16594 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 16595 16596 synchronized (mPackages) { 16597 // Verify that all of the preferred activity components actually 16598 // exist. It is possible for applications to be updated and at 16599 // that point remove a previously declared activity component that 16600 // had been set as a preferred activity. We try to clean this up 16601 // the next time we encounter that preferred activity, but it is 16602 // possible for the user flow to never be able to return to that 16603 // situation so here we do a sanity check to make sure we haven't 16604 // left any junk around. 16605 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 16606 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16607 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16608 removed.clear(); 16609 for (PreferredActivity pa : pir.filterSet()) { 16610 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 16611 removed.add(pa); 16612 } 16613 } 16614 if (removed.size() > 0) { 16615 for (int r=0; r<removed.size(); r++) { 16616 PreferredActivity pa = removed.get(r); 16617 Slog.w(TAG, "Removing dangling preferred activity: " 16618 + pa.mPref.mComponent); 16619 pir.removeFilter(pa); 16620 } 16621 mSettings.writePackageRestrictionsLPr( 16622 mSettings.mPreferredActivities.keyAt(i)); 16623 } 16624 } 16625 16626 for (int userId : UserManagerService.getInstance().getUserIds()) { 16627 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 16628 grantPermissionsUserIds = ArrayUtils.appendInt( 16629 grantPermissionsUserIds, userId); 16630 } 16631 } 16632 } 16633 sUserManager.systemReady(); 16634 16635 // If we upgraded grant all default permissions before kicking off. 16636 for (int userId : grantPermissionsUserIds) { 16637 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 16638 } 16639 16640 // Kick off any messages waiting for system ready 16641 if (mPostSystemReadyMessages != null) { 16642 for (Message msg : mPostSystemReadyMessages) { 16643 msg.sendToTarget(); 16644 } 16645 mPostSystemReadyMessages = null; 16646 } 16647 16648 // Watch for external volumes that come and go over time 16649 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16650 storage.registerListener(mStorageListener); 16651 16652 mInstallerService.systemReady(); 16653 mPackageDexOptimizer.systemReady(); 16654 16655 MountServiceInternal mountServiceInternal = LocalServices.getService( 16656 MountServiceInternal.class); 16657 mountServiceInternal.addExternalStoragePolicy( 16658 new MountServiceInternal.ExternalStorageMountPolicy() { 16659 @Override 16660 public int getMountMode(int uid, String packageName) { 16661 if (Process.isIsolated(uid)) { 16662 return Zygote.MOUNT_EXTERNAL_NONE; 16663 } 16664 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 16665 return Zygote.MOUNT_EXTERNAL_DEFAULT; 16666 } 16667 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 16668 return Zygote.MOUNT_EXTERNAL_DEFAULT; 16669 } 16670 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 16671 return Zygote.MOUNT_EXTERNAL_READ; 16672 } 16673 return Zygote.MOUNT_EXTERNAL_WRITE; 16674 } 16675 16676 @Override 16677 public boolean hasExternalStorage(int uid, String packageName) { 16678 return true; 16679 } 16680 }); 16681 } 16682 16683 @Override 16684 public boolean isSafeMode() { 16685 return mSafeMode; 16686 } 16687 16688 @Override 16689 public boolean hasSystemUidErrors() { 16690 return mHasSystemUidErrors; 16691 } 16692 16693 static String arrayToString(int[] array) { 16694 StringBuffer buf = new StringBuffer(128); 16695 buf.append('['); 16696 if (array != null) { 16697 for (int i=0; i<array.length; i++) { 16698 if (i > 0) buf.append(", "); 16699 buf.append(array[i]); 16700 } 16701 } 16702 buf.append(']'); 16703 return buf.toString(); 16704 } 16705 16706 static class DumpState { 16707 public static final int DUMP_LIBS = 1 << 0; 16708 public static final int DUMP_FEATURES = 1 << 1; 16709 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 16710 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 16711 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 16712 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 16713 public static final int DUMP_PERMISSIONS = 1 << 6; 16714 public static final int DUMP_PACKAGES = 1 << 7; 16715 public static final int DUMP_SHARED_USERS = 1 << 8; 16716 public static final int DUMP_MESSAGES = 1 << 9; 16717 public static final int DUMP_PROVIDERS = 1 << 10; 16718 public static final int DUMP_VERIFIERS = 1 << 11; 16719 public static final int DUMP_PREFERRED = 1 << 12; 16720 public static final int DUMP_PREFERRED_XML = 1 << 13; 16721 public static final int DUMP_KEYSETS = 1 << 14; 16722 public static final int DUMP_VERSION = 1 << 15; 16723 public static final int DUMP_INSTALLS = 1 << 16; 16724 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 16725 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 16726 16727 public static final int OPTION_SHOW_FILTERS = 1 << 0; 16728 16729 private int mTypes; 16730 16731 private int mOptions; 16732 16733 private boolean mTitlePrinted; 16734 16735 private SharedUserSetting mSharedUser; 16736 16737 public boolean isDumping(int type) { 16738 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 16739 return true; 16740 } 16741 16742 return (mTypes & type) != 0; 16743 } 16744 16745 public void setDump(int type) { 16746 mTypes |= type; 16747 } 16748 16749 public boolean isOptionEnabled(int option) { 16750 return (mOptions & option) != 0; 16751 } 16752 16753 public void setOptionEnabled(int option) { 16754 mOptions |= option; 16755 } 16756 16757 public boolean onTitlePrinted() { 16758 final boolean printed = mTitlePrinted; 16759 mTitlePrinted = true; 16760 return printed; 16761 } 16762 16763 public boolean getTitlePrinted() { 16764 return mTitlePrinted; 16765 } 16766 16767 public void setTitlePrinted(boolean enabled) { 16768 mTitlePrinted = enabled; 16769 } 16770 16771 public SharedUserSetting getSharedUser() { 16772 return mSharedUser; 16773 } 16774 16775 public void setSharedUser(SharedUserSetting user) { 16776 mSharedUser = user; 16777 } 16778 } 16779 16780 @Override 16781 public void onShellCommand(FileDescriptor in, FileDescriptor out, 16782 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 16783 (new PackageManagerShellCommand(this)).exec( 16784 this, in, out, err, args, resultReceiver); 16785 } 16786 16787 @Override 16788 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 16789 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 16790 != PackageManager.PERMISSION_GRANTED) { 16791 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 16792 + Binder.getCallingPid() 16793 + ", uid=" + Binder.getCallingUid() 16794 + " without permission " 16795 + android.Manifest.permission.DUMP); 16796 return; 16797 } 16798 16799 DumpState dumpState = new DumpState(); 16800 boolean fullPreferred = false; 16801 boolean checkin = false; 16802 16803 String packageName = null; 16804 ArraySet<String> permissionNames = null; 16805 16806 int opti = 0; 16807 while (opti < args.length) { 16808 String opt = args[opti]; 16809 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 16810 break; 16811 } 16812 opti++; 16813 16814 if ("-a".equals(opt)) { 16815 // Right now we only know how to print all. 16816 } else if ("-h".equals(opt)) { 16817 pw.println("Package manager dump options:"); 16818 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 16819 pw.println(" --checkin: dump for a checkin"); 16820 pw.println(" -f: print details of intent filters"); 16821 pw.println(" -h: print this help"); 16822 pw.println(" cmd may be one of:"); 16823 pw.println(" l[ibraries]: list known shared libraries"); 16824 pw.println(" f[eatures]: list device features"); 16825 pw.println(" k[eysets]: print known keysets"); 16826 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 16827 pw.println(" perm[issions]: dump permissions"); 16828 pw.println(" permission [name ...]: dump declaration and use of given permission"); 16829 pw.println(" pref[erred]: print preferred package settings"); 16830 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 16831 pw.println(" prov[iders]: dump content providers"); 16832 pw.println(" p[ackages]: dump installed packages"); 16833 pw.println(" s[hared-users]: dump shared user IDs"); 16834 pw.println(" m[essages]: print collected runtime messages"); 16835 pw.println(" v[erifiers]: print package verifier info"); 16836 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 16837 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 16838 pw.println(" version: print database version info"); 16839 pw.println(" write: write current settings now"); 16840 pw.println(" installs: details about install sessions"); 16841 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 16842 pw.println(" <package.name>: info about given package"); 16843 return; 16844 } else if ("--checkin".equals(opt)) { 16845 checkin = true; 16846 } else if ("-f".equals(opt)) { 16847 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 16848 } else { 16849 pw.println("Unknown argument: " + opt + "; use -h for help"); 16850 } 16851 } 16852 16853 // Is the caller requesting to dump a particular piece of data? 16854 if (opti < args.length) { 16855 String cmd = args[opti]; 16856 opti++; 16857 // Is this a package name? 16858 if ("android".equals(cmd) || cmd.contains(".")) { 16859 packageName = cmd; 16860 // When dumping a single package, we always dump all of its 16861 // filter information since the amount of data will be reasonable. 16862 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 16863 } else if ("check-permission".equals(cmd)) { 16864 if (opti >= args.length) { 16865 pw.println("Error: check-permission missing permission argument"); 16866 return; 16867 } 16868 String perm = args[opti]; 16869 opti++; 16870 if (opti >= args.length) { 16871 pw.println("Error: check-permission missing package argument"); 16872 return; 16873 } 16874 String pkg = args[opti]; 16875 opti++; 16876 int user = UserHandle.getUserId(Binder.getCallingUid()); 16877 if (opti < args.length) { 16878 try { 16879 user = Integer.parseInt(args[opti]); 16880 } catch (NumberFormatException e) { 16881 pw.println("Error: check-permission user argument is not a number: " 16882 + args[opti]); 16883 return; 16884 } 16885 } 16886 pw.println(checkPermission(perm, pkg, user)); 16887 return; 16888 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 16889 dumpState.setDump(DumpState.DUMP_LIBS); 16890 } else if ("f".equals(cmd) || "features".equals(cmd)) { 16891 dumpState.setDump(DumpState.DUMP_FEATURES); 16892 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 16893 if (opti >= args.length) { 16894 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 16895 | DumpState.DUMP_SERVICE_RESOLVERS 16896 | DumpState.DUMP_RECEIVER_RESOLVERS 16897 | DumpState.DUMP_CONTENT_RESOLVERS); 16898 } else { 16899 while (opti < args.length) { 16900 String name = args[opti]; 16901 if ("a".equals(name) || "activity".equals(name)) { 16902 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 16903 } else if ("s".equals(name) || "service".equals(name)) { 16904 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 16905 } else if ("r".equals(name) || "receiver".equals(name)) { 16906 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 16907 } else if ("c".equals(name) || "content".equals(name)) { 16908 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 16909 } else { 16910 pw.println("Error: unknown resolver table type: " + name); 16911 return; 16912 } 16913 opti++; 16914 } 16915 } 16916 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 16917 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 16918 } else if ("permission".equals(cmd)) { 16919 if (opti >= args.length) { 16920 pw.println("Error: permission requires permission name"); 16921 return; 16922 } 16923 permissionNames = new ArraySet<>(); 16924 while (opti < args.length) { 16925 permissionNames.add(args[opti]); 16926 opti++; 16927 } 16928 dumpState.setDump(DumpState.DUMP_PERMISSIONS 16929 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 16930 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 16931 dumpState.setDump(DumpState.DUMP_PREFERRED); 16932 } else if ("preferred-xml".equals(cmd)) { 16933 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 16934 if (opti < args.length && "--full".equals(args[opti])) { 16935 fullPreferred = true; 16936 opti++; 16937 } 16938 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 16939 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 16940 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 16941 dumpState.setDump(DumpState.DUMP_PACKAGES); 16942 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 16943 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 16944 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 16945 dumpState.setDump(DumpState.DUMP_PROVIDERS); 16946 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 16947 dumpState.setDump(DumpState.DUMP_MESSAGES); 16948 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 16949 dumpState.setDump(DumpState.DUMP_VERIFIERS); 16950 } else if ("i".equals(cmd) || "ifv".equals(cmd) 16951 || "intent-filter-verifiers".equals(cmd)) { 16952 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 16953 } else if ("version".equals(cmd)) { 16954 dumpState.setDump(DumpState.DUMP_VERSION); 16955 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 16956 dumpState.setDump(DumpState.DUMP_KEYSETS); 16957 } else if ("installs".equals(cmd)) { 16958 dumpState.setDump(DumpState.DUMP_INSTALLS); 16959 } else if ("write".equals(cmd)) { 16960 synchronized (mPackages) { 16961 mSettings.writeLPr(); 16962 pw.println("Settings written."); 16963 return; 16964 } 16965 } 16966 } 16967 16968 if (checkin) { 16969 pw.println("vers,1"); 16970 } 16971 16972 // reader 16973 synchronized (mPackages) { 16974 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 16975 if (!checkin) { 16976 if (dumpState.onTitlePrinted()) 16977 pw.println(); 16978 pw.println("Database versions:"); 16979 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 16980 } 16981 } 16982 16983 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 16984 if (!checkin) { 16985 if (dumpState.onTitlePrinted()) 16986 pw.println(); 16987 pw.println("Verifiers:"); 16988 pw.print(" Required: "); 16989 pw.print(mRequiredVerifierPackage); 16990 pw.print(" (uid="); 16991 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 16992 UserHandle.USER_SYSTEM)); 16993 pw.println(")"); 16994 } else if (mRequiredVerifierPackage != null) { 16995 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 16996 pw.print(","); 16997 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 16998 UserHandle.USER_SYSTEM)); 16999 } 17000 } 17001 17002 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 17003 packageName == null) { 17004 if (mIntentFilterVerifierComponent != null) { 17005 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 17006 if (!checkin) { 17007 if (dumpState.onTitlePrinted()) 17008 pw.println(); 17009 pw.println("Intent Filter Verifier:"); 17010 pw.print(" Using: "); 17011 pw.print(verifierPackageName); 17012 pw.print(" (uid="); 17013 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17014 UserHandle.USER_SYSTEM)); 17015 pw.println(")"); 17016 } else if (verifierPackageName != null) { 17017 pw.print("ifv,"); pw.print(verifierPackageName); 17018 pw.print(","); 17019 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17020 UserHandle.USER_SYSTEM)); 17021 } 17022 } else { 17023 pw.println(); 17024 pw.println("No Intent Filter Verifier available!"); 17025 } 17026 } 17027 17028 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 17029 boolean printedHeader = false; 17030 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 17031 while (it.hasNext()) { 17032 String name = it.next(); 17033 SharedLibraryEntry ent = mSharedLibraries.get(name); 17034 if (!checkin) { 17035 if (!printedHeader) { 17036 if (dumpState.onTitlePrinted()) 17037 pw.println(); 17038 pw.println("Libraries:"); 17039 printedHeader = true; 17040 } 17041 pw.print(" "); 17042 } else { 17043 pw.print("lib,"); 17044 } 17045 pw.print(name); 17046 if (!checkin) { 17047 pw.print(" -> "); 17048 } 17049 if (ent.path != null) { 17050 if (!checkin) { 17051 pw.print("(jar) "); 17052 pw.print(ent.path); 17053 } else { 17054 pw.print(",jar,"); 17055 pw.print(ent.path); 17056 } 17057 } else { 17058 if (!checkin) { 17059 pw.print("(apk) "); 17060 pw.print(ent.apk); 17061 } else { 17062 pw.print(",apk,"); 17063 pw.print(ent.apk); 17064 } 17065 } 17066 pw.println(); 17067 } 17068 } 17069 17070 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 17071 if (dumpState.onTitlePrinted()) 17072 pw.println(); 17073 if (!checkin) { 17074 pw.println("Features:"); 17075 } 17076 17077 for (FeatureInfo feat : mAvailableFeatures.values()) { 17078 if (checkin) { 17079 pw.print("feat,"); 17080 pw.print(feat.name); 17081 pw.print(","); 17082 pw.println(feat.version); 17083 } else { 17084 pw.print(" "); 17085 pw.print(feat.name); 17086 if (feat.version > 0) { 17087 pw.print(" version="); 17088 pw.print(feat.version); 17089 } 17090 pw.println(); 17091 } 17092 } 17093 } 17094 17095 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 17096 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 17097 : "Activity Resolver Table:", " ", packageName, 17098 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17099 dumpState.setTitlePrinted(true); 17100 } 17101 } 17102 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 17103 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 17104 : "Receiver Resolver Table:", " ", packageName, 17105 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17106 dumpState.setTitlePrinted(true); 17107 } 17108 } 17109 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 17110 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 17111 : "Service Resolver Table:", " ", packageName, 17112 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17113 dumpState.setTitlePrinted(true); 17114 } 17115 } 17116 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 17117 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 17118 : "Provider Resolver Table:", " ", packageName, 17119 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17120 dumpState.setTitlePrinted(true); 17121 } 17122 } 17123 17124 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 17125 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17126 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17127 int user = mSettings.mPreferredActivities.keyAt(i); 17128 if (pir.dump(pw, 17129 dumpState.getTitlePrinted() 17130 ? "\nPreferred Activities User " + user + ":" 17131 : "Preferred Activities User " + user + ":", " ", 17132 packageName, true, false)) { 17133 dumpState.setTitlePrinted(true); 17134 } 17135 } 17136 } 17137 17138 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 17139 pw.flush(); 17140 FileOutputStream fout = new FileOutputStream(fd); 17141 BufferedOutputStream str = new BufferedOutputStream(fout); 17142 XmlSerializer serializer = new FastXmlSerializer(); 17143 try { 17144 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 17145 serializer.startDocument(null, true); 17146 serializer.setFeature( 17147 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 17148 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 17149 serializer.endDocument(); 17150 serializer.flush(); 17151 } catch (IllegalArgumentException e) { 17152 pw.println("Failed writing: " + e); 17153 } catch (IllegalStateException e) { 17154 pw.println("Failed writing: " + e); 17155 } catch (IOException e) { 17156 pw.println("Failed writing: " + e); 17157 } 17158 } 17159 17160 if (!checkin 17161 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 17162 && packageName == null) { 17163 pw.println(); 17164 int count = mSettings.mPackages.size(); 17165 if (count == 0) { 17166 pw.println("No applications!"); 17167 pw.println(); 17168 } else { 17169 final String prefix = " "; 17170 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 17171 if (allPackageSettings.size() == 0) { 17172 pw.println("No domain preferred apps!"); 17173 pw.println(); 17174 } else { 17175 pw.println("App verification status:"); 17176 pw.println(); 17177 count = 0; 17178 for (PackageSetting ps : allPackageSettings) { 17179 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 17180 if (ivi == null || ivi.getPackageName() == null) continue; 17181 pw.println(prefix + "Package: " + ivi.getPackageName()); 17182 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 17183 pw.println(prefix + "Status: " + ivi.getStatusString()); 17184 pw.println(); 17185 count++; 17186 } 17187 if (count == 0) { 17188 pw.println(prefix + "No app verification established."); 17189 pw.println(); 17190 } 17191 for (int userId : sUserManager.getUserIds()) { 17192 pw.println("App linkages for user " + userId + ":"); 17193 pw.println(); 17194 count = 0; 17195 for (PackageSetting ps : allPackageSettings) { 17196 final long status = ps.getDomainVerificationStatusForUser(userId); 17197 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 17198 continue; 17199 } 17200 pw.println(prefix + "Package: " + ps.name); 17201 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 17202 String statusStr = IntentFilterVerificationInfo. 17203 getStatusStringFromValue(status); 17204 pw.println(prefix + "Status: " + statusStr); 17205 pw.println(); 17206 count++; 17207 } 17208 if (count == 0) { 17209 pw.println(prefix + "No configured app linkages."); 17210 pw.println(); 17211 } 17212 } 17213 } 17214 } 17215 } 17216 17217 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 17218 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 17219 if (packageName == null && permissionNames == null) { 17220 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 17221 if (iperm == 0) { 17222 if (dumpState.onTitlePrinted()) 17223 pw.println(); 17224 pw.println("AppOp Permissions:"); 17225 } 17226 pw.print(" AppOp Permission "); 17227 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 17228 pw.println(":"); 17229 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 17230 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 17231 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 17232 } 17233 } 17234 } 17235 } 17236 17237 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 17238 boolean printedSomething = false; 17239 for (PackageParser.Provider p : mProviders.mProviders.values()) { 17240 if (packageName != null && !packageName.equals(p.info.packageName)) { 17241 continue; 17242 } 17243 if (!printedSomething) { 17244 if (dumpState.onTitlePrinted()) 17245 pw.println(); 17246 pw.println("Registered ContentProviders:"); 17247 printedSomething = true; 17248 } 17249 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 17250 pw.print(" "); pw.println(p.toString()); 17251 } 17252 printedSomething = false; 17253 for (Map.Entry<String, PackageParser.Provider> entry : 17254 mProvidersByAuthority.entrySet()) { 17255 PackageParser.Provider p = entry.getValue(); 17256 if (packageName != null && !packageName.equals(p.info.packageName)) { 17257 continue; 17258 } 17259 if (!printedSomething) { 17260 if (dumpState.onTitlePrinted()) 17261 pw.println(); 17262 pw.println("ContentProvider Authorities:"); 17263 printedSomething = true; 17264 } 17265 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 17266 pw.print(" "); pw.println(p.toString()); 17267 if (p.info != null && p.info.applicationInfo != null) { 17268 final String appInfo = p.info.applicationInfo.toString(); 17269 pw.print(" applicationInfo="); pw.println(appInfo); 17270 } 17271 } 17272 } 17273 17274 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 17275 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 17276 } 17277 17278 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 17279 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 17280 } 17281 17282 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 17283 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 17284 } 17285 17286 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 17287 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 17288 } 17289 17290 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 17291 // XXX should handle packageName != null by dumping only install data that 17292 // the given package is involved with. 17293 if (dumpState.onTitlePrinted()) pw.println(); 17294 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 17295 } 17296 17297 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 17298 if (dumpState.onTitlePrinted()) pw.println(); 17299 mSettings.dumpReadMessagesLPr(pw, dumpState); 17300 17301 pw.println(); 17302 pw.println("Package warning messages:"); 17303 BufferedReader in = null; 17304 String line = null; 17305 try { 17306 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 17307 while ((line = in.readLine()) != null) { 17308 if (line.contains("ignored: updated version")) continue; 17309 pw.println(line); 17310 } 17311 } catch (IOException ignored) { 17312 } finally { 17313 IoUtils.closeQuietly(in); 17314 } 17315 } 17316 17317 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 17318 BufferedReader in = null; 17319 String line = null; 17320 try { 17321 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 17322 while ((line = in.readLine()) != null) { 17323 if (line.contains("ignored: updated version")) continue; 17324 pw.print("msg,"); 17325 pw.println(line); 17326 } 17327 } catch (IOException ignored) { 17328 } finally { 17329 IoUtils.closeQuietly(in); 17330 } 17331 } 17332 } 17333 } 17334 17335 private String dumpDomainString(String packageName) { 17336 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 17337 List<IntentFilter> filters = getAllIntentFilters(packageName); 17338 17339 ArraySet<String> result = new ArraySet<>(); 17340 if (iviList.size() > 0) { 17341 for (IntentFilterVerificationInfo ivi : iviList) { 17342 for (String host : ivi.getDomains()) { 17343 result.add(host); 17344 } 17345 } 17346 } 17347 if (filters != null && filters.size() > 0) { 17348 for (IntentFilter filter : filters) { 17349 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 17350 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 17351 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 17352 result.addAll(filter.getHostsList()); 17353 } 17354 } 17355 } 17356 17357 StringBuilder sb = new StringBuilder(result.size() * 16); 17358 for (String domain : result) { 17359 if (sb.length() > 0) sb.append(" "); 17360 sb.append(domain); 17361 } 17362 return sb.toString(); 17363 } 17364 17365 // ------- apps on sdcard specific code ------- 17366 static final boolean DEBUG_SD_INSTALL = false; 17367 17368 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 17369 17370 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 17371 17372 private boolean mMediaMounted = false; 17373 17374 static String getEncryptKey() { 17375 try { 17376 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 17377 SD_ENCRYPTION_KEYSTORE_NAME); 17378 if (sdEncKey == null) { 17379 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 17380 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 17381 if (sdEncKey == null) { 17382 Slog.e(TAG, "Failed to create encryption keys"); 17383 return null; 17384 } 17385 } 17386 return sdEncKey; 17387 } catch (NoSuchAlgorithmException nsae) { 17388 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 17389 return null; 17390 } catch (IOException ioe) { 17391 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 17392 return null; 17393 } 17394 } 17395 17396 /* 17397 * Update media status on PackageManager. 17398 */ 17399 @Override 17400 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 17401 int callingUid = Binder.getCallingUid(); 17402 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 17403 throw new SecurityException("Media status can only be updated by the system"); 17404 } 17405 // reader; this apparently protects mMediaMounted, but should probably 17406 // be a different lock in that case. 17407 synchronized (mPackages) { 17408 Log.i(TAG, "Updating external media status from " 17409 + (mMediaMounted ? "mounted" : "unmounted") + " to " 17410 + (mediaStatus ? "mounted" : "unmounted")); 17411 if (DEBUG_SD_INSTALL) 17412 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 17413 + ", mMediaMounted=" + mMediaMounted); 17414 if (mediaStatus == mMediaMounted) { 17415 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 17416 : 0, -1); 17417 mHandler.sendMessage(msg); 17418 return; 17419 } 17420 mMediaMounted = mediaStatus; 17421 } 17422 // Queue up an async operation since the package installation may take a 17423 // little while. 17424 mHandler.post(new Runnable() { 17425 public void run() { 17426 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 17427 } 17428 }); 17429 } 17430 17431 /** 17432 * Called by MountService when the initial ASECs to scan are available. 17433 * Should block until all the ASEC containers are finished being scanned. 17434 */ 17435 public void scanAvailableAsecs() { 17436 updateExternalMediaStatusInner(true, false, false); 17437 } 17438 17439 /* 17440 * Collect information of applications on external media, map them against 17441 * existing containers and update information based on current mount status. 17442 * Please note that we always have to report status if reportStatus has been 17443 * set to true especially when unloading packages. 17444 */ 17445 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 17446 boolean externalStorage) { 17447 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 17448 int[] uidArr = EmptyArray.INT; 17449 17450 final String[] list = PackageHelper.getSecureContainerList(); 17451 if (ArrayUtils.isEmpty(list)) { 17452 Log.i(TAG, "No secure containers found"); 17453 } else { 17454 // Process list of secure containers and categorize them 17455 // as active or stale based on their package internal state. 17456 17457 // reader 17458 synchronized (mPackages) { 17459 for (String cid : list) { 17460 // Leave stages untouched for now; installer service owns them 17461 if (PackageInstallerService.isStageName(cid)) continue; 17462 17463 if (DEBUG_SD_INSTALL) 17464 Log.i(TAG, "Processing container " + cid); 17465 String pkgName = getAsecPackageName(cid); 17466 if (pkgName == null) { 17467 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 17468 continue; 17469 } 17470 if (DEBUG_SD_INSTALL) 17471 Log.i(TAG, "Looking for pkg : " + pkgName); 17472 17473 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17474 if (ps == null) { 17475 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 17476 continue; 17477 } 17478 17479 /* 17480 * Skip packages that are not external if we're unmounting 17481 * external storage. 17482 */ 17483 if (externalStorage && !isMounted && !isExternal(ps)) { 17484 continue; 17485 } 17486 17487 final AsecInstallArgs args = new AsecInstallArgs(cid, 17488 getAppDexInstructionSets(ps), ps.isForwardLocked()); 17489 // The package status is changed only if the code path 17490 // matches between settings and the container id. 17491 if (ps.codePathString != null 17492 && ps.codePathString.startsWith(args.getCodePath())) { 17493 if (DEBUG_SD_INSTALL) { 17494 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 17495 + " at code path: " + ps.codePathString); 17496 } 17497 17498 // We do have a valid package installed on sdcard 17499 processCids.put(args, ps.codePathString); 17500 final int uid = ps.appId; 17501 if (uid != -1) { 17502 uidArr = ArrayUtils.appendInt(uidArr, uid); 17503 } 17504 } else { 17505 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 17506 + ps.codePathString); 17507 } 17508 } 17509 } 17510 17511 Arrays.sort(uidArr); 17512 } 17513 17514 // Process packages with valid entries. 17515 if (isMounted) { 17516 if (DEBUG_SD_INSTALL) 17517 Log.i(TAG, "Loading packages"); 17518 loadMediaPackages(processCids, uidArr, externalStorage); 17519 startCleaningPackages(); 17520 mInstallerService.onSecureContainersAvailable(); 17521 } else { 17522 if (DEBUG_SD_INSTALL) 17523 Log.i(TAG, "Unloading packages"); 17524 unloadMediaPackages(processCids, uidArr, reportStatus); 17525 } 17526 } 17527 17528 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17529 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 17530 final int size = infos.size(); 17531 final String[] packageNames = new String[size]; 17532 final int[] packageUids = new int[size]; 17533 for (int i = 0; i < size; i++) { 17534 final ApplicationInfo info = infos.get(i); 17535 packageNames[i] = info.packageName; 17536 packageUids[i] = info.uid; 17537 } 17538 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 17539 finishedReceiver); 17540 } 17541 17542 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17543 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 17544 sendResourcesChangedBroadcast(mediaStatus, replacing, 17545 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 17546 } 17547 17548 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17549 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 17550 int size = pkgList.length; 17551 if (size > 0) { 17552 // Send broadcasts here 17553 Bundle extras = new Bundle(); 17554 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 17555 if (uidArr != null) { 17556 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 17557 } 17558 if (replacing) { 17559 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 17560 } 17561 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 17562 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 17563 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 17564 } 17565 } 17566 17567 /* 17568 * Look at potentially valid container ids from processCids If package 17569 * information doesn't match the one on record or package scanning fails, 17570 * the cid is added to list of removeCids. We currently don't delete stale 17571 * containers. 17572 */ 17573 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 17574 boolean externalStorage) { 17575 ArrayList<String> pkgList = new ArrayList<String>(); 17576 Set<AsecInstallArgs> keys = processCids.keySet(); 17577 17578 for (AsecInstallArgs args : keys) { 17579 String codePath = processCids.get(args); 17580 if (DEBUG_SD_INSTALL) 17581 Log.i(TAG, "Loading container : " + args.cid); 17582 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 17583 try { 17584 // Make sure there are no container errors first. 17585 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 17586 Slog.e(TAG, "Failed to mount cid : " + args.cid 17587 + " when installing from sdcard"); 17588 continue; 17589 } 17590 // Check code path here. 17591 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 17592 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 17593 + " does not match one in settings " + codePath); 17594 continue; 17595 } 17596 // Parse package 17597 int parseFlags = mDefParseFlags; 17598 if (args.isExternalAsec()) { 17599 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 17600 } 17601 if (args.isFwdLocked()) { 17602 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 17603 } 17604 17605 synchronized (mInstallLock) { 17606 PackageParser.Package pkg = null; 17607 try { 17608 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 17609 } catch (PackageManagerException e) { 17610 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 17611 } 17612 // Scan the package 17613 if (pkg != null) { 17614 /* 17615 * TODO why is the lock being held? doPostInstall is 17616 * called in other places without the lock. This needs 17617 * to be straightened out. 17618 */ 17619 // writer 17620 synchronized (mPackages) { 17621 retCode = PackageManager.INSTALL_SUCCEEDED; 17622 pkgList.add(pkg.packageName); 17623 // Post process args 17624 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 17625 pkg.applicationInfo.uid); 17626 } 17627 } else { 17628 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 17629 } 17630 } 17631 17632 } finally { 17633 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 17634 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 17635 } 17636 } 17637 } 17638 // writer 17639 synchronized (mPackages) { 17640 // If the platform SDK has changed since the last time we booted, 17641 // we need to re-grant app permission to catch any new ones that 17642 // appear. This is really a hack, and means that apps can in some 17643 // cases get permissions that the user didn't initially explicitly 17644 // allow... it would be nice to have some better way to handle 17645 // this situation. 17646 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 17647 : mSettings.getInternalVersion(); 17648 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 17649 : StorageManager.UUID_PRIVATE_INTERNAL; 17650 17651 int updateFlags = UPDATE_PERMISSIONS_ALL; 17652 if (ver.sdkVersion != mSdkVersion) { 17653 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 17654 + mSdkVersion + "; regranting permissions for external"); 17655 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 17656 } 17657 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 17658 17659 // Yay, everything is now upgraded 17660 ver.forceCurrent(); 17661 17662 // can downgrade to reader 17663 // Persist settings 17664 mSettings.writeLPr(); 17665 } 17666 // Send a broadcast to let everyone know we are done processing 17667 if (pkgList.size() > 0) { 17668 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 17669 } 17670 } 17671 17672 /* 17673 * Utility method to unload a list of specified containers 17674 */ 17675 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 17676 // Just unmount all valid containers. 17677 for (AsecInstallArgs arg : cidArgs) { 17678 synchronized (mInstallLock) { 17679 arg.doPostDeleteLI(false); 17680 } 17681 } 17682 } 17683 17684 /* 17685 * Unload packages mounted on external media. This involves deleting package 17686 * data from internal structures, sending broadcasts about disabled packages, 17687 * gc'ing to free up references, unmounting all secure containers 17688 * corresponding to packages on external media, and posting a 17689 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 17690 * that we always have to post this message if status has been requested no 17691 * matter what. 17692 */ 17693 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 17694 final boolean reportStatus) { 17695 if (DEBUG_SD_INSTALL) 17696 Log.i(TAG, "unloading media packages"); 17697 ArrayList<String> pkgList = new ArrayList<String>(); 17698 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 17699 final Set<AsecInstallArgs> keys = processCids.keySet(); 17700 for (AsecInstallArgs args : keys) { 17701 String pkgName = args.getPackageName(); 17702 if (DEBUG_SD_INSTALL) 17703 Log.i(TAG, "Trying to unload pkg : " + pkgName); 17704 // Delete package internally 17705 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 17706 synchronized (mInstallLock) { 17707 boolean res = deletePackageLI(pkgName, null, false, null, 17708 PackageManager.DELETE_KEEP_DATA, outInfo, false, null); 17709 if (res) { 17710 pkgList.add(pkgName); 17711 } else { 17712 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 17713 failedList.add(args); 17714 } 17715 } 17716 } 17717 17718 // reader 17719 synchronized (mPackages) { 17720 // We didn't update the settings after removing each package; 17721 // write them now for all packages. 17722 mSettings.writeLPr(); 17723 } 17724 17725 // We have to absolutely send UPDATED_MEDIA_STATUS only 17726 // after confirming that all the receivers processed the ordered 17727 // broadcast when packages get disabled, force a gc to clean things up. 17728 // and unload all the containers. 17729 if (pkgList.size() > 0) { 17730 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 17731 new IIntentReceiver.Stub() { 17732 public void performReceive(Intent intent, int resultCode, String data, 17733 Bundle extras, boolean ordered, boolean sticky, 17734 int sendingUser) throws RemoteException { 17735 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 17736 reportStatus ? 1 : 0, 1, keys); 17737 mHandler.sendMessage(msg); 17738 } 17739 }); 17740 } else { 17741 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 17742 keys); 17743 mHandler.sendMessage(msg); 17744 } 17745 } 17746 17747 private void loadPrivatePackages(final VolumeInfo vol) { 17748 mHandler.post(new Runnable() { 17749 @Override 17750 public void run() { 17751 loadPrivatePackagesInner(vol); 17752 } 17753 }); 17754 } 17755 17756 private void loadPrivatePackagesInner(VolumeInfo vol) { 17757 final String volumeUuid = vol.fsUuid; 17758 if (TextUtils.isEmpty(volumeUuid)) { 17759 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 17760 return; 17761 } 17762 17763 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 17764 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 17765 17766 final VersionInfo ver; 17767 final List<PackageSetting> packages; 17768 synchronized (mPackages) { 17769 ver = mSettings.findOrCreateVersion(volumeUuid); 17770 packages = mSettings.getVolumePackagesLPr(volumeUuid); 17771 } 17772 17773 // TODO: introduce a new concept similar to "frozen" to prevent these 17774 // apps from being launched until after data has been fully reconciled 17775 for (PackageSetting ps : packages) { 17776 synchronized (mInstallLock) { 17777 final PackageParser.Package pkg; 17778 try { 17779 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 17780 loaded.add(pkg.applicationInfo); 17781 17782 } catch (PackageManagerException e) { 17783 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 17784 } 17785 17786 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 17787 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 17788 } 17789 } 17790 } 17791 17792 // Reconcile app data for all started/unlocked users 17793 final StorageManager sm = mContext.getSystemService(StorageManager.class); 17794 final UserManager um = mContext.getSystemService(UserManager.class); 17795 for (UserInfo user : um.getUsers()) { 17796 final int flags; 17797 if (um.isUserUnlocked(user.id)) { 17798 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 17799 } else if (um.isUserRunning(user.id)) { 17800 flags = StorageManager.FLAG_STORAGE_DE; 17801 } else { 17802 continue; 17803 } 17804 17805 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 17806 reconcileAppsData(volumeUuid, user.id, flags); 17807 } 17808 17809 synchronized (mPackages) { 17810 int updateFlags = UPDATE_PERMISSIONS_ALL; 17811 if (ver.sdkVersion != mSdkVersion) { 17812 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 17813 + mSdkVersion + "; regranting permissions for " + volumeUuid); 17814 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 17815 } 17816 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 17817 17818 // Yay, everything is now upgraded 17819 ver.forceCurrent(); 17820 17821 mSettings.writeLPr(); 17822 } 17823 17824 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 17825 sendResourcesChangedBroadcast(true, false, loaded, null); 17826 } 17827 17828 private void unloadPrivatePackages(final VolumeInfo vol) { 17829 mHandler.post(new Runnable() { 17830 @Override 17831 public void run() { 17832 unloadPrivatePackagesInner(vol); 17833 } 17834 }); 17835 } 17836 17837 private void unloadPrivatePackagesInner(VolumeInfo vol) { 17838 final String volumeUuid = vol.fsUuid; 17839 if (TextUtils.isEmpty(volumeUuid)) { 17840 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 17841 return; 17842 } 17843 17844 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 17845 synchronized (mInstallLock) { 17846 synchronized (mPackages) { 17847 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 17848 for (PackageSetting ps : packages) { 17849 if (ps.pkg == null) continue; 17850 17851 final ApplicationInfo info = ps.pkg.applicationInfo; 17852 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 17853 if (deletePackageLI(ps.name, null, false, null, 17854 PackageManager.DELETE_KEEP_DATA, outInfo, false, null)) { 17855 unloaded.add(info); 17856 } else { 17857 Slog.w(TAG, "Failed to unload " + ps.codePath); 17858 } 17859 } 17860 17861 mSettings.writeLPr(); 17862 } 17863 } 17864 17865 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 17866 sendResourcesChangedBroadcast(false, false, unloaded, null); 17867 } 17868 17869 /** 17870 * Examine all users present on given mounted volume, and destroy data 17871 * belonging to users that are no longer valid, or whose user ID has been 17872 * recycled. 17873 */ 17874 private void reconcileUsers(String volumeUuid) { 17875 // TODO: also reconcile DE directories 17876 final File[] files = FileUtils 17877 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)); 17878 for (File file : files) { 17879 if (!file.isDirectory()) continue; 17880 17881 final int userId; 17882 final UserInfo info; 17883 try { 17884 userId = Integer.parseInt(file.getName()); 17885 info = sUserManager.getUserInfo(userId); 17886 } catch (NumberFormatException e) { 17887 Slog.w(TAG, "Invalid user directory " + file); 17888 continue; 17889 } 17890 17891 boolean destroyUser = false; 17892 if (info == null) { 17893 logCriticalInfo(Log.WARN, "Destroying user directory " + file 17894 + " because no matching user was found"); 17895 destroyUser = true; 17896 } else { 17897 try { 17898 UserManagerService.enforceSerialNumber(file, info.serialNumber); 17899 } catch (IOException e) { 17900 logCriticalInfo(Log.WARN, "Destroying user directory " + file 17901 + " because we failed to enforce serial number: " + e); 17902 destroyUser = true; 17903 } 17904 } 17905 17906 if (destroyUser) { 17907 synchronized (mInstallLock) { 17908 try { 17909 mInstaller.removeUserDataDirs(volumeUuid, userId); 17910 } catch (InstallerException e) { 17911 Slog.w(TAG, "Failed to clean up user dirs", e); 17912 } 17913 } 17914 } 17915 } 17916 } 17917 17918 private void assertPackageKnown(String volumeUuid, String packageName) 17919 throws PackageManagerException { 17920 synchronized (mPackages) { 17921 final PackageSetting ps = mSettings.mPackages.get(packageName); 17922 if (ps == null) { 17923 throw new PackageManagerException("Package " + packageName + " is unknown"); 17924 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 17925 throw new PackageManagerException( 17926 "Package " + packageName + " found on unknown volume " + volumeUuid 17927 + "; expected volume " + ps.volumeUuid); 17928 } 17929 } 17930 } 17931 17932 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 17933 throws PackageManagerException { 17934 synchronized (mPackages) { 17935 final PackageSetting ps = mSettings.mPackages.get(packageName); 17936 if (ps == null) { 17937 throw new PackageManagerException("Package " + packageName + " is unknown"); 17938 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 17939 throw new PackageManagerException( 17940 "Package " + packageName + " found on unknown volume " + volumeUuid 17941 + "; expected volume " + ps.volumeUuid); 17942 } else if (!ps.getInstalled(userId)) { 17943 throw new PackageManagerException( 17944 "Package " + packageName + " not installed for user " + userId); 17945 } 17946 } 17947 } 17948 17949 /** 17950 * Examine all apps present on given mounted volume, and destroy apps that 17951 * aren't expected, either due to uninstallation or reinstallation on 17952 * another volume. 17953 */ 17954 private void reconcileApps(String volumeUuid) { 17955 final File[] files = FileUtils 17956 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 17957 for (File file : files) { 17958 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 17959 && !PackageInstallerService.isStageName(file.getName()); 17960 if (!isPackage) { 17961 // Ignore entries which are not packages 17962 continue; 17963 } 17964 17965 try { 17966 final PackageLite pkg = PackageParser.parsePackageLite(file, 17967 PackageParser.PARSE_MUST_BE_APK); 17968 assertPackageKnown(volumeUuid, pkg.packageName); 17969 17970 } catch (PackageParserException | PackageManagerException e) { 17971 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 17972 synchronized (mInstallLock) { 17973 removeCodePathLI(file); 17974 } 17975 } 17976 } 17977 } 17978 17979 /** 17980 * Reconcile all app data for the given user. 17981 * <p> 17982 * Verifies that directories exist and that ownership and labeling is 17983 * correct for all installed apps on all mounted volumes. 17984 */ 17985 void reconcileAppsData(int userId, int flags) { 17986 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17987 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 17988 final String volumeUuid = vol.getFsUuid(); 17989 reconcileAppsData(volumeUuid, userId, flags); 17990 } 17991 } 17992 17993 /** 17994 * Reconcile all app data on given mounted volume. 17995 * <p> 17996 * Destroys app data that isn't expected, either due to uninstallation or 17997 * reinstallation on another volume. 17998 * <p> 17999 * Verifies that directories exist and that ownership and labeling is 18000 * correct for all installed apps. 18001 */ 18002 private void reconcileAppsData(String volumeUuid, int userId, int flags) { 18003 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 18004 + Integer.toHexString(flags)); 18005 18006 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 18007 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 18008 18009 boolean restoreconNeeded = false; 18010 18011 // First look for stale data that doesn't belong, and check if things 18012 // have changed since we did our last restorecon 18013 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18014 if (!isUserKeyUnlocked(userId)) { 18015 throw new RuntimeException( 18016 "Yikes, someone asked us to reconcile CE storage while " + userId 18017 + " was still locked; this would have caused massive data loss!"); 18018 } 18019 18020 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 18021 18022 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 18023 for (File file : files) { 18024 final String packageName = file.getName(); 18025 try { 18026 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18027 } catch (PackageManagerException e) { 18028 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18029 synchronized (mInstallLock) { 18030 destroyAppDataLI(volumeUuid, packageName, userId, 18031 StorageManager.FLAG_STORAGE_CE); 18032 } 18033 } 18034 } 18035 } 18036 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18037 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 18038 18039 final File[] files = FileUtils.listFilesOrEmpty(deDir); 18040 for (File file : files) { 18041 final String packageName = file.getName(); 18042 try { 18043 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18044 } catch (PackageManagerException e) { 18045 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18046 synchronized (mInstallLock) { 18047 destroyAppDataLI(volumeUuid, packageName, userId, 18048 StorageManager.FLAG_STORAGE_DE); 18049 } 18050 } 18051 } 18052 } 18053 18054 // Ensure that data directories are ready to roll for all packages 18055 // installed for this volume and user 18056 final List<PackageSetting> packages; 18057 synchronized (mPackages) { 18058 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18059 } 18060 int preparedCount = 0; 18061 for (PackageSetting ps : packages) { 18062 final String packageName = ps.name; 18063 if (ps.pkg == null) { 18064 Slog.w(TAG, "Odd, missing scanned package " + packageName); 18065 // TODO: might be due to legacy ASEC apps; we should circle back 18066 // and reconcile again once they're scanned 18067 continue; 18068 } 18069 18070 if (ps.getInstalled(userId)) { 18071 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 18072 18073 if (maybeMigrateAppData(volumeUuid, userId, ps.pkg)) { 18074 // We may have just shuffled around app data directories, so 18075 // prepare them one more time 18076 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 18077 } 18078 18079 preparedCount++; 18080 } 18081 } 18082 18083 if (restoreconNeeded) { 18084 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18085 SELinuxMMAC.setRestoreconDone(ceDir); 18086 } 18087 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18088 SELinuxMMAC.setRestoreconDone(deDir); 18089 } 18090 } 18091 18092 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 18093 + " packages; restoreconNeeded was " + restoreconNeeded); 18094 } 18095 18096 /** 18097 * Prepare app data for the given app just after it was installed or 18098 * upgraded. This method carefully only touches users that it's installed 18099 * for, and it forces a restorecon to handle any seinfo changes. 18100 * <p> 18101 * Verifies that directories exist and that ownership and labeling is 18102 * correct for all installed apps. If there is an ownership mismatch, it 18103 * will try recovering system apps by wiping data; third-party app data is 18104 * left intact. 18105 * <p> 18106 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 18107 */ 18108 private void prepareAppDataAfterInstall(PackageParser.Package pkg) { 18109 prepareAppDataAfterInstallInternal(pkg); 18110 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 18111 for (int i = 0; i < childCount; i++) { 18112 PackageParser.Package childPackage = pkg.childPackages.get(i); 18113 prepareAppDataAfterInstallInternal(childPackage); 18114 } 18115 } 18116 18117 private void prepareAppDataAfterInstallInternal(PackageParser.Package pkg) { 18118 final PackageSetting ps; 18119 synchronized (mPackages) { 18120 ps = mSettings.mPackages.get(pkg.packageName); 18121 mSettings.writeKernelMappingLPr(ps); 18122 } 18123 18124 final UserManager um = mContext.getSystemService(UserManager.class); 18125 for (UserInfo user : um.getUsers()) { 18126 final int flags; 18127 if (um.isUserUnlocked(user.id)) { 18128 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18129 } else if (um.isUserRunning(user.id)) { 18130 flags = StorageManager.FLAG_STORAGE_DE; 18131 } else { 18132 continue; 18133 } 18134 18135 if (ps.getInstalled(user.id)) { 18136 // Whenever an app changes, force a restorecon of its data 18137 // TODO: when user data is locked, mark that we're still dirty 18138 prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true); 18139 } 18140 } 18141 } 18142 18143 /** 18144 * Prepare app data for the given app. 18145 * <p> 18146 * Verifies that directories exist and that ownership and labeling is 18147 * correct for all installed apps. If there is an ownership mismatch, this 18148 * will try recovering system apps by wiping data; third-party app data is 18149 * left intact. 18150 */ 18151 private void prepareAppData(String volumeUuid, int userId, int flags, 18152 PackageParser.Package pkg, boolean restoreconNeeded) { 18153 if (DEBUG_APP_DATA) { 18154 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 18155 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 18156 } 18157 18158 final String packageName = pkg.packageName; 18159 final ApplicationInfo app = pkg.applicationInfo; 18160 final int appId = UserHandle.getAppId(app.uid); 18161 18162 Preconditions.checkNotNull(app.seinfo); 18163 18164 synchronized (mInstallLock) { 18165 try { 18166 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18167 appId, app.seinfo, app.targetSdkVersion); 18168 } catch (InstallerException e) { 18169 if (app.isSystemApp()) { 18170 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 18171 + ", but trying to recover: " + e); 18172 destroyAppDataLI(volumeUuid, packageName, userId, flags); 18173 try { 18174 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18175 appId, app.seinfo, app.targetSdkVersion); 18176 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 18177 } catch (InstallerException e2) { 18178 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 18179 } 18180 } else { 18181 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 18182 } 18183 } 18184 18185 if (restoreconNeeded) { 18186 restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo); 18187 } 18188 18189 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18190 // Create a native library symlink only if we have native libraries 18191 // and if the native libraries are 32 bit libraries. We do not provide 18192 // this symlink for 64 bit libraries. 18193 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 18194 final String nativeLibPath = app.nativeLibraryDir; 18195 try { 18196 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 18197 nativeLibPath, userId); 18198 } catch (InstallerException e) { 18199 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 18200 } 18201 } 18202 } 18203 } 18204 } 18205 18206 /** 18207 * For system apps on non-FBE devices, this method migrates any existing 18208 * CE/DE data to match the {@code forceDeviceEncrypted} flag requested by 18209 * the app. 18210 */ 18211 private boolean maybeMigrateAppData(String volumeUuid, int userId, PackageParser.Package pkg) { 18212 if (pkg.isSystemApp() && !StorageManager.isFileBasedEncryptionEnabled() 18213 && PackageManager.APPLY_FORCE_DEVICE_ENCRYPTED) { 18214 final int storageTarget = pkg.applicationInfo.isForceDeviceEncrypted() 18215 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 18216 synchronized (mInstallLock) { 18217 try { 18218 mInstaller.migrateAppData(volumeUuid, pkg.packageName, userId, storageTarget); 18219 } catch (InstallerException e) { 18220 logCriticalInfo(Log.WARN, 18221 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 18222 } 18223 } 18224 return true; 18225 } else { 18226 return false; 18227 } 18228 } 18229 18230 private void unfreezePackage(String packageName) { 18231 synchronized (mPackages) { 18232 final PackageSetting ps = mSettings.mPackages.get(packageName); 18233 if (ps != null) { 18234 ps.frozen = false; 18235 } 18236 } 18237 } 18238 18239 @Override 18240 public int movePackage(final String packageName, final String volumeUuid) { 18241 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 18242 18243 final int moveId = mNextMoveId.getAndIncrement(); 18244 mHandler.post(new Runnable() { 18245 @Override 18246 public void run() { 18247 try { 18248 movePackageInternal(packageName, volumeUuid, moveId); 18249 } catch (PackageManagerException e) { 18250 Slog.w(TAG, "Failed to move " + packageName, e); 18251 mMoveCallbacks.notifyStatusChanged(moveId, 18252 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 18253 } 18254 } 18255 }); 18256 return moveId; 18257 } 18258 18259 private void movePackageInternal(final String packageName, final String volumeUuid, 18260 final int moveId) throws PackageManagerException { 18261 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 18262 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18263 final PackageManager pm = mContext.getPackageManager(); 18264 18265 final boolean currentAsec; 18266 final String currentVolumeUuid; 18267 final File codeFile; 18268 final String installerPackageName; 18269 final String packageAbiOverride; 18270 final int appId; 18271 final String seinfo; 18272 final String label; 18273 final int targetSdkVersion; 18274 18275 // reader 18276 synchronized (mPackages) { 18277 final PackageParser.Package pkg = mPackages.get(packageName); 18278 final PackageSetting ps = mSettings.mPackages.get(packageName); 18279 if (pkg == null || ps == null) { 18280 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 18281 } 18282 18283 if (pkg.applicationInfo.isSystemApp()) { 18284 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 18285 "Cannot move system application"); 18286 } 18287 18288 if (pkg.applicationInfo.isExternalAsec()) { 18289 currentAsec = true; 18290 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 18291 } else if (pkg.applicationInfo.isForwardLocked()) { 18292 currentAsec = true; 18293 currentVolumeUuid = "forward_locked"; 18294 } else { 18295 currentAsec = false; 18296 currentVolumeUuid = ps.volumeUuid; 18297 18298 final File probe = new File(pkg.codePath); 18299 final File probeOat = new File(probe, "oat"); 18300 if (!probe.isDirectory() || !probeOat.isDirectory()) { 18301 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18302 "Move only supported for modern cluster style installs"); 18303 } 18304 } 18305 18306 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 18307 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18308 "Package already moved to " + volumeUuid); 18309 } 18310 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 18311 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 18312 "Device admin cannot be moved"); 18313 } 18314 18315 if (ps.frozen) { 18316 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 18317 "Failed to move already frozen package"); 18318 } 18319 ps.frozen = true; 18320 18321 codeFile = new File(pkg.codePath); 18322 installerPackageName = ps.installerPackageName; 18323 packageAbiOverride = ps.cpuAbiOverrideString; 18324 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18325 seinfo = pkg.applicationInfo.seinfo; 18326 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 18327 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 18328 } 18329 18330 // Now that we're guarded by frozen state, kill app during move 18331 final long token = Binder.clearCallingIdentity(); 18332 try { 18333 killApplication(packageName, appId, "move pkg"); 18334 } finally { 18335 Binder.restoreCallingIdentity(token); 18336 } 18337 18338 final Bundle extras = new Bundle(); 18339 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 18340 extras.putString(Intent.EXTRA_TITLE, label); 18341 mMoveCallbacks.notifyCreated(moveId, extras); 18342 18343 int installFlags; 18344 final boolean moveCompleteApp; 18345 final File measurePath; 18346 18347 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 18348 installFlags = INSTALL_INTERNAL; 18349 moveCompleteApp = !currentAsec; 18350 measurePath = Environment.getDataAppDirectory(volumeUuid); 18351 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 18352 installFlags = INSTALL_EXTERNAL; 18353 moveCompleteApp = false; 18354 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 18355 } else { 18356 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 18357 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 18358 || !volume.isMountedWritable()) { 18359 unfreezePackage(packageName); 18360 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18361 "Move location not mounted private volume"); 18362 } 18363 18364 Preconditions.checkState(!currentAsec); 18365 18366 installFlags = INSTALL_INTERNAL; 18367 moveCompleteApp = true; 18368 measurePath = Environment.getDataAppDirectory(volumeUuid); 18369 } 18370 18371 final PackageStats stats = new PackageStats(null, -1); 18372 synchronized (mInstaller) { 18373 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 18374 unfreezePackage(packageName); 18375 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18376 "Failed to measure package size"); 18377 } 18378 } 18379 18380 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 18381 + stats.dataSize); 18382 18383 final long startFreeBytes = measurePath.getFreeSpace(); 18384 final long sizeBytes; 18385 if (moveCompleteApp) { 18386 sizeBytes = stats.codeSize + stats.dataSize; 18387 } else { 18388 sizeBytes = stats.codeSize; 18389 } 18390 18391 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 18392 unfreezePackage(packageName); 18393 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18394 "Not enough free space to move"); 18395 } 18396 18397 mMoveCallbacks.notifyStatusChanged(moveId, 10); 18398 18399 final CountDownLatch installedLatch = new CountDownLatch(1); 18400 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 18401 @Override 18402 public void onUserActionRequired(Intent intent) throws RemoteException { 18403 throw new IllegalStateException(); 18404 } 18405 18406 @Override 18407 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 18408 Bundle extras) throws RemoteException { 18409 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 18410 + PackageManager.installStatusToString(returnCode, msg)); 18411 18412 installedLatch.countDown(); 18413 18414 // Regardless of success or failure of the move operation, 18415 // always unfreeze the package 18416 unfreezePackage(packageName); 18417 18418 final int status = PackageManager.installStatusToPublicStatus(returnCode); 18419 switch (status) { 18420 case PackageInstaller.STATUS_SUCCESS: 18421 mMoveCallbacks.notifyStatusChanged(moveId, 18422 PackageManager.MOVE_SUCCEEDED); 18423 break; 18424 case PackageInstaller.STATUS_FAILURE_STORAGE: 18425 mMoveCallbacks.notifyStatusChanged(moveId, 18426 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 18427 break; 18428 default: 18429 mMoveCallbacks.notifyStatusChanged(moveId, 18430 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 18431 break; 18432 } 18433 } 18434 }; 18435 18436 final MoveInfo move; 18437 if (moveCompleteApp) { 18438 // Kick off a thread to report progress estimates 18439 new Thread() { 18440 @Override 18441 public void run() { 18442 while (true) { 18443 try { 18444 if (installedLatch.await(1, TimeUnit.SECONDS)) { 18445 break; 18446 } 18447 } catch (InterruptedException ignored) { 18448 } 18449 18450 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 18451 final int progress = 10 + (int) MathUtils.constrain( 18452 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 18453 mMoveCallbacks.notifyStatusChanged(moveId, progress); 18454 } 18455 } 18456 }.start(); 18457 18458 final String dataAppName = codeFile.getName(); 18459 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 18460 dataAppName, appId, seinfo, targetSdkVersion); 18461 } else { 18462 move = null; 18463 } 18464 18465 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 18466 18467 final Message msg = mHandler.obtainMessage(INIT_COPY); 18468 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 18469 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 18470 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 18471 packageAbiOverride, null); 18472 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 18473 msg.obj = params; 18474 18475 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 18476 System.identityHashCode(msg.obj)); 18477 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 18478 System.identityHashCode(msg.obj)); 18479 18480 mHandler.sendMessage(msg); 18481 } 18482 18483 @Override 18484 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 18485 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 18486 18487 final int realMoveId = mNextMoveId.getAndIncrement(); 18488 final Bundle extras = new Bundle(); 18489 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 18490 mMoveCallbacks.notifyCreated(realMoveId, extras); 18491 18492 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 18493 @Override 18494 public void onCreated(int moveId, Bundle extras) { 18495 // Ignored 18496 } 18497 18498 @Override 18499 public void onStatusChanged(int moveId, int status, long estMillis) { 18500 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 18501 } 18502 }; 18503 18504 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18505 storage.setPrimaryStorageUuid(volumeUuid, callback); 18506 return realMoveId; 18507 } 18508 18509 @Override 18510 public int getMoveStatus(int moveId) { 18511 mContext.enforceCallingOrSelfPermission( 18512 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18513 return mMoveCallbacks.mLastStatus.get(moveId); 18514 } 18515 18516 @Override 18517 public void registerMoveCallback(IPackageMoveObserver callback) { 18518 mContext.enforceCallingOrSelfPermission( 18519 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18520 mMoveCallbacks.register(callback); 18521 } 18522 18523 @Override 18524 public void unregisterMoveCallback(IPackageMoveObserver callback) { 18525 mContext.enforceCallingOrSelfPermission( 18526 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18527 mMoveCallbacks.unregister(callback); 18528 } 18529 18530 @Override 18531 public boolean setInstallLocation(int loc) { 18532 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 18533 null); 18534 if (getInstallLocation() == loc) { 18535 return true; 18536 } 18537 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 18538 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 18539 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 18540 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 18541 return true; 18542 } 18543 return false; 18544 } 18545 18546 @Override 18547 public int getInstallLocation() { 18548 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 18549 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 18550 PackageHelper.APP_INSTALL_AUTO); 18551 } 18552 18553 /** Called by UserManagerService */ 18554 void cleanUpUser(UserManagerService userManager, int userHandle) { 18555 synchronized (mPackages) { 18556 mDirtyUsers.remove(userHandle); 18557 mUserNeedsBadging.delete(userHandle); 18558 mSettings.removeUserLPw(userHandle); 18559 mPendingBroadcasts.remove(userHandle); 18560 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 18561 } 18562 synchronized (mInstallLock) { 18563 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18564 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18565 final String volumeUuid = vol.getFsUuid(); 18566 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 18567 try { 18568 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 18569 } catch (InstallerException e) { 18570 Slog.w(TAG, "Failed to remove user data", e); 18571 } 18572 } 18573 synchronized (mPackages) { 18574 removeUnusedPackagesLILPw(userManager, userHandle); 18575 } 18576 } 18577 } 18578 18579 /** 18580 * We're removing userHandle and would like to remove any downloaded packages 18581 * that are no longer in use by any other user. 18582 * @param userHandle the user being removed 18583 */ 18584 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 18585 final boolean DEBUG_CLEAN_APKS = false; 18586 int [] users = userManager.getUserIds(); 18587 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 18588 while (psit.hasNext()) { 18589 PackageSetting ps = psit.next(); 18590 if (ps.pkg == null) { 18591 continue; 18592 } 18593 final String packageName = ps.pkg.packageName; 18594 // Skip over if system app 18595 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 18596 continue; 18597 } 18598 if (DEBUG_CLEAN_APKS) { 18599 Slog.i(TAG, "Checking package " + packageName); 18600 } 18601 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 18602 if (keep) { 18603 if (DEBUG_CLEAN_APKS) { 18604 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 18605 } 18606 } else { 18607 for (int i = 0; i < users.length; i++) { 18608 if (users[i] != userHandle && ps.getInstalled(users[i])) { 18609 keep = true; 18610 if (DEBUG_CLEAN_APKS) { 18611 Slog.i(TAG, " Keeping package " + packageName + " for user " 18612 + users[i]); 18613 } 18614 break; 18615 } 18616 } 18617 } 18618 if (!keep) { 18619 if (DEBUG_CLEAN_APKS) { 18620 Slog.i(TAG, " Removing package " + packageName); 18621 } 18622 mHandler.post(new Runnable() { 18623 public void run() { 18624 deletePackageX(packageName, userHandle, 0); 18625 } //end run 18626 }); 18627 } 18628 } 18629 } 18630 18631 /** Called by UserManagerService */ 18632 void createNewUser(int userHandle) { 18633 synchronized (mInstallLock) { 18634 try { 18635 mInstaller.createUserConfig(userHandle); 18636 } catch (InstallerException e) { 18637 Slog.w(TAG, "Failed to create user config", e); 18638 } 18639 mSettings.createNewUserLI(this, mInstaller, userHandle); 18640 } 18641 synchronized (mPackages) { 18642 applyFactoryDefaultBrowserLPw(userHandle); 18643 primeDomainVerificationsLPw(userHandle); 18644 } 18645 } 18646 18647 void newUserCreated(final int userHandle) { 18648 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 18649 // If permission review for legacy apps is required, we represent 18650 // dagerous permissions for such apps as always granted runtime 18651 // permissions to keep per user flag state whether review is needed. 18652 // Hence, if a new user is added we have to propagate dangerous 18653 // permission grants for these legacy apps. 18654 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 18655 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 18656 | UPDATE_PERMISSIONS_REPLACE_ALL); 18657 } 18658 } 18659 18660 @Override 18661 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 18662 mContext.enforceCallingOrSelfPermission( 18663 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 18664 "Only package verification agents can read the verifier device identity"); 18665 18666 synchronized (mPackages) { 18667 return mSettings.getVerifierDeviceIdentityLPw(); 18668 } 18669 } 18670 18671 @Override 18672 public void setPermissionEnforced(String permission, boolean enforced) { 18673 // TODO: Now that we no longer change GID for storage, this should to away. 18674 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 18675 "setPermissionEnforced"); 18676 if (READ_EXTERNAL_STORAGE.equals(permission)) { 18677 synchronized (mPackages) { 18678 if (mSettings.mReadExternalStorageEnforced == null 18679 || mSettings.mReadExternalStorageEnforced != enforced) { 18680 mSettings.mReadExternalStorageEnforced = enforced; 18681 mSettings.writeLPr(); 18682 } 18683 } 18684 // kill any non-foreground processes so we restart them and 18685 // grant/revoke the GID. 18686 final IActivityManager am = ActivityManagerNative.getDefault(); 18687 if (am != null) { 18688 final long token = Binder.clearCallingIdentity(); 18689 try { 18690 am.killProcessesBelowForeground("setPermissionEnforcement"); 18691 } catch (RemoteException e) { 18692 } finally { 18693 Binder.restoreCallingIdentity(token); 18694 } 18695 } 18696 } else { 18697 throw new IllegalArgumentException("No selective enforcement for " + permission); 18698 } 18699 } 18700 18701 @Override 18702 @Deprecated 18703 public boolean isPermissionEnforced(String permission) { 18704 return true; 18705 } 18706 18707 @Override 18708 public boolean isStorageLow() { 18709 final long token = Binder.clearCallingIdentity(); 18710 try { 18711 final DeviceStorageMonitorInternal 18712 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 18713 if (dsm != null) { 18714 return dsm.isMemoryLow(); 18715 } else { 18716 return false; 18717 } 18718 } finally { 18719 Binder.restoreCallingIdentity(token); 18720 } 18721 } 18722 18723 @Override 18724 public IPackageInstaller getPackageInstaller() { 18725 return mInstallerService; 18726 } 18727 18728 private boolean userNeedsBadging(int userId) { 18729 int index = mUserNeedsBadging.indexOfKey(userId); 18730 if (index < 0) { 18731 final UserInfo userInfo; 18732 final long token = Binder.clearCallingIdentity(); 18733 try { 18734 userInfo = sUserManager.getUserInfo(userId); 18735 } finally { 18736 Binder.restoreCallingIdentity(token); 18737 } 18738 final boolean b; 18739 if (userInfo != null && userInfo.isManagedProfile()) { 18740 b = true; 18741 } else { 18742 b = false; 18743 } 18744 mUserNeedsBadging.put(userId, b); 18745 return b; 18746 } 18747 return mUserNeedsBadging.valueAt(index); 18748 } 18749 18750 @Override 18751 public KeySet getKeySetByAlias(String packageName, String alias) { 18752 if (packageName == null || alias == null) { 18753 return null; 18754 } 18755 synchronized(mPackages) { 18756 final PackageParser.Package pkg = mPackages.get(packageName); 18757 if (pkg == null) { 18758 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18759 throw new IllegalArgumentException("Unknown package: " + packageName); 18760 } 18761 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18762 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 18763 } 18764 } 18765 18766 @Override 18767 public KeySet getSigningKeySet(String packageName) { 18768 if (packageName == null) { 18769 return null; 18770 } 18771 synchronized(mPackages) { 18772 final PackageParser.Package pkg = mPackages.get(packageName); 18773 if (pkg == null) { 18774 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18775 throw new IllegalArgumentException("Unknown package: " + packageName); 18776 } 18777 if (pkg.applicationInfo.uid != Binder.getCallingUid() 18778 && Process.SYSTEM_UID != Binder.getCallingUid()) { 18779 throw new SecurityException("May not access signing KeySet of other apps."); 18780 } 18781 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18782 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 18783 } 18784 } 18785 18786 @Override 18787 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 18788 if (packageName == null || ks == null) { 18789 return false; 18790 } 18791 synchronized(mPackages) { 18792 final PackageParser.Package pkg = mPackages.get(packageName); 18793 if (pkg == null) { 18794 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18795 throw new IllegalArgumentException("Unknown package: " + packageName); 18796 } 18797 IBinder ksh = ks.getToken(); 18798 if (ksh instanceof KeySetHandle) { 18799 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18800 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 18801 } 18802 return false; 18803 } 18804 } 18805 18806 @Override 18807 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 18808 if (packageName == null || ks == null) { 18809 return false; 18810 } 18811 synchronized(mPackages) { 18812 final PackageParser.Package pkg = mPackages.get(packageName); 18813 if (pkg == null) { 18814 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18815 throw new IllegalArgumentException("Unknown package: " + packageName); 18816 } 18817 IBinder ksh = ks.getToken(); 18818 if (ksh instanceof KeySetHandle) { 18819 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18820 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 18821 } 18822 return false; 18823 } 18824 } 18825 18826 private void deletePackageIfUnusedLPr(final String packageName) { 18827 PackageSetting ps = mSettings.mPackages.get(packageName); 18828 if (ps == null) { 18829 return; 18830 } 18831 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 18832 // TODO Implement atomic delete if package is unused 18833 // It is currently possible that the package will be deleted even if it is installed 18834 // after this method returns. 18835 mHandler.post(new Runnable() { 18836 public void run() { 18837 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 18838 } 18839 }); 18840 } 18841 } 18842 18843 /** 18844 * Check and throw if the given before/after packages would be considered a 18845 * downgrade. 18846 */ 18847 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 18848 throws PackageManagerException { 18849 if (after.versionCode < before.mVersionCode) { 18850 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 18851 "Update version code " + after.versionCode + " is older than current " 18852 + before.mVersionCode); 18853 } else if (after.versionCode == before.mVersionCode) { 18854 if (after.baseRevisionCode < before.baseRevisionCode) { 18855 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 18856 "Update base revision code " + after.baseRevisionCode 18857 + " is older than current " + before.baseRevisionCode); 18858 } 18859 18860 if (!ArrayUtils.isEmpty(after.splitNames)) { 18861 for (int i = 0; i < after.splitNames.length; i++) { 18862 final String splitName = after.splitNames[i]; 18863 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 18864 if (j != -1) { 18865 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 18866 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 18867 "Update split " + splitName + " revision code " 18868 + after.splitRevisionCodes[i] + " is older than current " 18869 + before.splitRevisionCodes[j]); 18870 } 18871 } 18872 } 18873 } 18874 } 18875 } 18876 18877 private static class MoveCallbacks extends Handler { 18878 private static final int MSG_CREATED = 1; 18879 private static final int MSG_STATUS_CHANGED = 2; 18880 18881 private final RemoteCallbackList<IPackageMoveObserver> 18882 mCallbacks = new RemoteCallbackList<>(); 18883 18884 private final SparseIntArray mLastStatus = new SparseIntArray(); 18885 18886 public MoveCallbacks(Looper looper) { 18887 super(looper); 18888 } 18889 18890 public void register(IPackageMoveObserver callback) { 18891 mCallbacks.register(callback); 18892 } 18893 18894 public void unregister(IPackageMoveObserver callback) { 18895 mCallbacks.unregister(callback); 18896 } 18897 18898 @Override 18899 public void handleMessage(Message msg) { 18900 final SomeArgs args = (SomeArgs) msg.obj; 18901 final int n = mCallbacks.beginBroadcast(); 18902 for (int i = 0; i < n; i++) { 18903 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 18904 try { 18905 invokeCallback(callback, msg.what, args); 18906 } catch (RemoteException ignored) { 18907 } 18908 } 18909 mCallbacks.finishBroadcast(); 18910 args.recycle(); 18911 } 18912 18913 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 18914 throws RemoteException { 18915 switch (what) { 18916 case MSG_CREATED: { 18917 callback.onCreated(args.argi1, (Bundle) args.arg2); 18918 break; 18919 } 18920 case MSG_STATUS_CHANGED: { 18921 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 18922 break; 18923 } 18924 } 18925 } 18926 18927 private void notifyCreated(int moveId, Bundle extras) { 18928 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 18929 18930 final SomeArgs args = SomeArgs.obtain(); 18931 args.argi1 = moveId; 18932 args.arg2 = extras; 18933 obtainMessage(MSG_CREATED, args).sendToTarget(); 18934 } 18935 18936 private void notifyStatusChanged(int moveId, int status) { 18937 notifyStatusChanged(moveId, status, -1); 18938 } 18939 18940 private void notifyStatusChanged(int moveId, int status, long estMillis) { 18941 Slog.v(TAG, "Move " + moveId + " status " + status); 18942 18943 final SomeArgs args = SomeArgs.obtain(); 18944 args.argi1 = moveId; 18945 args.argi2 = status; 18946 args.arg3 = estMillis; 18947 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 18948 18949 synchronized (mLastStatus) { 18950 mLastStatus.put(moveId, status); 18951 } 18952 } 18953 } 18954 18955 private final static class OnPermissionChangeListeners extends Handler { 18956 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 18957 18958 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 18959 new RemoteCallbackList<>(); 18960 18961 public OnPermissionChangeListeners(Looper looper) { 18962 super(looper); 18963 } 18964 18965 @Override 18966 public void handleMessage(Message msg) { 18967 switch (msg.what) { 18968 case MSG_ON_PERMISSIONS_CHANGED: { 18969 final int uid = msg.arg1; 18970 handleOnPermissionsChanged(uid); 18971 } break; 18972 } 18973 } 18974 18975 public void addListenerLocked(IOnPermissionsChangeListener listener) { 18976 mPermissionListeners.register(listener); 18977 18978 } 18979 18980 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 18981 mPermissionListeners.unregister(listener); 18982 } 18983 18984 public void onPermissionsChanged(int uid) { 18985 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 18986 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 18987 } 18988 } 18989 18990 private void handleOnPermissionsChanged(int uid) { 18991 final int count = mPermissionListeners.beginBroadcast(); 18992 try { 18993 for (int i = 0; i < count; i++) { 18994 IOnPermissionsChangeListener callback = mPermissionListeners 18995 .getBroadcastItem(i); 18996 try { 18997 callback.onPermissionsChanged(uid); 18998 } catch (RemoteException e) { 18999 Log.e(TAG, "Permission listener is dead", e); 19000 } 19001 } 19002 } finally { 19003 mPermissionListeners.finishBroadcast(); 19004 } 19005 } 19006 } 19007 19008 private class PackageManagerInternalImpl extends PackageManagerInternal { 19009 @Override 19010 public void setLocationPackagesProvider(PackagesProvider provider) { 19011 synchronized (mPackages) { 19012 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 19013 } 19014 } 19015 19016 @Override 19017 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 19018 synchronized (mPackages) { 19019 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 19020 } 19021 } 19022 19023 @Override 19024 public void setSmsAppPackagesProvider(PackagesProvider provider) { 19025 synchronized (mPackages) { 19026 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 19027 } 19028 } 19029 19030 @Override 19031 public void setDialerAppPackagesProvider(PackagesProvider provider) { 19032 synchronized (mPackages) { 19033 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 19034 } 19035 } 19036 19037 @Override 19038 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 19039 synchronized (mPackages) { 19040 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 19041 } 19042 } 19043 19044 @Override 19045 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 19046 synchronized (mPackages) { 19047 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 19048 } 19049 } 19050 19051 @Override 19052 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 19053 synchronized (mPackages) { 19054 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 19055 packageName, userId); 19056 } 19057 } 19058 19059 @Override 19060 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 19061 synchronized (mPackages) { 19062 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 19063 packageName, userId); 19064 } 19065 } 19066 19067 @Override 19068 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 19069 synchronized (mPackages) { 19070 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 19071 packageName, userId); 19072 } 19073 } 19074 19075 @Override 19076 public void setKeepUninstalledPackages(final List<String> packageList) { 19077 Preconditions.checkNotNull(packageList); 19078 List<String> removedFromList = null; 19079 synchronized (mPackages) { 19080 if (mKeepUninstalledPackages != null) { 19081 final int packagesCount = mKeepUninstalledPackages.size(); 19082 for (int i = 0; i < packagesCount; i++) { 19083 String oldPackage = mKeepUninstalledPackages.get(i); 19084 if (packageList != null && packageList.contains(oldPackage)) { 19085 continue; 19086 } 19087 if (removedFromList == null) { 19088 removedFromList = new ArrayList<>(); 19089 } 19090 removedFromList.add(oldPackage); 19091 } 19092 } 19093 mKeepUninstalledPackages = new ArrayList<>(packageList); 19094 if (removedFromList != null) { 19095 final int removedCount = removedFromList.size(); 19096 for (int i = 0; i < removedCount; i++) { 19097 deletePackageIfUnusedLPr(removedFromList.get(i)); 19098 } 19099 } 19100 } 19101 } 19102 19103 @Override 19104 public boolean isPermissionsReviewRequired(String packageName, int userId) { 19105 synchronized (mPackages) { 19106 // If we do not support permission review, done. 19107 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 19108 return false; 19109 } 19110 19111 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 19112 if (packageSetting == null) { 19113 return false; 19114 } 19115 19116 // Permission review applies only to apps not supporting the new permission model. 19117 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 19118 return false; 19119 } 19120 19121 // Legacy apps have the permission and get user consent on launch. 19122 PermissionsState permissionsState = packageSetting.getPermissionsState(); 19123 return permissionsState.isPermissionReviewRequired(userId); 19124 } 19125 } 19126 } 19127 19128 @Override 19129 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 19130 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 19131 synchronized (mPackages) { 19132 final long identity = Binder.clearCallingIdentity(); 19133 try { 19134 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 19135 packageNames, userId); 19136 } finally { 19137 Binder.restoreCallingIdentity(identity); 19138 } 19139 } 19140 } 19141 19142 private static void enforceSystemOrPhoneCaller(String tag) { 19143 int callingUid = Binder.getCallingUid(); 19144 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 19145 throw new SecurityException( 19146 "Cannot call " + tag + " from UID " + callingUid); 19147 } 19148 } 19149 19150 boolean isHistoricalPackageUsageAvailable() { 19151 return mPackageUsage.isHistoricalPackageUsageAvailable(); 19152 } 19153} 19154