PackageManagerService.java revision ca6abfd9d6c815053a89cf5c2bac11375b7de487
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.VerificationParams; 157import android.content.pm.VerifierDeviceIdentity; 158import android.content.pm.VerifierInfo; 159import android.content.res.Resources; 160import android.graphics.Bitmap; 161import android.hardware.display.DisplayManager; 162import android.net.Uri; 163import android.os.Binder; 164import android.os.Build; 165import android.os.Bundle; 166import android.os.Debug; 167import android.os.Environment; 168import android.os.Environment.UserEnvironment; 169import android.os.FileUtils; 170import android.os.Handler; 171import android.os.IBinder; 172import android.os.Looper; 173import android.os.Message; 174import android.os.Parcel; 175import android.os.ParcelFileDescriptor; 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, false, false, "is package available"); 2892 synchronized (mPackages) { 2893 PackageParser.Package p = mPackages.get(packageName); 2894 if (p != null) { 2895 final PackageSetting ps = (PackageSetting) p.mExtras; 2896 if (ps != null) { 2897 final PackageUserState state = ps.readUserState(userId); 2898 if (state != null) { 2899 return PackageParser.isAvailable(state); 2900 } 2901 } 2902 } 2903 } 2904 return false; 2905 } 2906 2907 @Override 2908 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2909 if (!sUserManager.exists(userId)) return null; 2910 flags = updateFlagsForPackage(flags, userId, packageName); 2911 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2912 // reader 2913 synchronized (mPackages) { 2914 PackageParser.Package p = mPackages.get(packageName); 2915 if (DEBUG_PACKAGE_INFO) 2916 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2917 if (p != null) { 2918 return generatePackageInfo(p, flags, userId); 2919 } 2920 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2921 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2922 } 2923 } 2924 return null; 2925 } 2926 2927 @Override 2928 public String[] currentToCanonicalPackageNames(String[] names) { 2929 String[] out = new String[names.length]; 2930 // reader 2931 synchronized (mPackages) { 2932 for (int i=names.length-1; i>=0; i--) { 2933 PackageSetting ps = mSettings.mPackages.get(names[i]); 2934 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2935 } 2936 } 2937 return out; 2938 } 2939 2940 @Override 2941 public String[] canonicalToCurrentPackageNames(String[] names) { 2942 String[] out = new String[names.length]; 2943 // reader 2944 synchronized (mPackages) { 2945 for (int i=names.length-1; i>=0; i--) { 2946 String cur = mSettings.mRenamedPackages.get(names[i]); 2947 out[i] = cur != null ? cur : names[i]; 2948 } 2949 } 2950 return out; 2951 } 2952 2953 @Override 2954 public int getPackageUid(String packageName, int flags, int userId) { 2955 if (!sUserManager.exists(userId)) return -1; 2956 flags = updateFlagsForPackage(flags, userId, packageName); 2957 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2958 2959 // reader 2960 synchronized (mPackages) { 2961 final PackageParser.Package p = mPackages.get(packageName); 2962 if (p != null && p.isMatch(flags)) { 2963 return UserHandle.getUid(userId, p.applicationInfo.uid); 2964 } 2965 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2966 final PackageSetting ps = mSettings.mPackages.get(packageName); 2967 if (ps != null && ps.isMatch(flags)) { 2968 return UserHandle.getUid(userId, ps.appId); 2969 } 2970 } 2971 } 2972 2973 return -1; 2974 } 2975 2976 @Override 2977 public int[] getPackageGids(String packageName, int flags, int userId) { 2978 if (!sUserManager.exists(userId)) return null; 2979 flags = updateFlagsForPackage(flags, userId, packageName); 2980 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2981 "getPackageGids"); 2982 2983 // reader 2984 synchronized (mPackages) { 2985 final PackageParser.Package p = mPackages.get(packageName); 2986 if (p != null && p.isMatch(flags)) { 2987 PackageSetting ps = (PackageSetting) p.mExtras; 2988 return ps.getPermissionsState().computeGids(userId); 2989 } 2990 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2991 final PackageSetting ps = mSettings.mPackages.get(packageName); 2992 if (ps != null && ps.isMatch(flags)) { 2993 return ps.getPermissionsState().computeGids(userId); 2994 } 2995 } 2996 } 2997 2998 return null; 2999 } 3000 3001 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3002 if (bp.perm != null) { 3003 return PackageParser.generatePermissionInfo(bp.perm, flags); 3004 } 3005 PermissionInfo pi = new PermissionInfo(); 3006 pi.name = bp.name; 3007 pi.packageName = bp.sourcePackage; 3008 pi.nonLocalizedLabel = bp.name; 3009 pi.protectionLevel = bp.protectionLevel; 3010 return pi; 3011 } 3012 3013 @Override 3014 public PermissionInfo getPermissionInfo(String name, int flags) { 3015 // reader 3016 synchronized (mPackages) { 3017 final BasePermission p = mSettings.mPermissions.get(name); 3018 if (p != null) { 3019 return generatePermissionInfo(p, flags); 3020 } 3021 return null; 3022 } 3023 } 3024 3025 @Override 3026 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 3027 // reader 3028 synchronized (mPackages) { 3029 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3030 for (BasePermission p : mSettings.mPermissions.values()) { 3031 if (group == null) { 3032 if (p.perm == null || p.perm.info.group == null) { 3033 out.add(generatePermissionInfo(p, flags)); 3034 } 3035 } else { 3036 if (p.perm != null && group.equals(p.perm.info.group)) { 3037 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3038 } 3039 } 3040 } 3041 3042 if (out.size() > 0) { 3043 return out; 3044 } 3045 return mPermissionGroups.containsKey(group) ? out : null; 3046 } 3047 } 3048 3049 @Override 3050 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3051 // reader 3052 synchronized (mPackages) { 3053 return PackageParser.generatePermissionGroupInfo( 3054 mPermissionGroups.get(name), flags); 3055 } 3056 } 3057 3058 @Override 3059 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3060 // reader 3061 synchronized (mPackages) { 3062 final int N = mPermissionGroups.size(); 3063 ArrayList<PermissionGroupInfo> out 3064 = new ArrayList<PermissionGroupInfo>(N); 3065 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3066 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3067 } 3068 return out; 3069 } 3070 } 3071 3072 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3073 int userId) { 3074 if (!sUserManager.exists(userId)) return null; 3075 PackageSetting ps = mSettings.mPackages.get(packageName); 3076 if (ps != null) { 3077 if (ps.pkg == null) { 3078 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 3079 flags, userId); 3080 if (pInfo != null) { 3081 return pInfo.applicationInfo; 3082 } 3083 return null; 3084 } 3085 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3086 ps.readUserState(userId), userId); 3087 } 3088 return null; 3089 } 3090 3091 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 3092 int userId) { 3093 if (!sUserManager.exists(userId)) return null; 3094 PackageSetting ps = mSettings.mPackages.get(packageName); 3095 if (ps != null) { 3096 PackageParser.Package pkg = ps.pkg; 3097 if (pkg == null) { 3098 if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) { 3099 return null; 3100 } 3101 // Only data remains, so we aren't worried about code paths 3102 pkg = new PackageParser.Package(packageName); 3103 pkg.applicationInfo.packageName = packageName; 3104 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 3105 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 3106 pkg.applicationInfo.uid = ps.appId; 3107 pkg.applicationInfo.initForUser(userId); 3108 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 3109 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 3110 } 3111 return generatePackageInfo(pkg, flags, userId); 3112 } 3113 return null; 3114 } 3115 3116 @Override 3117 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3118 if (!sUserManager.exists(userId)) return null; 3119 flags = updateFlagsForApplication(flags, userId, packageName); 3120 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 3121 // writer 3122 synchronized (mPackages) { 3123 PackageParser.Package p = mPackages.get(packageName); 3124 if (DEBUG_PACKAGE_INFO) Log.v( 3125 TAG, "getApplicationInfo " + packageName 3126 + ": " + p); 3127 if (p != null) { 3128 PackageSetting ps = mSettings.mPackages.get(packageName); 3129 if (ps == null) return null; 3130 // Note: isEnabledLP() does not apply here - always return info 3131 return PackageParser.generateApplicationInfo( 3132 p, flags, ps.readUserState(userId), userId); 3133 } 3134 if ("android".equals(packageName)||"system".equals(packageName)) { 3135 return mAndroidApplication; 3136 } 3137 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3138 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3139 } 3140 } 3141 return null; 3142 } 3143 3144 @Override 3145 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3146 final IPackageDataObserver observer) { 3147 mContext.enforceCallingOrSelfPermission( 3148 android.Manifest.permission.CLEAR_APP_CACHE, null); 3149 // Queue up an async operation since clearing cache may take a little while. 3150 mHandler.post(new Runnable() { 3151 public void run() { 3152 mHandler.removeCallbacks(this); 3153 boolean success = true; 3154 synchronized (mInstallLock) { 3155 try { 3156 mInstaller.freeCache(volumeUuid, freeStorageSize); 3157 } catch (InstallerException e) { 3158 Slog.w(TAG, "Couldn't clear application caches: " + e); 3159 success = false; 3160 } 3161 } 3162 if (observer != null) { 3163 try { 3164 observer.onRemoveCompleted(null, success); 3165 } catch (RemoteException e) { 3166 Slog.w(TAG, "RemoveException when invoking call back"); 3167 } 3168 } 3169 } 3170 }); 3171 } 3172 3173 @Override 3174 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3175 final IntentSender pi) { 3176 mContext.enforceCallingOrSelfPermission( 3177 android.Manifest.permission.CLEAR_APP_CACHE, null); 3178 // Queue up an async operation since clearing cache may take a little while. 3179 mHandler.post(new Runnable() { 3180 public void run() { 3181 mHandler.removeCallbacks(this); 3182 boolean success = true; 3183 synchronized (mInstallLock) { 3184 try { 3185 mInstaller.freeCache(volumeUuid, freeStorageSize); 3186 } catch (InstallerException e) { 3187 Slog.w(TAG, "Couldn't clear application caches: " + e); 3188 success = false; 3189 } 3190 } 3191 if(pi != null) { 3192 try { 3193 // Callback via pending intent 3194 int code = success ? 1 : 0; 3195 pi.sendIntent(null, code, null, 3196 null, null); 3197 } catch (SendIntentException e1) { 3198 Slog.i(TAG, "Failed to send pending intent"); 3199 } 3200 } 3201 } 3202 }); 3203 } 3204 3205 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3206 synchronized (mInstallLock) { 3207 try { 3208 mInstaller.freeCache(volumeUuid, freeStorageSize); 3209 } catch (InstallerException e) { 3210 throw new IOException("Failed to free enough space", e); 3211 } 3212 } 3213 } 3214 3215 /** 3216 * Return if the user key is currently unlocked. 3217 */ 3218 private boolean isUserKeyUnlocked(int userId) { 3219 if (StorageManager.isFileBasedEncryptionEnabled()) { 3220 final IMountService mount = IMountService.Stub 3221 .asInterface(ServiceManager.getService("mount")); 3222 if (mount == null) { 3223 Slog.w(TAG, "Early during boot, assuming locked"); 3224 return false; 3225 } 3226 final long token = Binder.clearCallingIdentity(); 3227 try { 3228 return mount.isUserKeyUnlocked(userId); 3229 } catch (RemoteException e) { 3230 throw e.rethrowAsRuntimeException(); 3231 } finally { 3232 Binder.restoreCallingIdentity(token); 3233 } 3234 } else { 3235 return true; 3236 } 3237 } 3238 3239 /** 3240 * Update given flags based on encryption status of current user. 3241 */ 3242 private int updateFlags(int flags, int userId) { 3243 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3244 | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) { 3245 // Caller expressed an explicit opinion about what encryption 3246 // aware/unaware components they want to see, so fall through and 3247 // give them what they want 3248 } else { 3249 // Caller expressed no opinion, so match based on user state 3250 if (isUserKeyUnlocked(userId)) { 3251 flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE; 3252 } else { 3253 flags |= PackageManager.MATCH_ENCRYPTION_AWARE; 3254 } 3255 } 3256 return flags; 3257 } 3258 3259 /** 3260 * Update given flags when being used to request {@link PackageInfo}. 3261 */ 3262 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3263 boolean triaged = true; 3264 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3265 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3266 // Caller is asking for component details, so they'd better be 3267 // asking for specific encryption matching behavior, or be triaged 3268 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3269 | PackageManager.MATCH_ENCRYPTION_AWARE 3270 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3271 triaged = false; 3272 } 3273 } 3274 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3275 | PackageManager.MATCH_SYSTEM_ONLY 3276 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3277 triaged = false; 3278 } 3279 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3280 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3281 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3282 } 3283 return updateFlags(flags, userId); 3284 } 3285 3286 /** 3287 * Update given flags when being used to request {@link ApplicationInfo}. 3288 */ 3289 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3290 return updateFlagsForPackage(flags, userId, cookie); 3291 } 3292 3293 /** 3294 * Update given flags when being used to request {@link ComponentInfo}. 3295 */ 3296 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3297 if (cookie instanceof Intent) { 3298 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3299 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3300 } 3301 } 3302 3303 boolean triaged = true; 3304 // Caller is asking for component details, so they'd better be 3305 // asking for specific encryption matching behavior, or be triaged 3306 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3307 | PackageManager.MATCH_ENCRYPTION_AWARE 3308 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3309 triaged = false; 3310 } 3311 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3312 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3313 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3314 } 3315 3316 return updateFlags(flags, userId); 3317 } 3318 3319 /** 3320 * Update given flags when being used to request {@link ResolveInfo}. 3321 */ 3322 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3323 // Safe mode means we shouldn't match any third-party components 3324 if (mSafeMode) { 3325 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3326 } 3327 3328 return updateFlagsForComponent(flags, userId, cookie); 3329 } 3330 3331 @Override 3332 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3333 if (!sUserManager.exists(userId)) return null; 3334 flags = updateFlagsForComponent(flags, userId, component); 3335 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 3336 synchronized (mPackages) { 3337 PackageParser.Activity a = mActivities.mActivities.get(component); 3338 3339 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3340 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3341 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3342 if (ps == null) return null; 3343 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3344 userId); 3345 } 3346 if (mResolveComponentName.equals(component)) { 3347 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3348 new PackageUserState(), userId); 3349 } 3350 } 3351 return null; 3352 } 3353 3354 @Override 3355 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3356 String resolvedType) { 3357 synchronized (mPackages) { 3358 if (component.equals(mResolveComponentName)) { 3359 // The resolver supports EVERYTHING! 3360 return true; 3361 } 3362 PackageParser.Activity a = mActivities.mActivities.get(component); 3363 if (a == null) { 3364 return false; 3365 } 3366 for (int i=0; i<a.intents.size(); i++) { 3367 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3368 intent.getData(), intent.getCategories(), TAG) >= 0) { 3369 return true; 3370 } 3371 } 3372 return false; 3373 } 3374 } 3375 3376 @Override 3377 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3378 if (!sUserManager.exists(userId)) return null; 3379 flags = updateFlagsForComponent(flags, userId, component); 3380 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3381 synchronized (mPackages) { 3382 PackageParser.Activity a = mReceivers.mActivities.get(component); 3383 if (DEBUG_PACKAGE_INFO) Log.v( 3384 TAG, "getReceiverInfo " + component + ": " + a); 3385 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3386 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3387 if (ps == null) return null; 3388 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3389 userId); 3390 } 3391 } 3392 return null; 3393 } 3394 3395 @Override 3396 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3397 if (!sUserManager.exists(userId)) return null; 3398 flags = updateFlagsForComponent(flags, userId, component); 3399 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3400 synchronized (mPackages) { 3401 PackageParser.Service s = mServices.mServices.get(component); 3402 if (DEBUG_PACKAGE_INFO) Log.v( 3403 TAG, "getServiceInfo " + component + ": " + s); 3404 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3405 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3406 if (ps == null) return null; 3407 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3408 userId); 3409 } 3410 } 3411 return null; 3412 } 3413 3414 @Override 3415 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3416 if (!sUserManager.exists(userId)) return null; 3417 flags = updateFlagsForComponent(flags, userId, component); 3418 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3419 synchronized (mPackages) { 3420 PackageParser.Provider p = mProviders.mProviders.get(component); 3421 if (DEBUG_PACKAGE_INFO) Log.v( 3422 TAG, "getProviderInfo " + component + ": " + p); 3423 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3424 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3425 if (ps == null) return null; 3426 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3427 userId); 3428 } 3429 } 3430 return null; 3431 } 3432 3433 @Override 3434 public String[] getSystemSharedLibraryNames() { 3435 Set<String> libSet; 3436 synchronized (mPackages) { 3437 libSet = mSharedLibraries.keySet(); 3438 int size = libSet.size(); 3439 if (size > 0) { 3440 String[] libs = new String[size]; 3441 libSet.toArray(libs); 3442 return libs; 3443 } 3444 } 3445 return null; 3446 } 3447 3448 @Override 3449 public @Nullable String getServicesSystemSharedLibraryPackageName() { 3450 synchronized (mPackages) { 3451 SharedLibraryEntry libraryEntry = mSharedLibraries.get( 3452 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 3453 if (libraryEntry != null) { 3454 return libraryEntry.apk; 3455 } 3456 } 3457 return null; 3458 } 3459 3460 @Override 3461 public FeatureInfo[] getSystemAvailableFeatures() { 3462 Collection<FeatureInfo> featSet; 3463 synchronized (mPackages) { 3464 featSet = mAvailableFeatures.values(); 3465 int size = featSet.size(); 3466 if (size > 0) { 3467 FeatureInfo[] features = new FeatureInfo[size+1]; 3468 featSet.toArray(features); 3469 FeatureInfo fi = new FeatureInfo(); 3470 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3471 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3472 features[size] = fi; 3473 return features; 3474 } 3475 } 3476 return null; 3477 } 3478 3479 @Override 3480 public boolean hasSystemFeature(String name, int version) { 3481 synchronized (mPackages) { 3482 final FeatureInfo feat = mAvailableFeatures.get(name); 3483 if (feat == null) { 3484 return false; 3485 } else { 3486 return feat.version >= version; 3487 } 3488 } 3489 } 3490 3491 @Override 3492 public int checkPermission(String permName, String pkgName, int userId) { 3493 if (!sUserManager.exists(userId)) { 3494 return PackageManager.PERMISSION_DENIED; 3495 } 3496 3497 synchronized (mPackages) { 3498 final PackageParser.Package p = mPackages.get(pkgName); 3499 if (p != null && p.mExtras != null) { 3500 final PackageSetting ps = (PackageSetting) p.mExtras; 3501 final PermissionsState permissionsState = ps.getPermissionsState(); 3502 if (permissionsState.hasPermission(permName, userId)) { 3503 return PackageManager.PERMISSION_GRANTED; 3504 } 3505 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3506 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3507 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3508 return PackageManager.PERMISSION_GRANTED; 3509 } 3510 } 3511 } 3512 3513 return PackageManager.PERMISSION_DENIED; 3514 } 3515 3516 @Override 3517 public int checkUidPermission(String permName, int uid) { 3518 final int userId = UserHandle.getUserId(uid); 3519 3520 if (!sUserManager.exists(userId)) { 3521 return PackageManager.PERMISSION_DENIED; 3522 } 3523 3524 synchronized (mPackages) { 3525 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3526 if (obj != null) { 3527 final SettingBase ps = (SettingBase) obj; 3528 final PermissionsState permissionsState = ps.getPermissionsState(); 3529 if (permissionsState.hasPermission(permName, userId)) { 3530 return PackageManager.PERMISSION_GRANTED; 3531 } 3532 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3533 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3534 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3535 return PackageManager.PERMISSION_GRANTED; 3536 } 3537 } else { 3538 ArraySet<String> perms = mSystemPermissions.get(uid); 3539 if (perms != null) { 3540 if (perms.contains(permName)) { 3541 return PackageManager.PERMISSION_GRANTED; 3542 } 3543 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3544 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3545 return PackageManager.PERMISSION_GRANTED; 3546 } 3547 } 3548 } 3549 } 3550 3551 return PackageManager.PERMISSION_DENIED; 3552 } 3553 3554 @Override 3555 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3556 if (UserHandle.getCallingUserId() != userId) { 3557 mContext.enforceCallingPermission( 3558 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3559 "isPermissionRevokedByPolicy for user " + userId); 3560 } 3561 3562 if (checkPermission(permission, packageName, userId) 3563 == PackageManager.PERMISSION_GRANTED) { 3564 return false; 3565 } 3566 3567 final long identity = Binder.clearCallingIdentity(); 3568 try { 3569 final int flags = getPermissionFlags(permission, packageName, userId); 3570 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3571 } finally { 3572 Binder.restoreCallingIdentity(identity); 3573 } 3574 } 3575 3576 @Override 3577 public String getPermissionControllerPackageName() { 3578 synchronized (mPackages) { 3579 return mRequiredInstallerPackage; 3580 } 3581 } 3582 3583 /** 3584 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3585 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3586 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3587 * @param message the message to log on security exception 3588 */ 3589 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3590 boolean checkShell, String message) { 3591 if (userId < 0) { 3592 throw new IllegalArgumentException("Invalid userId " + userId); 3593 } 3594 if (checkShell) { 3595 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3596 } 3597 if (userId == UserHandle.getUserId(callingUid)) return; 3598 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3599 if (requireFullPermission) { 3600 mContext.enforceCallingOrSelfPermission( 3601 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3602 } else { 3603 try { 3604 mContext.enforceCallingOrSelfPermission( 3605 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3606 } catch (SecurityException se) { 3607 mContext.enforceCallingOrSelfPermission( 3608 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3609 } 3610 } 3611 } 3612 } 3613 3614 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3615 if (callingUid == Process.SHELL_UID) { 3616 if (userHandle >= 0 3617 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3618 throw new SecurityException("Shell does not have permission to access user " 3619 + userHandle); 3620 } else if (userHandle < 0) { 3621 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3622 + Debug.getCallers(3)); 3623 } 3624 } 3625 } 3626 3627 private BasePermission findPermissionTreeLP(String permName) { 3628 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3629 if (permName.startsWith(bp.name) && 3630 permName.length() > bp.name.length() && 3631 permName.charAt(bp.name.length()) == '.') { 3632 return bp; 3633 } 3634 } 3635 return null; 3636 } 3637 3638 private BasePermission checkPermissionTreeLP(String permName) { 3639 if (permName != null) { 3640 BasePermission bp = findPermissionTreeLP(permName); 3641 if (bp != null) { 3642 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3643 return bp; 3644 } 3645 throw new SecurityException("Calling uid " 3646 + Binder.getCallingUid() 3647 + " is not allowed to add to permission tree " 3648 + bp.name + " owned by uid " + bp.uid); 3649 } 3650 } 3651 throw new SecurityException("No permission tree found for " + permName); 3652 } 3653 3654 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3655 if (s1 == null) { 3656 return s2 == null; 3657 } 3658 if (s2 == null) { 3659 return false; 3660 } 3661 if (s1.getClass() != s2.getClass()) { 3662 return false; 3663 } 3664 return s1.equals(s2); 3665 } 3666 3667 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3668 if (pi1.icon != pi2.icon) return false; 3669 if (pi1.logo != pi2.logo) return false; 3670 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3671 if (!compareStrings(pi1.name, pi2.name)) return false; 3672 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3673 // We'll take care of setting this one. 3674 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3675 // These are not currently stored in settings. 3676 //if (!compareStrings(pi1.group, pi2.group)) return false; 3677 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3678 //if (pi1.labelRes != pi2.labelRes) return false; 3679 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3680 return true; 3681 } 3682 3683 int permissionInfoFootprint(PermissionInfo info) { 3684 int size = info.name.length(); 3685 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3686 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3687 return size; 3688 } 3689 3690 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3691 int size = 0; 3692 for (BasePermission perm : mSettings.mPermissions.values()) { 3693 if (perm.uid == tree.uid) { 3694 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3695 } 3696 } 3697 return size; 3698 } 3699 3700 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3701 // We calculate the max size of permissions defined by this uid and throw 3702 // if that plus the size of 'info' would exceed our stated maximum. 3703 if (tree.uid != Process.SYSTEM_UID) { 3704 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3705 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3706 throw new SecurityException("Permission tree size cap exceeded"); 3707 } 3708 } 3709 } 3710 3711 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3712 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3713 throw new SecurityException("Label must be specified in permission"); 3714 } 3715 BasePermission tree = checkPermissionTreeLP(info.name); 3716 BasePermission bp = mSettings.mPermissions.get(info.name); 3717 boolean added = bp == null; 3718 boolean changed = true; 3719 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3720 if (added) { 3721 enforcePermissionCapLocked(info, tree); 3722 bp = new BasePermission(info.name, tree.sourcePackage, 3723 BasePermission.TYPE_DYNAMIC); 3724 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3725 throw new SecurityException( 3726 "Not allowed to modify non-dynamic permission " 3727 + info.name); 3728 } else { 3729 if (bp.protectionLevel == fixedLevel 3730 && bp.perm.owner.equals(tree.perm.owner) 3731 && bp.uid == tree.uid 3732 && comparePermissionInfos(bp.perm.info, info)) { 3733 changed = false; 3734 } 3735 } 3736 bp.protectionLevel = fixedLevel; 3737 info = new PermissionInfo(info); 3738 info.protectionLevel = fixedLevel; 3739 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3740 bp.perm.info.packageName = tree.perm.info.packageName; 3741 bp.uid = tree.uid; 3742 if (added) { 3743 mSettings.mPermissions.put(info.name, bp); 3744 } 3745 if (changed) { 3746 if (!async) { 3747 mSettings.writeLPr(); 3748 } else { 3749 scheduleWriteSettingsLocked(); 3750 } 3751 } 3752 return added; 3753 } 3754 3755 @Override 3756 public boolean addPermission(PermissionInfo info) { 3757 synchronized (mPackages) { 3758 return addPermissionLocked(info, false); 3759 } 3760 } 3761 3762 @Override 3763 public boolean addPermissionAsync(PermissionInfo info) { 3764 synchronized (mPackages) { 3765 return addPermissionLocked(info, true); 3766 } 3767 } 3768 3769 @Override 3770 public void removePermission(String name) { 3771 synchronized (mPackages) { 3772 checkPermissionTreeLP(name); 3773 BasePermission bp = mSettings.mPermissions.get(name); 3774 if (bp != null) { 3775 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3776 throw new SecurityException( 3777 "Not allowed to modify non-dynamic permission " 3778 + name); 3779 } 3780 mSettings.mPermissions.remove(name); 3781 mSettings.writeLPr(); 3782 } 3783 } 3784 } 3785 3786 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3787 BasePermission bp) { 3788 int index = pkg.requestedPermissions.indexOf(bp.name); 3789 if (index == -1) { 3790 throw new SecurityException("Package " + pkg.packageName 3791 + " has not requested permission " + bp.name); 3792 } 3793 if (!bp.isRuntime() && !bp.isDevelopment()) { 3794 throw new SecurityException("Permission " + bp.name 3795 + " is not a changeable permission type"); 3796 } 3797 } 3798 3799 @Override 3800 public void grantRuntimePermission(String packageName, String name, final int userId) { 3801 if (!sUserManager.exists(userId)) { 3802 Log.e(TAG, "No such user:" + userId); 3803 return; 3804 } 3805 3806 mContext.enforceCallingOrSelfPermission( 3807 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3808 "grantRuntimePermission"); 3809 3810 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3811 "grantRuntimePermission"); 3812 3813 final int uid; 3814 final SettingBase sb; 3815 3816 synchronized (mPackages) { 3817 final PackageParser.Package pkg = mPackages.get(packageName); 3818 if (pkg == null) { 3819 throw new IllegalArgumentException("Unknown package: " + packageName); 3820 } 3821 3822 final BasePermission bp = mSettings.mPermissions.get(name); 3823 if (bp == null) { 3824 throw new IllegalArgumentException("Unknown permission: " + name); 3825 } 3826 3827 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3828 3829 // If a permission review is required for legacy apps we represent 3830 // their permissions as always granted runtime ones since we need 3831 // to keep the review required permission flag per user while an 3832 // install permission's state is shared across all users. 3833 if (Build.PERMISSIONS_REVIEW_REQUIRED 3834 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3835 && bp.isRuntime()) { 3836 return; 3837 } 3838 3839 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3840 sb = (SettingBase) pkg.mExtras; 3841 if (sb == null) { 3842 throw new IllegalArgumentException("Unknown package: " + packageName); 3843 } 3844 3845 final PermissionsState permissionsState = sb.getPermissionsState(); 3846 3847 final int flags = permissionsState.getPermissionFlags(name, userId); 3848 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3849 throw new SecurityException("Cannot grant system fixed permission " 3850 + name + " for package " + packageName); 3851 } 3852 3853 if (bp.isDevelopment()) { 3854 // Development permissions must be handled specially, since they are not 3855 // normal runtime permissions. For now they apply to all users. 3856 if (permissionsState.grantInstallPermission(bp) != 3857 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3858 scheduleWriteSettingsLocked(); 3859 } 3860 return; 3861 } 3862 3863 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 3864 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 3865 return; 3866 } 3867 3868 final int result = permissionsState.grantRuntimePermission(bp, userId); 3869 switch (result) { 3870 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3871 return; 3872 } 3873 3874 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3875 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3876 mHandler.post(new Runnable() { 3877 @Override 3878 public void run() { 3879 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3880 } 3881 }); 3882 } 3883 break; 3884 } 3885 3886 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3887 3888 // Not critical if that is lost - app has to request again. 3889 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3890 } 3891 3892 // Only need to do this if user is initialized. Otherwise it's a new user 3893 // and there are no processes running as the user yet and there's no need 3894 // to make an expensive call to remount processes for the changed permissions. 3895 if (READ_EXTERNAL_STORAGE.equals(name) 3896 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3897 final long token = Binder.clearCallingIdentity(); 3898 try { 3899 if (sUserManager.isInitialized(userId)) { 3900 MountServiceInternal mountServiceInternal = LocalServices.getService( 3901 MountServiceInternal.class); 3902 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3903 } 3904 } finally { 3905 Binder.restoreCallingIdentity(token); 3906 } 3907 } 3908 } 3909 3910 @Override 3911 public void revokeRuntimePermission(String packageName, String name, int userId) { 3912 if (!sUserManager.exists(userId)) { 3913 Log.e(TAG, "No such user:" + userId); 3914 return; 3915 } 3916 3917 mContext.enforceCallingOrSelfPermission( 3918 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3919 "revokeRuntimePermission"); 3920 3921 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3922 "revokeRuntimePermission"); 3923 3924 final int appId; 3925 3926 synchronized (mPackages) { 3927 final PackageParser.Package pkg = mPackages.get(packageName); 3928 if (pkg == null) { 3929 throw new IllegalArgumentException("Unknown package: " + packageName); 3930 } 3931 3932 final BasePermission bp = mSettings.mPermissions.get(name); 3933 if (bp == null) { 3934 throw new IllegalArgumentException("Unknown permission: " + name); 3935 } 3936 3937 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3938 3939 // If a permission review is required for legacy apps we represent 3940 // their permissions as always granted runtime ones since we need 3941 // to keep the review required permission flag per user while an 3942 // install permission's state is shared across all users. 3943 if (Build.PERMISSIONS_REVIEW_REQUIRED 3944 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3945 && bp.isRuntime()) { 3946 return; 3947 } 3948 3949 SettingBase sb = (SettingBase) pkg.mExtras; 3950 if (sb == null) { 3951 throw new IllegalArgumentException("Unknown package: " + packageName); 3952 } 3953 3954 final PermissionsState permissionsState = sb.getPermissionsState(); 3955 3956 final int flags = permissionsState.getPermissionFlags(name, userId); 3957 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3958 throw new SecurityException("Cannot revoke system fixed permission " 3959 + name + " for package " + packageName); 3960 } 3961 3962 if (bp.isDevelopment()) { 3963 // Development permissions must be handled specially, since they are not 3964 // normal runtime permissions. For now they apply to all users. 3965 if (permissionsState.revokeInstallPermission(bp) != 3966 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3967 scheduleWriteSettingsLocked(); 3968 } 3969 return; 3970 } 3971 3972 if (permissionsState.revokeRuntimePermission(bp, userId) == 3973 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3974 return; 3975 } 3976 3977 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3978 3979 // Critical, after this call app should never have the permission. 3980 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3981 3982 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3983 } 3984 3985 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3986 } 3987 3988 @Override 3989 public void resetRuntimePermissions() { 3990 mContext.enforceCallingOrSelfPermission( 3991 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3992 "revokeRuntimePermission"); 3993 3994 int callingUid = Binder.getCallingUid(); 3995 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3996 mContext.enforceCallingOrSelfPermission( 3997 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3998 "resetRuntimePermissions"); 3999 } 4000 4001 synchronized (mPackages) { 4002 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4003 for (int userId : UserManagerService.getInstance().getUserIds()) { 4004 final int packageCount = mPackages.size(); 4005 for (int i = 0; i < packageCount; i++) { 4006 PackageParser.Package pkg = mPackages.valueAt(i); 4007 if (!(pkg.mExtras instanceof PackageSetting)) { 4008 continue; 4009 } 4010 PackageSetting ps = (PackageSetting) pkg.mExtras; 4011 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4012 } 4013 } 4014 } 4015 } 4016 4017 @Override 4018 public int getPermissionFlags(String name, String packageName, int userId) { 4019 if (!sUserManager.exists(userId)) { 4020 return 0; 4021 } 4022 4023 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4024 4025 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 4026 "getPermissionFlags"); 4027 4028 synchronized (mPackages) { 4029 final PackageParser.Package pkg = mPackages.get(packageName); 4030 if (pkg == null) { 4031 throw new IllegalArgumentException("Unknown package: " + packageName); 4032 } 4033 4034 final BasePermission bp = mSettings.mPermissions.get(name); 4035 if (bp == null) { 4036 throw new IllegalArgumentException("Unknown permission: " + name); 4037 } 4038 4039 SettingBase sb = (SettingBase) pkg.mExtras; 4040 if (sb == null) { 4041 throw new IllegalArgumentException("Unknown package: " + packageName); 4042 } 4043 4044 PermissionsState permissionsState = sb.getPermissionsState(); 4045 return permissionsState.getPermissionFlags(name, userId); 4046 } 4047 } 4048 4049 @Override 4050 public void updatePermissionFlags(String name, String packageName, int flagMask, 4051 int flagValues, int userId) { 4052 if (!sUserManager.exists(userId)) { 4053 return; 4054 } 4055 4056 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4057 4058 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 4059 "updatePermissionFlags"); 4060 4061 // Only the system can change these flags and nothing else. 4062 if (getCallingUid() != Process.SYSTEM_UID) { 4063 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4064 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4065 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4066 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4067 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4068 } 4069 4070 synchronized (mPackages) { 4071 final PackageParser.Package pkg = mPackages.get(packageName); 4072 if (pkg == null) { 4073 throw new IllegalArgumentException("Unknown package: " + packageName); 4074 } 4075 4076 final BasePermission bp = mSettings.mPermissions.get(name); 4077 if (bp == null) { 4078 throw new IllegalArgumentException("Unknown permission: " + name); 4079 } 4080 4081 SettingBase sb = (SettingBase) pkg.mExtras; 4082 if (sb == null) { 4083 throw new IllegalArgumentException("Unknown package: " + packageName); 4084 } 4085 4086 PermissionsState permissionsState = sb.getPermissionsState(); 4087 4088 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4089 4090 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4091 // Install and runtime permissions are stored in different places, 4092 // so figure out what permission changed and persist the change. 4093 if (permissionsState.getInstallPermissionState(name) != null) { 4094 scheduleWriteSettingsLocked(); 4095 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4096 || hadState) { 4097 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4098 } 4099 } 4100 } 4101 } 4102 4103 /** 4104 * Update the permission flags for all packages and runtime permissions of a user in order 4105 * to allow device or profile owner to remove POLICY_FIXED. 4106 */ 4107 @Override 4108 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4109 if (!sUserManager.exists(userId)) { 4110 return; 4111 } 4112 4113 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4114 4115 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 4116 "updatePermissionFlagsForAllApps"); 4117 4118 // Only the system can change system fixed flags. 4119 if (getCallingUid() != Process.SYSTEM_UID) { 4120 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4121 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4122 } 4123 4124 synchronized (mPackages) { 4125 boolean changed = false; 4126 final int packageCount = mPackages.size(); 4127 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4128 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4129 SettingBase sb = (SettingBase) pkg.mExtras; 4130 if (sb == null) { 4131 continue; 4132 } 4133 PermissionsState permissionsState = sb.getPermissionsState(); 4134 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4135 userId, flagMask, flagValues); 4136 } 4137 if (changed) { 4138 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4139 } 4140 } 4141 } 4142 4143 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4144 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4145 != PackageManager.PERMISSION_GRANTED 4146 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4147 != PackageManager.PERMISSION_GRANTED) { 4148 throw new SecurityException(message + " requires " 4149 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4150 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4151 } 4152 } 4153 4154 @Override 4155 public boolean shouldShowRequestPermissionRationale(String permissionName, 4156 String packageName, int userId) { 4157 if (UserHandle.getCallingUserId() != userId) { 4158 mContext.enforceCallingPermission( 4159 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4160 "canShowRequestPermissionRationale for user " + userId); 4161 } 4162 4163 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4164 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4165 return false; 4166 } 4167 4168 if (checkPermission(permissionName, packageName, userId) 4169 == PackageManager.PERMISSION_GRANTED) { 4170 return false; 4171 } 4172 4173 final int flags; 4174 4175 final long identity = Binder.clearCallingIdentity(); 4176 try { 4177 flags = getPermissionFlags(permissionName, 4178 packageName, userId); 4179 } finally { 4180 Binder.restoreCallingIdentity(identity); 4181 } 4182 4183 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4184 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4185 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4186 4187 if ((flags & fixedFlags) != 0) { 4188 return false; 4189 } 4190 4191 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4192 } 4193 4194 @Override 4195 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4196 mContext.enforceCallingOrSelfPermission( 4197 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4198 "addOnPermissionsChangeListener"); 4199 4200 synchronized (mPackages) { 4201 mOnPermissionChangeListeners.addListenerLocked(listener); 4202 } 4203 } 4204 4205 @Override 4206 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4207 synchronized (mPackages) { 4208 mOnPermissionChangeListeners.removeListenerLocked(listener); 4209 } 4210 } 4211 4212 @Override 4213 public boolean isProtectedBroadcast(String actionName) { 4214 synchronized (mPackages) { 4215 if (mProtectedBroadcasts.contains(actionName)) { 4216 return true; 4217 } else if (actionName != null) { 4218 // TODO: remove these terrible hacks 4219 if (actionName.startsWith("android.net.netmon.lingerExpired") 4220 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4221 || actionName.startsWith("com.android.internal.telephony.data-reconnect")) { 4222 return true; 4223 } 4224 } 4225 } 4226 return false; 4227 } 4228 4229 @Override 4230 public int checkSignatures(String pkg1, String pkg2) { 4231 synchronized (mPackages) { 4232 final PackageParser.Package p1 = mPackages.get(pkg1); 4233 final PackageParser.Package p2 = mPackages.get(pkg2); 4234 if (p1 == null || p1.mExtras == null 4235 || p2 == null || p2.mExtras == null) { 4236 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4237 } 4238 return compareSignatures(p1.mSignatures, p2.mSignatures); 4239 } 4240 } 4241 4242 @Override 4243 public int checkUidSignatures(int uid1, int uid2) { 4244 // Map to base uids. 4245 uid1 = UserHandle.getAppId(uid1); 4246 uid2 = UserHandle.getAppId(uid2); 4247 // reader 4248 synchronized (mPackages) { 4249 Signature[] s1; 4250 Signature[] s2; 4251 Object obj = mSettings.getUserIdLPr(uid1); 4252 if (obj != null) { 4253 if (obj instanceof SharedUserSetting) { 4254 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4255 } else if (obj instanceof PackageSetting) { 4256 s1 = ((PackageSetting)obj).signatures.mSignatures; 4257 } else { 4258 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4259 } 4260 } else { 4261 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4262 } 4263 obj = mSettings.getUserIdLPr(uid2); 4264 if (obj != null) { 4265 if (obj instanceof SharedUserSetting) { 4266 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4267 } else if (obj instanceof PackageSetting) { 4268 s2 = ((PackageSetting)obj).signatures.mSignatures; 4269 } else { 4270 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4271 } 4272 } else { 4273 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4274 } 4275 return compareSignatures(s1, s2); 4276 } 4277 } 4278 4279 private void killUid(int appId, int userId, String reason) { 4280 final long identity = Binder.clearCallingIdentity(); 4281 try { 4282 IActivityManager am = ActivityManagerNative.getDefault(); 4283 if (am != null) { 4284 try { 4285 am.killUid(appId, userId, reason); 4286 } catch (RemoteException e) { 4287 /* ignore - same process */ 4288 } 4289 } 4290 } finally { 4291 Binder.restoreCallingIdentity(identity); 4292 } 4293 } 4294 4295 /** 4296 * Compares two sets of signatures. Returns: 4297 * <br /> 4298 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4299 * <br /> 4300 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4301 * <br /> 4302 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4303 * <br /> 4304 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4305 * <br /> 4306 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4307 */ 4308 static int compareSignatures(Signature[] s1, Signature[] s2) { 4309 if (s1 == null) { 4310 return s2 == null 4311 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4312 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4313 } 4314 4315 if (s2 == null) { 4316 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4317 } 4318 4319 if (s1.length != s2.length) { 4320 return PackageManager.SIGNATURE_NO_MATCH; 4321 } 4322 4323 // Since both signature sets are of size 1, we can compare without HashSets. 4324 if (s1.length == 1) { 4325 return s1[0].equals(s2[0]) ? 4326 PackageManager.SIGNATURE_MATCH : 4327 PackageManager.SIGNATURE_NO_MATCH; 4328 } 4329 4330 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4331 for (Signature sig : s1) { 4332 set1.add(sig); 4333 } 4334 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4335 for (Signature sig : s2) { 4336 set2.add(sig); 4337 } 4338 // Make sure s2 contains all signatures in s1. 4339 if (set1.equals(set2)) { 4340 return PackageManager.SIGNATURE_MATCH; 4341 } 4342 return PackageManager.SIGNATURE_NO_MATCH; 4343 } 4344 4345 /** 4346 * If the database version for this type of package (internal storage or 4347 * external storage) is less than the version where package signatures 4348 * were updated, return true. 4349 */ 4350 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4351 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4352 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4353 } 4354 4355 /** 4356 * Used for backward compatibility to make sure any packages with 4357 * certificate chains get upgraded to the new style. {@code existingSigs} 4358 * will be in the old format (since they were stored on disk from before the 4359 * system upgrade) and {@code scannedSigs} will be in the newer format. 4360 */ 4361 private int compareSignaturesCompat(PackageSignatures existingSigs, 4362 PackageParser.Package scannedPkg) { 4363 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4364 return PackageManager.SIGNATURE_NO_MATCH; 4365 } 4366 4367 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4368 for (Signature sig : existingSigs.mSignatures) { 4369 existingSet.add(sig); 4370 } 4371 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4372 for (Signature sig : scannedPkg.mSignatures) { 4373 try { 4374 Signature[] chainSignatures = sig.getChainSignatures(); 4375 for (Signature chainSig : chainSignatures) { 4376 scannedCompatSet.add(chainSig); 4377 } 4378 } catch (CertificateEncodingException e) { 4379 scannedCompatSet.add(sig); 4380 } 4381 } 4382 /* 4383 * Make sure the expanded scanned set contains all signatures in the 4384 * existing one. 4385 */ 4386 if (scannedCompatSet.equals(existingSet)) { 4387 // Migrate the old signatures to the new scheme. 4388 existingSigs.assignSignatures(scannedPkg.mSignatures); 4389 // The new KeySets will be re-added later in the scanning process. 4390 synchronized (mPackages) { 4391 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4392 } 4393 return PackageManager.SIGNATURE_MATCH; 4394 } 4395 return PackageManager.SIGNATURE_NO_MATCH; 4396 } 4397 4398 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4399 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4400 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4401 } 4402 4403 private int compareSignaturesRecover(PackageSignatures existingSigs, 4404 PackageParser.Package scannedPkg) { 4405 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4406 return PackageManager.SIGNATURE_NO_MATCH; 4407 } 4408 4409 String msg = null; 4410 try { 4411 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4412 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4413 + scannedPkg.packageName); 4414 return PackageManager.SIGNATURE_MATCH; 4415 } 4416 } catch (CertificateException e) { 4417 msg = e.getMessage(); 4418 } 4419 4420 logCriticalInfo(Log.INFO, 4421 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4422 return PackageManager.SIGNATURE_NO_MATCH; 4423 } 4424 4425 @Override 4426 public String[] getPackagesForUid(int uid) { 4427 uid = UserHandle.getAppId(uid); 4428 // reader 4429 synchronized (mPackages) { 4430 Object obj = mSettings.getUserIdLPr(uid); 4431 if (obj instanceof SharedUserSetting) { 4432 final SharedUserSetting sus = (SharedUserSetting) obj; 4433 final int N = sus.packages.size(); 4434 final String[] res = new String[N]; 4435 final Iterator<PackageSetting> it = sus.packages.iterator(); 4436 int i = 0; 4437 while (it.hasNext()) { 4438 res[i++] = it.next().name; 4439 } 4440 return res; 4441 } else if (obj instanceof PackageSetting) { 4442 final PackageSetting ps = (PackageSetting) obj; 4443 return new String[] { ps.name }; 4444 } 4445 } 4446 return null; 4447 } 4448 4449 @Override 4450 public String getNameForUid(int uid) { 4451 // reader 4452 synchronized (mPackages) { 4453 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4454 if (obj instanceof SharedUserSetting) { 4455 final SharedUserSetting sus = (SharedUserSetting) obj; 4456 return sus.name + ":" + sus.userId; 4457 } else if (obj instanceof PackageSetting) { 4458 final PackageSetting ps = (PackageSetting) obj; 4459 return ps.name; 4460 } 4461 } 4462 return null; 4463 } 4464 4465 @Override 4466 public int getUidForSharedUser(String sharedUserName) { 4467 if(sharedUserName == null) { 4468 return -1; 4469 } 4470 // reader 4471 synchronized (mPackages) { 4472 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4473 if (suid == null) { 4474 return -1; 4475 } 4476 return suid.userId; 4477 } 4478 } 4479 4480 @Override 4481 public int getFlagsForUid(int uid) { 4482 synchronized (mPackages) { 4483 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4484 if (obj instanceof SharedUserSetting) { 4485 final SharedUserSetting sus = (SharedUserSetting) obj; 4486 return sus.pkgFlags; 4487 } else if (obj instanceof PackageSetting) { 4488 final PackageSetting ps = (PackageSetting) obj; 4489 return ps.pkgFlags; 4490 } 4491 } 4492 return 0; 4493 } 4494 4495 @Override 4496 public int getPrivateFlagsForUid(int uid) { 4497 synchronized (mPackages) { 4498 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4499 if (obj instanceof SharedUserSetting) { 4500 final SharedUserSetting sus = (SharedUserSetting) obj; 4501 return sus.pkgPrivateFlags; 4502 } else if (obj instanceof PackageSetting) { 4503 final PackageSetting ps = (PackageSetting) obj; 4504 return ps.pkgPrivateFlags; 4505 } 4506 } 4507 return 0; 4508 } 4509 4510 @Override 4511 public boolean isUidPrivileged(int uid) { 4512 uid = UserHandle.getAppId(uid); 4513 // reader 4514 synchronized (mPackages) { 4515 Object obj = mSettings.getUserIdLPr(uid); 4516 if (obj instanceof SharedUserSetting) { 4517 final SharedUserSetting sus = (SharedUserSetting) obj; 4518 final Iterator<PackageSetting> it = sus.packages.iterator(); 4519 while (it.hasNext()) { 4520 if (it.next().isPrivileged()) { 4521 return true; 4522 } 4523 } 4524 } else if (obj instanceof PackageSetting) { 4525 final PackageSetting ps = (PackageSetting) obj; 4526 return ps.isPrivileged(); 4527 } 4528 } 4529 return false; 4530 } 4531 4532 @Override 4533 public String[] getAppOpPermissionPackages(String permissionName) { 4534 synchronized (mPackages) { 4535 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4536 if (pkgs == null) { 4537 return null; 4538 } 4539 return pkgs.toArray(new String[pkgs.size()]); 4540 } 4541 } 4542 4543 @Override 4544 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4545 int flags, int userId) { 4546 if (!sUserManager.exists(userId)) return null; 4547 flags = updateFlagsForResolve(flags, userId, intent); 4548 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4549 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4550 final ResolveInfo bestChoice = 4551 chooseBestActivity(intent, resolvedType, flags, query, userId); 4552 4553 if (isEphemeralAllowed(intent, query, userId)) { 4554 final EphemeralResolveInfo ai = 4555 getEphemeralResolveInfo(intent, resolvedType, userId); 4556 if (ai != null) { 4557 if (DEBUG_EPHEMERAL) { 4558 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4559 } 4560 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4561 bestChoice.ephemeralResolveInfo = ai; 4562 } 4563 } 4564 return bestChoice; 4565 } 4566 4567 @Override 4568 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4569 IntentFilter filter, int match, ComponentName activity) { 4570 final int userId = UserHandle.getCallingUserId(); 4571 if (DEBUG_PREFERRED) { 4572 Log.v(TAG, "setLastChosenActivity intent=" + intent 4573 + " resolvedType=" + resolvedType 4574 + " flags=" + flags 4575 + " filter=" + filter 4576 + " match=" + match 4577 + " activity=" + activity); 4578 filter.dump(new PrintStreamPrinter(System.out), " "); 4579 } 4580 intent.setComponent(null); 4581 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4582 // Find any earlier preferred or last chosen entries and nuke them 4583 findPreferredActivity(intent, resolvedType, 4584 flags, query, 0, false, true, false, userId); 4585 // Add the new activity as the last chosen for this filter 4586 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4587 "Setting last chosen"); 4588 } 4589 4590 @Override 4591 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4592 final int userId = UserHandle.getCallingUserId(); 4593 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4594 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4595 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4596 false, false, false, userId); 4597 } 4598 4599 4600 private boolean isEphemeralAllowed( 4601 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4602 // Short circuit and return early if possible. 4603 if (DISABLE_EPHEMERAL_APPS) { 4604 return false; 4605 } 4606 final int callingUser = UserHandle.getCallingUserId(); 4607 if (callingUser != UserHandle.USER_SYSTEM) { 4608 return false; 4609 } 4610 if (mEphemeralResolverConnection == null) { 4611 return false; 4612 } 4613 if (intent.getComponent() != null) { 4614 return false; 4615 } 4616 if (intent.getPackage() != null) { 4617 return false; 4618 } 4619 final boolean isWebUri = hasWebURI(intent); 4620 if (!isWebUri) { 4621 return false; 4622 } 4623 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4624 synchronized (mPackages) { 4625 final int count = resolvedActivites.size(); 4626 for (int n = 0; n < count; n++) { 4627 ResolveInfo info = resolvedActivites.get(n); 4628 String packageName = info.activityInfo.packageName; 4629 PackageSetting ps = mSettings.mPackages.get(packageName); 4630 if (ps != null) { 4631 // Try to get the status from User settings first 4632 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4633 int status = (int) (packedStatus >> 32); 4634 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4635 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4636 if (DEBUG_EPHEMERAL) { 4637 Slog.v(TAG, "DENY ephemeral apps;" 4638 + " pkg: " + packageName + ", status: " + status); 4639 } 4640 return false; 4641 } 4642 } 4643 } 4644 } 4645 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4646 return true; 4647 } 4648 4649 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4650 int userId) { 4651 MessageDigest digest = null; 4652 try { 4653 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4654 } catch (NoSuchAlgorithmException e) { 4655 // If we can't create a digest, ignore ephemeral apps. 4656 return null; 4657 } 4658 4659 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4660 final byte[] digestBytes = digest.digest(hostBytes); 4661 int shaPrefix = 4662 digestBytes[0] << 24 4663 | digestBytes[1] << 16 4664 | digestBytes[2] << 8 4665 | digestBytes[3] << 0; 4666 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4667 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4668 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4669 // No hash prefix match; there are no ephemeral apps for this domain. 4670 return null; 4671 } 4672 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4673 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4674 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4675 continue; 4676 } 4677 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4678 // No filters; this should never happen. 4679 if (filters.isEmpty()) { 4680 continue; 4681 } 4682 // We have a domain match; resolve the filters to see if anything matches. 4683 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4684 for (int j = filters.size() - 1; j >= 0; --j) { 4685 final EphemeralResolveIntentInfo intentInfo = 4686 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4687 ephemeralResolver.addFilter(intentInfo); 4688 } 4689 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4690 intent, resolvedType, false /*defaultOnly*/, userId); 4691 if (!matchedResolveInfoList.isEmpty()) { 4692 return matchedResolveInfoList.get(0); 4693 } 4694 } 4695 // Hash or filter mis-match; no ephemeral apps for this domain. 4696 return null; 4697 } 4698 4699 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4700 int flags, List<ResolveInfo> query, int userId) { 4701 if (query != null) { 4702 final int N = query.size(); 4703 if (N == 1) { 4704 return query.get(0); 4705 } else if (N > 1) { 4706 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4707 // If there is more than one activity with the same priority, 4708 // then let the user decide between them. 4709 ResolveInfo r0 = query.get(0); 4710 ResolveInfo r1 = query.get(1); 4711 if (DEBUG_INTENT_MATCHING || debug) { 4712 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4713 + r1.activityInfo.name + "=" + r1.priority); 4714 } 4715 // If the first activity has a higher priority, or a different 4716 // default, then it is always desirable to pick it. 4717 if (r0.priority != r1.priority 4718 || r0.preferredOrder != r1.preferredOrder 4719 || r0.isDefault != r1.isDefault) { 4720 return query.get(0); 4721 } 4722 // If we have saved a preference for a preferred activity for 4723 // this Intent, use that. 4724 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4725 flags, query, r0.priority, true, false, debug, userId); 4726 if (ri != null) { 4727 return ri; 4728 } 4729 ri = new ResolveInfo(mResolveInfo); 4730 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4731 ri.activityInfo.applicationInfo = new ApplicationInfo( 4732 ri.activityInfo.applicationInfo); 4733 if (userId != 0) { 4734 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4735 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4736 } 4737 // Make sure that the resolver is displayable in car mode 4738 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4739 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4740 return ri; 4741 } 4742 } 4743 return null; 4744 } 4745 4746 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4747 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4748 final int N = query.size(); 4749 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4750 .get(userId); 4751 // Get the list of persistent preferred activities that handle the intent 4752 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4753 List<PersistentPreferredActivity> pprefs = ppir != null 4754 ? ppir.queryIntent(intent, resolvedType, 4755 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4756 : null; 4757 if (pprefs != null && pprefs.size() > 0) { 4758 final int M = pprefs.size(); 4759 for (int i=0; i<M; i++) { 4760 final PersistentPreferredActivity ppa = pprefs.get(i); 4761 if (DEBUG_PREFERRED || debug) { 4762 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4763 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4764 + "\n component=" + ppa.mComponent); 4765 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4766 } 4767 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4768 flags | MATCH_DISABLED_COMPONENTS, userId); 4769 if (DEBUG_PREFERRED || debug) { 4770 Slog.v(TAG, "Found persistent preferred activity:"); 4771 if (ai != null) { 4772 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4773 } else { 4774 Slog.v(TAG, " null"); 4775 } 4776 } 4777 if (ai == null) { 4778 // This previously registered persistent preferred activity 4779 // component is no longer known. Ignore it and do NOT remove it. 4780 continue; 4781 } 4782 for (int j=0; j<N; j++) { 4783 final ResolveInfo ri = query.get(j); 4784 if (!ri.activityInfo.applicationInfo.packageName 4785 .equals(ai.applicationInfo.packageName)) { 4786 continue; 4787 } 4788 if (!ri.activityInfo.name.equals(ai.name)) { 4789 continue; 4790 } 4791 // Found a persistent preference that can handle the intent. 4792 if (DEBUG_PREFERRED || debug) { 4793 Slog.v(TAG, "Returning persistent preferred activity: " + 4794 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4795 } 4796 return ri; 4797 } 4798 } 4799 } 4800 return null; 4801 } 4802 4803 // TODO: handle preferred activities missing while user has amnesia 4804 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4805 List<ResolveInfo> query, int priority, boolean always, 4806 boolean removeMatches, boolean debug, int userId) { 4807 if (!sUserManager.exists(userId)) return null; 4808 flags = updateFlagsForResolve(flags, userId, intent); 4809 // writer 4810 synchronized (mPackages) { 4811 if (intent.getSelector() != null) { 4812 intent = intent.getSelector(); 4813 } 4814 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4815 4816 // Try to find a matching persistent preferred activity. 4817 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4818 debug, userId); 4819 4820 // If a persistent preferred activity matched, use it. 4821 if (pri != null) { 4822 return pri; 4823 } 4824 4825 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4826 // Get the list of preferred activities that handle the intent 4827 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4828 List<PreferredActivity> prefs = pir != null 4829 ? pir.queryIntent(intent, resolvedType, 4830 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4831 : null; 4832 if (prefs != null && prefs.size() > 0) { 4833 boolean changed = false; 4834 try { 4835 // First figure out how good the original match set is. 4836 // We will only allow preferred activities that came 4837 // from the same match quality. 4838 int match = 0; 4839 4840 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4841 4842 final int N = query.size(); 4843 for (int j=0; j<N; j++) { 4844 final ResolveInfo ri = query.get(j); 4845 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4846 + ": 0x" + Integer.toHexString(match)); 4847 if (ri.match > match) { 4848 match = ri.match; 4849 } 4850 } 4851 4852 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4853 + Integer.toHexString(match)); 4854 4855 match &= IntentFilter.MATCH_CATEGORY_MASK; 4856 final int M = prefs.size(); 4857 for (int i=0; i<M; i++) { 4858 final PreferredActivity pa = prefs.get(i); 4859 if (DEBUG_PREFERRED || debug) { 4860 Slog.v(TAG, "Checking PreferredActivity ds=" 4861 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4862 + "\n component=" + pa.mPref.mComponent); 4863 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4864 } 4865 if (pa.mPref.mMatch != match) { 4866 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4867 + Integer.toHexString(pa.mPref.mMatch)); 4868 continue; 4869 } 4870 // If it's not an "always" type preferred activity and that's what we're 4871 // looking for, skip it. 4872 if (always && !pa.mPref.mAlways) { 4873 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4874 continue; 4875 } 4876 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4877 flags | MATCH_DISABLED_COMPONENTS, userId); 4878 if (DEBUG_PREFERRED || debug) { 4879 Slog.v(TAG, "Found preferred activity:"); 4880 if (ai != null) { 4881 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4882 } else { 4883 Slog.v(TAG, " null"); 4884 } 4885 } 4886 if (ai == null) { 4887 // This previously registered preferred activity 4888 // component is no longer known. Most likely an update 4889 // to the app was installed and in the new version this 4890 // component no longer exists. Clean it up by removing 4891 // it from the preferred activities list, and skip it. 4892 Slog.w(TAG, "Removing dangling preferred activity: " 4893 + pa.mPref.mComponent); 4894 pir.removeFilter(pa); 4895 changed = true; 4896 continue; 4897 } 4898 for (int j=0; j<N; j++) { 4899 final ResolveInfo ri = query.get(j); 4900 if (!ri.activityInfo.applicationInfo.packageName 4901 .equals(ai.applicationInfo.packageName)) { 4902 continue; 4903 } 4904 if (!ri.activityInfo.name.equals(ai.name)) { 4905 continue; 4906 } 4907 4908 if (removeMatches) { 4909 pir.removeFilter(pa); 4910 changed = true; 4911 if (DEBUG_PREFERRED) { 4912 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4913 } 4914 break; 4915 } 4916 4917 // Okay we found a previously set preferred or last chosen app. 4918 // If the result set is different from when this 4919 // was created, we need to clear it and re-ask the 4920 // user their preference, if we're looking for an "always" type entry. 4921 if (always && !pa.mPref.sameSet(query)) { 4922 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4923 + intent + " type " + resolvedType); 4924 if (DEBUG_PREFERRED) { 4925 Slog.v(TAG, "Removing preferred activity since set changed " 4926 + pa.mPref.mComponent); 4927 } 4928 pir.removeFilter(pa); 4929 // Re-add the filter as a "last chosen" entry (!always) 4930 PreferredActivity lastChosen = new PreferredActivity( 4931 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4932 pir.addFilter(lastChosen); 4933 changed = true; 4934 return null; 4935 } 4936 4937 // Yay! Either the set matched or we're looking for the last chosen 4938 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4939 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4940 return ri; 4941 } 4942 } 4943 } finally { 4944 if (changed) { 4945 if (DEBUG_PREFERRED) { 4946 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4947 } 4948 scheduleWritePackageRestrictionsLocked(userId); 4949 } 4950 } 4951 } 4952 } 4953 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4954 return null; 4955 } 4956 4957 /* 4958 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4959 */ 4960 @Override 4961 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4962 int targetUserId) { 4963 mContext.enforceCallingOrSelfPermission( 4964 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4965 List<CrossProfileIntentFilter> matches = 4966 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4967 if (matches != null) { 4968 int size = matches.size(); 4969 for (int i = 0; i < size; i++) { 4970 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4971 } 4972 } 4973 if (hasWebURI(intent)) { 4974 // cross-profile app linking works only towards the parent. 4975 final UserInfo parent = getProfileParent(sourceUserId); 4976 synchronized(mPackages) { 4977 int flags = updateFlagsForResolve(0, parent.id, intent); 4978 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4979 intent, resolvedType, flags, sourceUserId, parent.id); 4980 return xpDomainInfo != null; 4981 } 4982 } 4983 return false; 4984 } 4985 4986 private UserInfo getProfileParent(int userId) { 4987 final long identity = Binder.clearCallingIdentity(); 4988 try { 4989 return sUserManager.getProfileParent(userId); 4990 } finally { 4991 Binder.restoreCallingIdentity(identity); 4992 } 4993 } 4994 4995 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4996 String resolvedType, int userId) { 4997 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4998 if (resolver != null) { 4999 return resolver.queryIntent(intent, resolvedType, false, userId); 5000 } 5001 return null; 5002 } 5003 5004 @Override 5005 public List<ResolveInfo> queryIntentActivities(Intent intent, 5006 String resolvedType, int flags, int userId) { 5007 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5008 flags = updateFlagsForResolve(flags, userId, intent); 5009 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 5010 ComponentName comp = intent.getComponent(); 5011 if (comp == null) { 5012 if (intent.getSelector() != null) { 5013 intent = intent.getSelector(); 5014 comp = intent.getComponent(); 5015 } 5016 } 5017 5018 if (comp != null) { 5019 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5020 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5021 if (ai != null) { 5022 final ResolveInfo ri = new ResolveInfo(); 5023 ri.activityInfo = ai; 5024 list.add(ri); 5025 } 5026 return list; 5027 } 5028 5029 // reader 5030 synchronized (mPackages) { 5031 final String pkgName = intent.getPackage(); 5032 if (pkgName == null) { 5033 List<CrossProfileIntentFilter> matchingFilters = 5034 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5035 // Check for results that need to skip the current profile. 5036 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5037 resolvedType, flags, userId); 5038 if (xpResolveInfo != null) { 5039 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5040 result.add(xpResolveInfo); 5041 return filterIfNotSystemUser(result, userId); 5042 } 5043 5044 // Check for results in the current profile. 5045 List<ResolveInfo> result = mActivities.queryIntent( 5046 intent, resolvedType, flags, userId); 5047 result = filterIfNotSystemUser(result, userId); 5048 5049 // Check for cross profile results. 5050 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5051 xpResolveInfo = queryCrossProfileIntents( 5052 matchingFilters, intent, resolvedType, flags, userId, 5053 hasNonNegativePriorityResult); 5054 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5055 boolean isVisibleToUser = filterIfNotSystemUser( 5056 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5057 if (isVisibleToUser) { 5058 result.add(xpResolveInfo); 5059 Collections.sort(result, mResolvePrioritySorter); 5060 } 5061 } 5062 if (hasWebURI(intent)) { 5063 CrossProfileDomainInfo xpDomainInfo = null; 5064 final UserInfo parent = getProfileParent(userId); 5065 if (parent != null) { 5066 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5067 flags, userId, parent.id); 5068 } 5069 if (xpDomainInfo != null) { 5070 if (xpResolveInfo != null) { 5071 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5072 // in the result. 5073 result.remove(xpResolveInfo); 5074 } 5075 if (result.size() == 0) { 5076 result.add(xpDomainInfo.resolveInfo); 5077 return result; 5078 } 5079 } else if (result.size() <= 1) { 5080 return result; 5081 } 5082 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5083 xpDomainInfo, userId); 5084 Collections.sort(result, mResolvePrioritySorter); 5085 } 5086 return result; 5087 } 5088 final PackageParser.Package pkg = mPackages.get(pkgName); 5089 if (pkg != null) { 5090 return filterIfNotSystemUser( 5091 mActivities.queryIntentForPackage( 5092 intent, resolvedType, flags, pkg.activities, userId), 5093 userId); 5094 } 5095 return new ArrayList<ResolveInfo>(); 5096 } 5097 } 5098 5099 private static class CrossProfileDomainInfo { 5100 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5101 ResolveInfo resolveInfo; 5102 /* Best domain verification status of the activities found in the other profile */ 5103 int bestDomainVerificationStatus; 5104 } 5105 5106 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5107 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5108 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5109 sourceUserId)) { 5110 return null; 5111 } 5112 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5113 resolvedType, flags, parentUserId); 5114 5115 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5116 return null; 5117 } 5118 CrossProfileDomainInfo result = null; 5119 int size = resultTargetUser.size(); 5120 for (int i = 0; i < size; i++) { 5121 ResolveInfo riTargetUser = resultTargetUser.get(i); 5122 // Intent filter verification is only for filters that specify a host. So don't return 5123 // those that handle all web uris. 5124 if (riTargetUser.handleAllWebDataURI) { 5125 continue; 5126 } 5127 String packageName = riTargetUser.activityInfo.packageName; 5128 PackageSetting ps = mSettings.mPackages.get(packageName); 5129 if (ps == null) { 5130 continue; 5131 } 5132 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5133 int status = (int)(verificationState >> 32); 5134 if (result == null) { 5135 result = new CrossProfileDomainInfo(); 5136 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5137 sourceUserId, parentUserId); 5138 result.bestDomainVerificationStatus = status; 5139 } else { 5140 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5141 result.bestDomainVerificationStatus); 5142 } 5143 } 5144 // Don't consider matches with status NEVER across profiles. 5145 if (result != null && result.bestDomainVerificationStatus 5146 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5147 return null; 5148 } 5149 return result; 5150 } 5151 5152 /** 5153 * Verification statuses are ordered from the worse to the best, except for 5154 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5155 */ 5156 private int bestDomainVerificationStatus(int status1, int status2) { 5157 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5158 return status2; 5159 } 5160 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5161 return status1; 5162 } 5163 return (int) MathUtils.max(status1, status2); 5164 } 5165 5166 private boolean isUserEnabled(int userId) { 5167 long callingId = Binder.clearCallingIdentity(); 5168 try { 5169 UserInfo userInfo = sUserManager.getUserInfo(userId); 5170 return userInfo != null && userInfo.isEnabled(); 5171 } finally { 5172 Binder.restoreCallingIdentity(callingId); 5173 } 5174 } 5175 5176 /** 5177 * Filter out activities with systemUserOnly flag set, when current user is not System. 5178 * 5179 * @return filtered list 5180 */ 5181 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5182 if (userId == UserHandle.USER_SYSTEM) { 5183 return resolveInfos; 5184 } 5185 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5186 ResolveInfo info = resolveInfos.get(i); 5187 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5188 resolveInfos.remove(i); 5189 } 5190 } 5191 return resolveInfos; 5192 } 5193 5194 /** 5195 * @param resolveInfos list of resolve infos in descending priority order 5196 * @return if the list contains a resolve info with non-negative priority 5197 */ 5198 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5199 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5200 } 5201 5202 private static boolean hasWebURI(Intent intent) { 5203 if (intent.getData() == null) { 5204 return false; 5205 } 5206 final String scheme = intent.getScheme(); 5207 if (TextUtils.isEmpty(scheme)) { 5208 return false; 5209 } 5210 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5211 } 5212 5213 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5214 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5215 int userId) { 5216 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5217 5218 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5219 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5220 candidates.size()); 5221 } 5222 5223 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5224 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5225 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5226 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5227 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5228 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5229 5230 synchronized (mPackages) { 5231 final int count = candidates.size(); 5232 // First, try to use linked apps. Partition the candidates into four lists: 5233 // one for the final results, one for the "do not use ever", one for "undefined status" 5234 // and finally one for "browser app type". 5235 for (int n=0; n<count; n++) { 5236 ResolveInfo info = candidates.get(n); 5237 String packageName = info.activityInfo.packageName; 5238 PackageSetting ps = mSettings.mPackages.get(packageName); 5239 if (ps != null) { 5240 // Add to the special match all list (Browser use case) 5241 if (info.handleAllWebDataURI) { 5242 matchAllList.add(info); 5243 continue; 5244 } 5245 // Try to get the status from User settings first 5246 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5247 int status = (int)(packedStatus >> 32); 5248 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5249 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5250 if (DEBUG_DOMAIN_VERIFICATION) { 5251 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5252 + " : linkgen=" + linkGeneration); 5253 } 5254 // Use link-enabled generation as preferredOrder, i.e. 5255 // prefer newly-enabled over earlier-enabled. 5256 info.preferredOrder = linkGeneration; 5257 alwaysList.add(info); 5258 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5259 if (DEBUG_DOMAIN_VERIFICATION) { 5260 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5261 } 5262 neverList.add(info); 5263 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5264 if (DEBUG_DOMAIN_VERIFICATION) { 5265 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5266 } 5267 alwaysAskList.add(info); 5268 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5269 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5270 if (DEBUG_DOMAIN_VERIFICATION) { 5271 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5272 } 5273 undefinedList.add(info); 5274 } 5275 } 5276 } 5277 5278 // We'll want to include browser possibilities in a few cases 5279 boolean includeBrowser = false; 5280 5281 // First try to add the "always" resolution(s) for the current user, if any 5282 if (alwaysList.size() > 0) { 5283 result.addAll(alwaysList); 5284 } else { 5285 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5286 result.addAll(undefinedList); 5287 // Maybe add one for the other profile. 5288 if (xpDomainInfo != null && ( 5289 xpDomainInfo.bestDomainVerificationStatus 5290 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5291 result.add(xpDomainInfo.resolveInfo); 5292 } 5293 includeBrowser = true; 5294 } 5295 5296 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5297 // If there were 'always' entries their preferred order has been set, so we also 5298 // back that off to make the alternatives equivalent 5299 if (alwaysAskList.size() > 0) { 5300 for (ResolveInfo i : result) { 5301 i.preferredOrder = 0; 5302 } 5303 result.addAll(alwaysAskList); 5304 includeBrowser = true; 5305 } 5306 5307 if (includeBrowser) { 5308 // Also add browsers (all of them or only the default one) 5309 if (DEBUG_DOMAIN_VERIFICATION) { 5310 Slog.v(TAG, " ...including browsers in candidate set"); 5311 } 5312 if ((matchFlags & MATCH_ALL) != 0) { 5313 result.addAll(matchAllList); 5314 } else { 5315 // Browser/generic handling case. If there's a default browser, go straight 5316 // to that (but only if there is no other higher-priority match). 5317 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5318 int maxMatchPrio = 0; 5319 ResolveInfo defaultBrowserMatch = null; 5320 final int numCandidates = matchAllList.size(); 5321 for (int n = 0; n < numCandidates; n++) { 5322 ResolveInfo info = matchAllList.get(n); 5323 // track the highest overall match priority... 5324 if (info.priority > maxMatchPrio) { 5325 maxMatchPrio = info.priority; 5326 } 5327 // ...and the highest-priority default browser match 5328 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5329 if (defaultBrowserMatch == null 5330 || (defaultBrowserMatch.priority < info.priority)) { 5331 if (debug) { 5332 Slog.v(TAG, "Considering default browser match " + info); 5333 } 5334 defaultBrowserMatch = info; 5335 } 5336 } 5337 } 5338 if (defaultBrowserMatch != null 5339 && defaultBrowserMatch.priority >= maxMatchPrio 5340 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5341 { 5342 if (debug) { 5343 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5344 } 5345 result.add(defaultBrowserMatch); 5346 } else { 5347 result.addAll(matchAllList); 5348 } 5349 } 5350 5351 // If there is nothing selected, add all candidates and remove the ones that the user 5352 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5353 if (result.size() == 0) { 5354 result.addAll(candidates); 5355 result.removeAll(neverList); 5356 } 5357 } 5358 } 5359 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5360 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5361 result.size()); 5362 for (ResolveInfo info : result) { 5363 Slog.v(TAG, " + " + info.activityInfo); 5364 } 5365 } 5366 return result; 5367 } 5368 5369 // Returns a packed value as a long: 5370 // 5371 // high 'int'-sized word: link status: undefined/ask/never/always. 5372 // low 'int'-sized word: relative priority among 'always' results. 5373 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5374 long result = ps.getDomainVerificationStatusForUser(userId); 5375 // if none available, get the master status 5376 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5377 if (ps.getIntentFilterVerificationInfo() != null) { 5378 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5379 } 5380 } 5381 return result; 5382 } 5383 5384 private ResolveInfo querySkipCurrentProfileIntents( 5385 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5386 int flags, int sourceUserId) { 5387 if (matchingFilters != null) { 5388 int size = matchingFilters.size(); 5389 for (int i = 0; i < size; i ++) { 5390 CrossProfileIntentFilter filter = matchingFilters.get(i); 5391 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5392 // Checking if there are activities in the target user that can handle the 5393 // intent. 5394 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5395 resolvedType, flags, sourceUserId); 5396 if (resolveInfo != null) { 5397 return resolveInfo; 5398 } 5399 } 5400 } 5401 } 5402 return null; 5403 } 5404 5405 // Return matching ResolveInfo in target user if any. 5406 private ResolveInfo queryCrossProfileIntents( 5407 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5408 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5409 if (matchingFilters != null) { 5410 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5411 // match the same intent. For performance reasons, it is better not to 5412 // run queryIntent twice for the same userId 5413 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5414 int size = matchingFilters.size(); 5415 for (int i = 0; i < size; i++) { 5416 CrossProfileIntentFilter filter = matchingFilters.get(i); 5417 int targetUserId = filter.getTargetUserId(); 5418 boolean skipCurrentProfile = 5419 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5420 boolean skipCurrentProfileIfNoMatchFound = 5421 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5422 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5423 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5424 // Checking if there are activities in the target user that can handle the 5425 // intent. 5426 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5427 resolvedType, flags, sourceUserId); 5428 if (resolveInfo != null) return resolveInfo; 5429 alreadyTriedUserIds.put(targetUserId, true); 5430 } 5431 } 5432 } 5433 return null; 5434 } 5435 5436 /** 5437 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5438 * will forward the intent to the filter's target user. 5439 * Otherwise, returns null. 5440 */ 5441 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5442 String resolvedType, int flags, int sourceUserId) { 5443 int targetUserId = filter.getTargetUserId(); 5444 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5445 resolvedType, flags, targetUserId); 5446 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5447 // If all the matches in the target profile are suspended, return null. 5448 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5449 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5450 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5451 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5452 targetUserId); 5453 } 5454 } 5455 } 5456 return null; 5457 } 5458 5459 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5460 int sourceUserId, int targetUserId) { 5461 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5462 long ident = Binder.clearCallingIdentity(); 5463 boolean targetIsProfile; 5464 try { 5465 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5466 } finally { 5467 Binder.restoreCallingIdentity(ident); 5468 } 5469 String className; 5470 if (targetIsProfile) { 5471 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5472 } else { 5473 className = FORWARD_INTENT_TO_PARENT; 5474 } 5475 ComponentName forwardingActivityComponentName = new ComponentName( 5476 mAndroidApplication.packageName, className); 5477 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5478 sourceUserId); 5479 if (!targetIsProfile) { 5480 forwardingActivityInfo.showUserIcon = targetUserId; 5481 forwardingResolveInfo.noResourceId = true; 5482 } 5483 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5484 forwardingResolveInfo.priority = 0; 5485 forwardingResolveInfo.preferredOrder = 0; 5486 forwardingResolveInfo.match = 0; 5487 forwardingResolveInfo.isDefault = true; 5488 forwardingResolveInfo.filter = filter; 5489 forwardingResolveInfo.targetUserId = targetUserId; 5490 return forwardingResolveInfo; 5491 } 5492 5493 @Override 5494 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5495 Intent[] specifics, String[] specificTypes, Intent intent, 5496 String resolvedType, int flags, int userId) { 5497 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5498 flags = updateFlagsForResolve(flags, userId, intent); 5499 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 5500 false, "query intent activity options"); 5501 final String resultsAction = intent.getAction(); 5502 5503 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 5504 | PackageManager.GET_RESOLVED_FILTER, userId); 5505 5506 if (DEBUG_INTENT_MATCHING) { 5507 Log.v(TAG, "Query " + intent + ": " + results); 5508 } 5509 5510 int specificsPos = 0; 5511 int N; 5512 5513 // todo: note that the algorithm used here is O(N^2). This 5514 // isn't a problem in our current environment, but if we start running 5515 // into situations where we have more than 5 or 10 matches then this 5516 // should probably be changed to something smarter... 5517 5518 // First we go through and resolve each of the specific items 5519 // that were supplied, taking care of removing any corresponding 5520 // duplicate items in the generic resolve list. 5521 if (specifics != null) { 5522 for (int i=0; i<specifics.length; i++) { 5523 final Intent sintent = specifics[i]; 5524 if (sintent == null) { 5525 continue; 5526 } 5527 5528 if (DEBUG_INTENT_MATCHING) { 5529 Log.v(TAG, "Specific #" + i + ": " + sintent); 5530 } 5531 5532 String action = sintent.getAction(); 5533 if (resultsAction != null && resultsAction.equals(action)) { 5534 // If this action was explicitly requested, then don't 5535 // remove things that have it. 5536 action = null; 5537 } 5538 5539 ResolveInfo ri = null; 5540 ActivityInfo ai = null; 5541 5542 ComponentName comp = sintent.getComponent(); 5543 if (comp == null) { 5544 ri = resolveIntent( 5545 sintent, 5546 specificTypes != null ? specificTypes[i] : null, 5547 flags, userId); 5548 if (ri == null) { 5549 continue; 5550 } 5551 if (ri == mResolveInfo) { 5552 // ACK! Must do something better with this. 5553 } 5554 ai = ri.activityInfo; 5555 comp = new ComponentName(ai.applicationInfo.packageName, 5556 ai.name); 5557 } else { 5558 ai = getActivityInfo(comp, flags, userId); 5559 if (ai == null) { 5560 continue; 5561 } 5562 } 5563 5564 // Look for any generic query activities that are duplicates 5565 // of this specific one, and remove them from the results. 5566 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5567 N = results.size(); 5568 int j; 5569 for (j=specificsPos; j<N; j++) { 5570 ResolveInfo sri = results.get(j); 5571 if ((sri.activityInfo.name.equals(comp.getClassName()) 5572 && sri.activityInfo.applicationInfo.packageName.equals( 5573 comp.getPackageName())) 5574 || (action != null && sri.filter.matchAction(action))) { 5575 results.remove(j); 5576 if (DEBUG_INTENT_MATCHING) Log.v( 5577 TAG, "Removing duplicate item from " + j 5578 + " due to specific " + specificsPos); 5579 if (ri == null) { 5580 ri = sri; 5581 } 5582 j--; 5583 N--; 5584 } 5585 } 5586 5587 // Add this specific item to its proper place. 5588 if (ri == null) { 5589 ri = new ResolveInfo(); 5590 ri.activityInfo = ai; 5591 } 5592 results.add(specificsPos, ri); 5593 ri.specificIndex = i; 5594 specificsPos++; 5595 } 5596 } 5597 5598 // Now we go through the remaining generic results and remove any 5599 // duplicate actions that are found here. 5600 N = results.size(); 5601 for (int i=specificsPos; i<N-1; i++) { 5602 final ResolveInfo rii = results.get(i); 5603 if (rii.filter == null) { 5604 continue; 5605 } 5606 5607 // Iterate over all of the actions of this result's intent 5608 // filter... typically this should be just one. 5609 final Iterator<String> it = rii.filter.actionsIterator(); 5610 if (it == null) { 5611 continue; 5612 } 5613 while (it.hasNext()) { 5614 final String action = it.next(); 5615 if (resultsAction != null && resultsAction.equals(action)) { 5616 // If this action was explicitly requested, then don't 5617 // remove things that have it. 5618 continue; 5619 } 5620 for (int j=i+1; j<N; j++) { 5621 final ResolveInfo rij = results.get(j); 5622 if (rij.filter != null && rij.filter.hasAction(action)) { 5623 results.remove(j); 5624 if (DEBUG_INTENT_MATCHING) Log.v( 5625 TAG, "Removing duplicate item from " + j 5626 + " due to action " + action + " at " + i); 5627 j--; 5628 N--; 5629 } 5630 } 5631 } 5632 5633 // If the caller didn't request filter information, drop it now 5634 // so we don't have to marshall/unmarshall it. 5635 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5636 rii.filter = null; 5637 } 5638 } 5639 5640 // Filter out the caller activity if so requested. 5641 if (caller != null) { 5642 N = results.size(); 5643 for (int i=0; i<N; i++) { 5644 ActivityInfo ainfo = results.get(i).activityInfo; 5645 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5646 && caller.getClassName().equals(ainfo.name)) { 5647 results.remove(i); 5648 break; 5649 } 5650 } 5651 } 5652 5653 // If the caller didn't request filter information, 5654 // drop them now so we don't have to 5655 // marshall/unmarshall it. 5656 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5657 N = results.size(); 5658 for (int i=0; i<N; i++) { 5659 results.get(i).filter = null; 5660 } 5661 } 5662 5663 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5664 return results; 5665 } 5666 5667 @Override 5668 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5669 int userId) { 5670 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5671 flags = updateFlagsForResolve(flags, userId, intent); 5672 ComponentName comp = intent.getComponent(); 5673 if (comp == null) { 5674 if (intent.getSelector() != null) { 5675 intent = intent.getSelector(); 5676 comp = intent.getComponent(); 5677 } 5678 } 5679 if (comp != null) { 5680 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5681 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5682 if (ai != null) { 5683 ResolveInfo ri = new ResolveInfo(); 5684 ri.activityInfo = ai; 5685 list.add(ri); 5686 } 5687 return list; 5688 } 5689 5690 // reader 5691 synchronized (mPackages) { 5692 String pkgName = intent.getPackage(); 5693 if (pkgName == null) { 5694 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5695 } 5696 final PackageParser.Package pkg = mPackages.get(pkgName); 5697 if (pkg != null) { 5698 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5699 userId); 5700 } 5701 return null; 5702 } 5703 } 5704 5705 @Override 5706 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5707 if (!sUserManager.exists(userId)) return null; 5708 flags = updateFlagsForResolve(flags, userId, intent); 5709 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5710 if (query != null) { 5711 if (query.size() >= 1) { 5712 // If there is more than one service with the same priority, 5713 // just arbitrarily pick the first one. 5714 return query.get(0); 5715 } 5716 } 5717 return null; 5718 } 5719 5720 @Override 5721 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5722 int userId) { 5723 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5724 flags = updateFlagsForResolve(flags, userId, intent); 5725 ComponentName comp = intent.getComponent(); 5726 if (comp == null) { 5727 if (intent.getSelector() != null) { 5728 intent = intent.getSelector(); 5729 comp = intent.getComponent(); 5730 } 5731 } 5732 if (comp != null) { 5733 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5734 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5735 if (si != null) { 5736 final ResolveInfo ri = new ResolveInfo(); 5737 ri.serviceInfo = si; 5738 list.add(ri); 5739 } 5740 return list; 5741 } 5742 5743 // reader 5744 synchronized (mPackages) { 5745 String pkgName = intent.getPackage(); 5746 if (pkgName == null) { 5747 return mServices.queryIntent(intent, resolvedType, flags, userId); 5748 } 5749 final PackageParser.Package pkg = mPackages.get(pkgName); 5750 if (pkg != null) { 5751 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5752 userId); 5753 } 5754 return null; 5755 } 5756 } 5757 5758 @Override 5759 public List<ResolveInfo> queryIntentContentProviders( 5760 Intent intent, String resolvedType, int flags, int userId) { 5761 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5762 flags = updateFlagsForResolve(flags, userId, intent); 5763 ComponentName comp = intent.getComponent(); 5764 if (comp == null) { 5765 if (intent.getSelector() != null) { 5766 intent = intent.getSelector(); 5767 comp = intent.getComponent(); 5768 } 5769 } 5770 if (comp != null) { 5771 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5772 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5773 if (pi != null) { 5774 final ResolveInfo ri = new ResolveInfo(); 5775 ri.providerInfo = pi; 5776 list.add(ri); 5777 } 5778 return list; 5779 } 5780 5781 // reader 5782 synchronized (mPackages) { 5783 String pkgName = intent.getPackage(); 5784 if (pkgName == null) { 5785 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5786 } 5787 final PackageParser.Package pkg = mPackages.get(pkgName); 5788 if (pkg != null) { 5789 return mProviders.queryIntentForPackage( 5790 intent, resolvedType, flags, pkg.providers, userId); 5791 } 5792 return null; 5793 } 5794 } 5795 5796 @Override 5797 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5798 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5799 flags = updateFlagsForPackage(flags, userId, null); 5800 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5801 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5802 5803 // writer 5804 synchronized (mPackages) { 5805 ArrayList<PackageInfo> list; 5806 if (listUninstalled) { 5807 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5808 for (PackageSetting ps : mSettings.mPackages.values()) { 5809 PackageInfo pi; 5810 if (ps.pkg != null) { 5811 pi = generatePackageInfo(ps.pkg, flags, userId); 5812 } else { 5813 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5814 } 5815 if (pi != null) { 5816 list.add(pi); 5817 } 5818 } 5819 } else { 5820 list = new ArrayList<PackageInfo>(mPackages.size()); 5821 for (PackageParser.Package p : mPackages.values()) { 5822 PackageInfo pi = generatePackageInfo(p, flags, userId); 5823 if (pi != null) { 5824 list.add(pi); 5825 } 5826 } 5827 } 5828 5829 return new ParceledListSlice<PackageInfo>(list); 5830 } 5831 } 5832 5833 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5834 String[] permissions, boolean[] tmp, int flags, int userId) { 5835 int numMatch = 0; 5836 final PermissionsState permissionsState = ps.getPermissionsState(); 5837 for (int i=0; i<permissions.length; i++) { 5838 final String permission = permissions[i]; 5839 if (permissionsState.hasPermission(permission, userId)) { 5840 tmp[i] = true; 5841 numMatch++; 5842 } else { 5843 tmp[i] = false; 5844 } 5845 } 5846 if (numMatch == 0) { 5847 return; 5848 } 5849 PackageInfo pi; 5850 if (ps.pkg != null) { 5851 pi = generatePackageInfo(ps.pkg, flags, userId); 5852 } else { 5853 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5854 } 5855 // The above might return null in cases of uninstalled apps or install-state 5856 // skew across users/profiles. 5857 if (pi != null) { 5858 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5859 if (numMatch == permissions.length) { 5860 pi.requestedPermissions = permissions; 5861 } else { 5862 pi.requestedPermissions = new String[numMatch]; 5863 numMatch = 0; 5864 for (int i=0; i<permissions.length; i++) { 5865 if (tmp[i]) { 5866 pi.requestedPermissions[numMatch] = permissions[i]; 5867 numMatch++; 5868 } 5869 } 5870 } 5871 } 5872 list.add(pi); 5873 } 5874 } 5875 5876 @Override 5877 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5878 String[] permissions, int flags, int userId) { 5879 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5880 flags = updateFlagsForPackage(flags, userId, permissions); 5881 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5882 5883 // writer 5884 synchronized (mPackages) { 5885 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5886 boolean[] tmpBools = new boolean[permissions.length]; 5887 if (listUninstalled) { 5888 for (PackageSetting ps : mSettings.mPackages.values()) { 5889 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5890 } 5891 } else { 5892 for (PackageParser.Package pkg : mPackages.values()) { 5893 PackageSetting ps = (PackageSetting)pkg.mExtras; 5894 if (ps != null) { 5895 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5896 userId); 5897 } 5898 } 5899 } 5900 5901 return new ParceledListSlice<PackageInfo>(list); 5902 } 5903 } 5904 5905 @Override 5906 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5907 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5908 flags = updateFlagsForApplication(flags, userId, null); 5909 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5910 5911 // writer 5912 synchronized (mPackages) { 5913 ArrayList<ApplicationInfo> list; 5914 if (listUninstalled) { 5915 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5916 for (PackageSetting ps : mSettings.mPackages.values()) { 5917 ApplicationInfo ai; 5918 if (ps.pkg != null) { 5919 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5920 ps.readUserState(userId), userId); 5921 } else { 5922 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5923 } 5924 if (ai != null) { 5925 list.add(ai); 5926 } 5927 } 5928 } else { 5929 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5930 for (PackageParser.Package p : mPackages.values()) { 5931 if (p.mExtras != null) { 5932 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5933 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5934 if (ai != null) { 5935 list.add(ai); 5936 } 5937 } 5938 } 5939 } 5940 5941 return new ParceledListSlice<ApplicationInfo>(list); 5942 } 5943 } 5944 5945 @Override 5946 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 5947 if (DISABLE_EPHEMERAL_APPS) { 5948 return null; 5949 } 5950 5951 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 5952 "getEphemeralApplications"); 5953 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5954 "getEphemeralApplications"); 5955 synchronized (mPackages) { 5956 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 5957 .getEphemeralApplicationsLPw(userId); 5958 if (ephemeralApps != null) { 5959 return new ParceledListSlice<>(ephemeralApps); 5960 } 5961 } 5962 return null; 5963 } 5964 5965 @Override 5966 public boolean isEphemeralApplication(String packageName, int userId) { 5967 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5968 "isEphemeral"); 5969 if (DISABLE_EPHEMERAL_APPS) { 5970 return false; 5971 } 5972 5973 if (!isCallerSameApp(packageName)) { 5974 return false; 5975 } 5976 synchronized (mPackages) { 5977 PackageParser.Package pkg = mPackages.get(packageName); 5978 if (pkg != null) { 5979 return pkg.applicationInfo.isEphemeralApp(); 5980 } 5981 } 5982 return false; 5983 } 5984 5985 @Override 5986 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 5987 if (DISABLE_EPHEMERAL_APPS) { 5988 return null; 5989 } 5990 5991 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5992 "getCookie"); 5993 if (!isCallerSameApp(packageName)) { 5994 return null; 5995 } 5996 synchronized (mPackages) { 5997 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 5998 packageName, userId); 5999 } 6000 } 6001 6002 @Override 6003 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6004 if (DISABLE_EPHEMERAL_APPS) { 6005 return true; 6006 } 6007 6008 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 6009 "setCookie"); 6010 if (!isCallerSameApp(packageName)) { 6011 return false; 6012 } 6013 synchronized (mPackages) { 6014 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6015 packageName, cookie, userId); 6016 } 6017 } 6018 6019 @Override 6020 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6021 if (DISABLE_EPHEMERAL_APPS) { 6022 return null; 6023 } 6024 6025 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6026 "getEphemeralApplicationIcon"); 6027 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 6028 "getEphemeralApplicationIcon"); 6029 synchronized (mPackages) { 6030 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6031 packageName, userId); 6032 } 6033 } 6034 6035 private boolean isCallerSameApp(String packageName) { 6036 PackageParser.Package pkg = mPackages.get(packageName); 6037 return pkg != null 6038 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6039 } 6040 6041 public List<ApplicationInfo> getPersistentApplications(int flags) { 6042 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6043 6044 // reader 6045 synchronized (mPackages) { 6046 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6047 final int userId = UserHandle.getCallingUserId(); 6048 while (i.hasNext()) { 6049 final PackageParser.Package p = i.next(); 6050 if (p.applicationInfo != null 6051 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 6052 && (!mSafeMode || isSystemApp(p))) { 6053 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6054 if (ps != null) { 6055 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6056 ps.readUserState(userId), userId); 6057 if (ai != null) { 6058 finalList.add(ai); 6059 } 6060 } 6061 } 6062 } 6063 } 6064 6065 return finalList; 6066 } 6067 6068 @Override 6069 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6070 if (!sUserManager.exists(userId)) return null; 6071 flags = updateFlagsForComponent(flags, userId, name); 6072 // reader 6073 synchronized (mPackages) { 6074 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6075 PackageSetting ps = provider != null 6076 ? mSettings.mPackages.get(provider.owner.packageName) 6077 : null; 6078 return ps != null 6079 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6080 ? PackageParser.generateProviderInfo(provider, flags, 6081 ps.readUserState(userId), userId) 6082 : null; 6083 } 6084 } 6085 6086 /** 6087 * @deprecated 6088 */ 6089 @Deprecated 6090 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6091 // reader 6092 synchronized (mPackages) { 6093 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6094 .entrySet().iterator(); 6095 final int userId = UserHandle.getCallingUserId(); 6096 while (i.hasNext()) { 6097 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6098 PackageParser.Provider p = entry.getValue(); 6099 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6100 6101 if (ps != null && p.syncable 6102 && (!mSafeMode || (p.info.applicationInfo.flags 6103 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6104 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6105 ps.readUserState(userId), userId); 6106 if (info != null) { 6107 outNames.add(entry.getKey()); 6108 outInfo.add(info); 6109 } 6110 } 6111 } 6112 } 6113 } 6114 6115 @Override 6116 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6117 int uid, int flags) { 6118 final int userId = processName != null ? UserHandle.getUserId(uid) 6119 : UserHandle.getCallingUserId(); 6120 if (!sUserManager.exists(userId)) return null; 6121 flags = updateFlagsForComponent(flags, userId, processName); 6122 6123 ArrayList<ProviderInfo> finalList = null; 6124 // reader 6125 synchronized (mPackages) { 6126 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6127 while (i.hasNext()) { 6128 final PackageParser.Provider p = i.next(); 6129 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6130 if (ps != null && p.info.authority != null 6131 && (processName == null 6132 || (p.info.processName.equals(processName) 6133 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6134 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6135 if (finalList == null) { 6136 finalList = new ArrayList<ProviderInfo>(3); 6137 } 6138 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6139 ps.readUserState(userId), userId); 6140 if (info != null) { 6141 finalList.add(info); 6142 } 6143 } 6144 } 6145 } 6146 6147 if (finalList != null) { 6148 Collections.sort(finalList, mProviderInitOrderSorter); 6149 return new ParceledListSlice<ProviderInfo>(finalList); 6150 } 6151 6152 return null; 6153 } 6154 6155 @Override 6156 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6157 // reader 6158 synchronized (mPackages) { 6159 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6160 return PackageParser.generateInstrumentationInfo(i, flags); 6161 } 6162 } 6163 6164 @Override 6165 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 6166 int flags) { 6167 ArrayList<InstrumentationInfo> finalList = 6168 new ArrayList<InstrumentationInfo>(); 6169 6170 // reader 6171 synchronized (mPackages) { 6172 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6173 while (i.hasNext()) { 6174 final PackageParser.Instrumentation p = i.next(); 6175 if (targetPackage == null 6176 || targetPackage.equals(p.info.targetPackage)) { 6177 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6178 flags); 6179 if (ii != null) { 6180 finalList.add(ii); 6181 } 6182 } 6183 } 6184 } 6185 6186 return finalList; 6187 } 6188 6189 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6190 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6191 if (overlays == null) { 6192 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6193 return; 6194 } 6195 for (PackageParser.Package opkg : overlays.values()) { 6196 // Not much to do if idmap fails: we already logged the error 6197 // and we certainly don't want to abort installation of pkg simply 6198 // because an overlay didn't fit properly. For these reasons, 6199 // ignore the return value of createIdmapForPackagePairLI. 6200 createIdmapForPackagePairLI(pkg, opkg); 6201 } 6202 } 6203 6204 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6205 PackageParser.Package opkg) { 6206 if (!opkg.mTrustedOverlay) { 6207 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6208 opkg.baseCodePath + ": overlay not trusted"); 6209 return false; 6210 } 6211 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6212 if (overlaySet == null) { 6213 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6214 opkg.baseCodePath + " but target package has no known overlays"); 6215 return false; 6216 } 6217 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6218 // TODO: generate idmap for split APKs 6219 try { 6220 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6221 } catch (InstallerException e) { 6222 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6223 + opkg.baseCodePath); 6224 return false; 6225 } 6226 PackageParser.Package[] overlayArray = 6227 overlaySet.values().toArray(new PackageParser.Package[0]); 6228 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6229 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6230 return p1.mOverlayPriority - p2.mOverlayPriority; 6231 } 6232 }; 6233 Arrays.sort(overlayArray, cmp); 6234 6235 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6236 int i = 0; 6237 for (PackageParser.Package p : overlayArray) { 6238 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6239 } 6240 return true; 6241 } 6242 6243 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6244 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6245 try { 6246 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6247 } finally { 6248 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6249 } 6250 } 6251 6252 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6253 final File[] files = dir.listFiles(); 6254 if (ArrayUtils.isEmpty(files)) { 6255 Log.d(TAG, "No files in app dir " + dir); 6256 return; 6257 } 6258 6259 if (DEBUG_PACKAGE_SCANNING) { 6260 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6261 + " flags=0x" + Integer.toHexString(parseFlags)); 6262 } 6263 6264 for (File file : files) { 6265 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6266 && !PackageInstallerService.isStageName(file.getName()); 6267 if (!isPackage) { 6268 // Ignore entries which are not packages 6269 continue; 6270 } 6271 try { 6272 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6273 scanFlags, currentTime, null); 6274 } catch (PackageManagerException e) { 6275 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6276 6277 // Delete invalid userdata apps 6278 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6279 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6280 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6281 removeCodePathLI(file); 6282 } 6283 } 6284 } 6285 } 6286 6287 private static File getSettingsProblemFile() { 6288 File dataDir = Environment.getDataDirectory(); 6289 File systemDir = new File(dataDir, "system"); 6290 File fname = new File(systemDir, "uiderrors.txt"); 6291 return fname; 6292 } 6293 6294 static void reportSettingsProblem(int priority, String msg) { 6295 logCriticalInfo(priority, msg); 6296 } 6297 6298 static void logCriticalInfo(int priority, String msg) { 6299 Slog.println(priority, TAG, msg); 6300 EventLogTags.writePmCriticalInfo(msg); 6301 try { 6302 File fname = getSettingsProblemFile(); 6303 FileOutputStream out = new FileOutputStream(fname, true); 6304 PrintWriter pw = new FastPrintWriter(out); 6305 SimpleDateFormat formatter = new SimpleDateFormat(); 6306 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6307 pw.println(dateString + ": " + msg); 6308 pw.close(); 6309 FileUtils.setPermissions( 6310 fname.toString(), 6311 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6312 -1, -1); 6313 } catch (java.io.IOException e) { 6314 } 6315 } 6316 6317 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6318 int parseFlags) throws PackageManagerException { 6319 if (ps != null 6320 && ps.codePath.equals(srcFile) 6321 && ps.timeStamp == srcFile.lastModified() 6322 && !isCompatSignatureUpdateNeeded(pkg) 6323 && !isRecoverSignatureUpdateNeeded(pkg)) { 6324 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6325 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6326 ArraySet<PublicKey> signingKs; 6327 synchronized (mPackages) { 6328 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6329 } 6330 if (ps.signatures.mSignatures != null 6331 && ps.signatures.mSignatures.length != 0 6332 && signingKs != null) { 6333 // Optimization: reuse the existing cached certificates 6334 // if the package appears to be unchanged. 6335 pkg.mSignatures = ps.signatures.mSignatures; 6336 pkg.mSigningKeys = signingKs; 6337 return; 6338 } 6339 6340 Slog.w(TAG, "PackageSetting for " + ps.name 6341 + " is missing signatures. Collecting certs again to recover them."); 6342 } else { 6343 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6344 } 6345 6346 try { 6347 PackageParser.collectCertificates(pkg, parseFlags); 6348 } catch (PackageParserException e) { 6349 throw PackageManagerException.from(e); 6350 } 6351 } 6352 6353 /** 6354 * Traces a package scan. 6355 * @see #scanPackageLI(File, int, int, long, UserHandle) 6356 */ 6357 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6358 long currentTime, UserHandle user) throws PackageManagerException { 6359 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6360 try { 6361 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6362 } finally { 6363 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6364 } 6365 } 6366 6367 /** 6368 * Scans a package and returns the newly parsed package. 6369 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6370 */ 6371 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6372 long currentTime, UserHandle user) throws PackageManagerException { 6373 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6374 parseFlags |= mDefParseFlags; 6375 PackageParser pp = new PackageParser(); 6376 pp.setSeparateProcesses(mSeparateProcesses); 6377 pp.setOnlyCoreApps(mOnlyCore); 6378 pp.setDisplayMetrics(mMetrics); 6379 6380 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6381 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6382 } 6383 6384 final PackageParser.Package pkg; 6385 try { 6386 pkg = pp.parsePackage(scanFile, parseFlags); 6387 } catch (PackageParserException e) { 6388 throw PackageManagerException.from(e); 6389 } 6390 6391 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6392 } 6393 6394 /** 6395 * Scans a package and returns the newly parsed package. 6396 * @throws PackageManagerException on a parse error. 6397 */ 6398 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6399 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6400 throws PackageManagerException { 6401 // If the package has children and this is the first dive in the function 6402 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6403 // packages (parent and children) would be successfully scanned before the 6404 // actual scan since scanning mutates internal state and we want to atomically 6405 // install the package and its children. 6406 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6407 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6408 scanFlags |= SCAN_CHECK_ONLY; 6409 } 6410 } else { 6411 scanFlags &= ~SCAN_CHECK_ONLY; 6412 } 6413 6414 // Scan the parent 6415 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags, 6416 scanFlags, currentTime, user); 6417 6418 // Scan the children 6419 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6420 for (int i = 0; i < childCount; i++) { 6421 PackageParser.Package childPackage = pkg.childPackages.get(i); 6422 scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags, 6423 currentTime, user); 6424 } 6425 6426 6427 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6428 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6429 } 6430 6431 return scannedPkg; 6432 } 6433 6434 /** 6435 * Scans a package and returns the newly parsed package. 6436 * @throws PackageManagerException on a parse error. 6437 */ 6438 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6439 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6440 throws PackageManagerException { 6441 PackageSetting ps = null; 6442 PackageSetting updatedPkg; 6443 // reader 6444 synchronized (mPackages) { 6445 // Look to see if we already know about this package. 6446 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6447 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6448 // This package has been renamed to its original name. Let's 6449 // use that. 6450 ps = mSettings.peekPackageLPr(oldName); 6451 } 6452 // If there was no original package, see one for the real package name. 6453 if (ps == null) { 6454 ps = mSettings.peekPackageLPr(pkg.packageName); 6455 } 6456 // Check to see if this package could be hiding/updating a system 6457 // package. Must look for it either under the original or real 6458 // package name depending on our state. 6459 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6460 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6461 6462 // If this is a package we don't know about on the system partition, we 6463 // may need to remove disabled child packages on the system partition 6464 // or may need to not add child packages if the parent apk is updated 6465 // on the data partition and no longer defines this child package. 6466 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6467 // If this is a parent package for an updated system app and this system 6468 // app got an OTA update which no longer defines some of the child packages 6469 // we have to prune them from the disabled system packages. 6470 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6471 if (disabledPs != null) { 6472 final int scannedChildCount = (pkg.childPackages != null) 6473 ? pkg.childPackages.size() : 0; 6474 final int disabledChildCount = disabledPs.childPackageNames != null 6475 ? disabledPs.childPackageNames.size() : 0; 6476 for (int i = 0; i < disabledChildCount; i++) { 6477 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6478 boolean disabledPackageAvailable = false; 6479 for (int j = 0; j < scannedChildCount; j++) { 6480 PackageParser.Package childPkg = pkg.childPackages.get(j); 6481 if (childPkg.packageName.equals(disabledChildPackageName)) { 6482 disabledPackageAvailable = true; 6483 break; 6484 } 6485 } 6486 if (!disabledPackageAvailable) { 6487 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6488 } 6489 } 6490 } 6491 } 6492 } 6493 6494 boolean updatedPkgBetter = false; 6495 // First check if this is a system package that may involve an update 6496 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6497 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6498 // it needs to drop FLAG_PRIVILEGED. 6499 if (locationIsPrivileged(scanFile)) { 6500 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6501 } else { 6502 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6503 } 6504 6505 if (ps != null && !ps.codePath.equals(scanFile)) { 6506 // The path has changed from what was last scanned... check the 6507 // version of the new path against what we have stored to determine 6508 // what to do. 6509 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6510 if (pkg.mVersionCode <= ps.versionCode) { 6511 // The system package has been updated and the code path does not match 6512 // Ignore entry. Skip it. 6513 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6514 + " ignored: updated version " + ps.versionCode 6515 + " better than this " + pkg.mVersionCode); 6516 if (!updatedPkg.codePath.equals(scanFile)) { 6517 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6518 + ps.name + " changing from " + updatedPkg.codePathString 6519 + " to " + scanFile); 6520 updatedPkg.codePath = scanFile; 6521 updatedPkg.codePathString = scanFile.toString(); 6522 updatedPkg.resourcePath = scanFile; 6523 updatedPkg.resourcePathString = scanFile.toString(); 6524 } 6525 updatedPkg.pkg = pkg; 6526 updatedPkg.versionCode = pkg.mVersionCode; 6527 6528 // Update the disabled system child packages to point to the package too. 6529 final int childCount = updatedPkg.childPackageNames != null 6530 ? updatedPkg.childPackageNames.size() : 0; 6531 for (int i = 0; i < childCount; i++) { 6532 String childPackageName = updatedPkg.childPackageNames.get(i); 6533 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6534 childPackageName); 6535 if (updatedChildPkg != null) { 6536 updatedChildPkg.pkg = pkg; 6537 updatedChildPkg.versionCode = pkg.mVersionCode; 6538 } 6539 } 6540 6541 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6542 + scanFile + " ignored: updated version " + ps.versionCode 6543 + " better than this " + pkg.mVersionCode); 6544 } else { 6545 // The current app on the system partition is better than 6546 // what we have updated to on the data partition; switch 6547 // back to the system partition version. 6548 // At this point, its safely assumed that package installation for 6549 // apps in system partition will go through. If not there won't be a working 6550 // version of the app 6551 // writer 6552 synchronized (mPackages) { 6553 // Just remove the loaded entries from package lists. 6554 mPackages.remove(ps.name); 6555 } 6556 6557 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6558 + " reverting from " + ps.codePathString 6559 + ": new version " + pkg.mVersionCode 6560 + " better than installed " + ps.versionCode); 6561 6562 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6563 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6564 synchronized (mInstallLock) { 6565 args.cleanUpResourcesLI(); 6566 } 6567 synchronized (mPackages) { 6568 mSettings.enableSystemPackageLPw(ps.name); 6569 } 6570 updatedPkgBetter = true; 6571 } 6572 } 6573 } 6574 6575 if (updatedPkg != null) { 6576 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6577 // initially 6578 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6579 6580 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6581 // flag set initially 6582 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6583 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6584 } 6585 } 6586 6587 // Verify certificates against what was last scanned 6588 collectCertificatesLI(ps, pkg, scanFile, parseFlags); 6589 6590 /* 6591 * A new system app appeared, but we already had a non-system one of the 6592 * same name installed earlier. 6593 */ 6594 boolean shouldHideSystemApp = false; 6595 if (updatedPkg == null && ps != null 6596 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6597 /* 6598 * Check to make sure the signatures match first. If they don't, 6599 * wipe the installed application and its data. 6600 */ 6601 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6602 != PackageManager.SIGNATURE_MATCH) { 6603 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6604 + " signatures don't match existing userdata copy; removing"); 6605 deletePackageLI(pkg.packageName, null, true, null, 0, null, false, null); 6606 ps = null; 6607 } else { 6608 /* 6609 * If the newly-added system app is an older version than the 6610 * already installed version, hide it. It will be scanned later 6611 * and re-added like an update. 6612 */ 6613 if (pkg.mVersionCode <= ps.versionCode) { 6614 shouldHideSystemApp = true; 6615 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6616 + " but new version " + pkg.mVersionCode + " better than installed " 6617 + ps.versionCode + "; hiding system"); 6618 } else { 6619 /* 6620 * The newly found system app is a newer version that the 6621 * one previously installed. Simply remove the 6622 * already-installed application and replace it with our own 6623 * while keeping the application data. 6624 */ 6625 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6626 + " reverting from " + ps.codePathString + ": new version " 6627 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6628 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6629 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6630 synchronized (mInstallLock) { 6631 args.cleanUpResourcesLI(); 6632 } 6633 } 6634 } 6635 } 6636 6637 // The apk is forward locked (not public) if its code and resources 6638 // are kept in different files. (except for app in either system or 6639 // vendor path). 6640 // TODO grab this value from PackageSettings 6641 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6642 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6643 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6644 } 6645 } 6646 6647 // TODO: extend to support forward-locked splits 6648 String resourcePath = null; 6649 String baseResourcePath = null; 6650 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6651 if (ps != null && ps.resourcePathString != null) { 6652 resourcePath = ps.resourcePathString; 6653 baseResourcePath = ps.resourcePathString; 6654 } else { 6655 // Should not happen at all. Just log an error. 6656 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6657 } 6658 } else { 6659 resourcePath = pkg.codePath; 6660 baseResourcePath = pkg.baseCodePath; 6661 } 6662 6663 // Set application objects path explicitly. 6664 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 6665 pkg.setApplicationInfoCodePath(pkg.codePath); 6666 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 6667 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 6668 pkg.setApplicationInfoResourcePath(resourcePath); 6669 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 6670 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 6671 6672 // Note that we invoke the following method only if we are about to unpack an application 6673 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6674 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6675 6676 /* 6677 * If the system app should be overridden by a previously installed 6678 * data, hide the system app now and let the /data/app scan pick it up 6679 * again. 6680 */ 6681 if (shouldHideSystemApp) { 6682 synchronized (mPackages) { 6683 mSettings.disableSystemPackageLPw(pkg.packageName, true); 6684 } 6685 } 6686 6687 return scannedPkg; 6688 } 6689 6690 private static String fixProcessName(String defProcessName, 6691 String processName, int uid) { 6692 if (processName == null) { 6693 return defProcessName; 6694 } 6695 return processName; 6696 } 6697 6698 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6699 throws PackageManagerException { 6700 if (pkgSetting.signatures.mSignatures != null) { 6701 // Already existing package. Make sure signatures match 6702 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6703 == PackageManager.SIGNATURE_MATCH; 6704 if (!match) { 6705 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6706 == PackageManager.SIGNATURE_MATCH; 6707 } 6708 if (!match) { 6709 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6710 == PackageManager.SIGNATURE_MATCH; 6711 } 6712 if (!match) { 6713 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6714 + pkg.packageName + " signatures do not match the " 6715 + "previously installed version; ignoring!"); 6716 } 6717 } 6718 6719 // Check for shared user signatures 6720 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6721 // Already existing package. Make sure signatures match 6722 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6723 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6724 if (!match) { 6725 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6726 == PackageManager.SIGNATURE_MATCH; 6727 } 6728 if (!match) { 6729 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6730 == PackageManager.SIGNATURE_MATCH; 6731 } 6732 if (!match) { 6733 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6734 "Package " + pkg.packageName 6735 + " has no signatures that match those in shared user " 6736 + pkgSetting.sharedUser.name + "; ignoring!"); 6737 } 6738 } 6739 } 6740 6741 /** 6742 * Enforces that only the system UID or root's UID can call a method exposed 6743 * via Binder. 6744 * 6745 * @param message used as message if SecurityException is thrown 6746 * @throws SecurityException if the caller is not system or root 6747 */ 6748 private static final void enforceSystemOrRoot(String message) { 6749 final int uid = Binder.getCallingUid(); 6750 if (uid != Process.SYSTEM_UID && uid != 0) { 6751 throw new SecurityException(message); 6752 } 6753 } 6754 6755 @Override 6756 public void performFstrimIfNeeded() { 6757 enforceSystemOrRoot("Only the system can request fstrim"); 6758 6759 // Before everything else, see whether we need to fstrim. 6760 try { 6761 IMountService ms = PackageHelper.getMountService(); 6762 if (ms != null) { 6763 final boolean isUpgrade = isUpgrade(); 6764 boolean doTrim = isUpgrade; 6765 if (doTrim) { 6766 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6767 } else { 6768 final long interval = android.provider.Settings.Global.getLong( 6769 mContext.getContentResolver(), 6770 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6771 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6772 if (interval > 0) { 6773 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6774 if (timeSinceLast > interval) { 6775 doTrim = true; 6776 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6777 + "; running immediately"); 6778 } 6779 } 6780 } 6781 if (doTrim) { 6782 if (!isFirstBoot()) { 6783 try { 6784 ActivityManagerNative.getDefault().showBootMessage( 6785 mContext.getResources().getString( 6786 R.string.android_upgrading_fstrim), true); 6787 } catch (RemoteException e) { 6788 } 6789 } 6790 ms.runMaintenance(); 6791 } 6792 } else { 6793 Slog.e(TAG, "Mount service unavailable!"); 6794 } 6795 } catch (RemoteException e) { 6796 // Can't happen; MountService is local 6797 } 6798 } 6799 6800 @Override 6801 public void extractPackagesIfNeeded() { 6802 enforceSystemOrRoot("Only the system can request package extraction"); 6803 6804 // Extract pacakges only if profile-guided compilation is enabled because 6805 // otherwise BackgroundDexOptService will not dexopt them later. 6806 if (!mUseJitProfiles || !isUpgrade()) { 6807 return; 6808 } 6809 6810 List<PackageParser.Package> pkgs; 6811 synchronized (mPackages) { 6812 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 6813 } 6814 6815 int curr = 0; 6816 int total = pkgs.size(); 6817 for (PackageParser.Package pkg : pkgs) { 6818 curr++; 6819 6820 if (DEBUG_DEXOPT) { 6821 Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName); 6822 } 6823 6824 if (!isFirstBoot()) { 6825 try { 6826 ActivityManagerNative.getDefault().showBootMessage( 6827 mContext.getResources().getString(R.string.android_upgrading_apk, 6828 curr, total), true); 6829 } catch (RemoteException e) { 6830 } 6831 } 6832 6833 if (PackageDexOptimizer.canOptimizePackage(pkg)) { 6834 performDexOpt(pkg.packageName, null /* instructionSet */, 6835 false /* useProfiles */, true /* extractOnly */, false /* force */); 6836 } 6837 } 6838 } 6839 6840 @Override 6841 public void notifyPackageUse(String packageName) { 6842 synchronized (mPackages) { 6843 PackageParser.Package p = mPackages.get(packageName); 6844 if (p == null) { 6845 return; 6846 } 6847 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6848 } 6849 } 6850 6851 // TODO: this is not used nor needed. Delete it. 6852 @Override 6853 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6854 return performDexOptTraced(packageName, instructionSet, false /* useProfiles */, 6855 false /* extractOnly */, false /* force */); 6856 } 6857 6858 @Override 6859 public boolean performDexOpt(String packageName, String instructionSet, boolean useProfiles, 6860 boolean extractOnly, boolean force) { 6861 return performDexOptTraced(packageName, instructionSet, useProfiles, extractOnly, force); 6862 } 6863 6864 private boolean performDexOptTraced(String packageName, String instructionSet, 6865 boolean useProfiles, boolean extractOnly, boolean force) { 6866 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6867 try { 6868 return performDexOptInternal(packageName, instructionSet, useProfiles, extractOnly, 6869 force); 6870 } finally { 6871 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6872 } 6873 } 6874 6875 private boolean performDexOptInternal(String packageName, String instructionSet, 6876 boolean useProfiles, boolean extractOnly, boolean force) { 6877 PackageParser.Package p; 6878 final String targetInstructionSet; 6879 synchronized (mPackages) { 6880 p = mPackages.get(packageName); 6881 if (p == null) { 6882 return false; 6883 } 6884 mPackageUsage.write(false); 6885 6886 targetInstructionSet = instructionSet != null ? instructionSet : 6887 getPrimaryInstructionSet(p.applicationInfo); 6888 if (!force && !useProfiles && p.mDexOptPerformed.contains(targetInstructionSet)) { 6889 // Skip only if we do not use profiles since they might trigger a recompilation. 6890 return false; 6891 } 6892 } 6893 long callingId = Binder.clearCallingIdentity(); 6894 try { 6895 synchronized (mInstallLock) { 6896 final String[] instructionSets = new String[] { targetInstructionSet }; 6897 int result = performDexOptInternalWithDependenciesLI(p, instructionSets, 6898 useProfiles, extractOnly, force); 6899 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6900 } 6901 } finally { 6902 Binder.restoreCallingIdentity(callingId); 6903 } 6904 } 6905 6906 public ArraySet<String> getOptimizablePackages() { 6907 ArraySet<String> pkgs = new ArraySet<String>(); 6908 synchronized (mPackages) { 6909 for (PackageParser.Package p : mPackages.values()) { 6910 if (PackageDexOptimizer.canOptimizePackage(p)) { 6911 pkgs.add(p.packageName); 6912 } 6913 } 6914 } 6915 return pkgs; 6916 } 6917 6918 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 6919 String instructionSets[], boolean useProfiles, boolean extractOnly, boolean force) { 6920 // Select the dex optimizer based on the force parameter. 6921 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 6922 // allocate an object here. 6923 PackageDexOptimizer pdo = force 6924 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 6925 : mPackageDexOptimizer; 6926 6927 // Optimize all dependencies first. Note: we ignore the return value and march on 6928 // on errors. 6929 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 6930 if (!deps.isEmpty()) { 6931 for (PackageParser.Package depPackage : deps) { 6932 // TODO: Analyze and investigate if we (should) profile libraries. 6933 // Currently this will do a full compilation of the library. 6934 pdo.performDexOpt(depPackage, instructionSets, false /* useProfiles */, 6935 false /* extractOnly */); 6936 } 6937 } 6938 6939 return pdo.performDexOpt(p, instructionSets, useProfiles, extractOnly); 6940 } 6941 6942 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 6943 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 6944 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 6945 Set<String> collectedNames = new HashSet<>(); 6946 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 6947 6948 retValue.remove(p); 6949 6950 return retValue; 6951 } else { 6952 return Collections.emptyList(); 6953 } 6954 } 6955 6956 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 6957 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 6958 if (!collectedNames.contains(p.packageName)) { 6959 collectedNames.add(p.packageName); 6960 collected.add(p); 6961 6962 if (p.usesLibraries != null) { 6963 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 6964 } 6965 if (p.usesOptionalLibraries != null) { 6966 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 6967 collectedNames); 6968 } 6969 } 6970 } 6971 6972 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 6973 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 6974 for (String libName : libs) { 6975 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 6976 if (libPkg != null) { 6977 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 6978 } 6979 } 6980 } 6981 6982 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 6983 synchronized (mPackages) { 6984 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 6985 if (lib != null && lib.apk != null) { 6986 return mPackages.get(lib.apk); 6987 } 6988 } 6989 return null; 6990 } 6991 6992 public void shutdown() { 6993 mPackageUsage.write(true); 6994 } 6995 6996 @Override 6997 public void forceDexOpt(String packageName) { 6998 enforceSystemOrRoot("forceDexOpt"); 6999 7000 PackageParser.Package pkg; 7001 synchronized (mPackages) { 7002 pkg = mPackages.get(packageName); 7003 if (pkg == null) { 7004 throw new IllegalArgumentException("Unknown package: " + packageName); 7005 } 7006 } 7007 7008 synchronized (mInstallLock) { 7009 final String[] instructionSets = new String[] { 7010 getPrimaryInstructionSet(pkg.applicationInfo) }; 7011 7012 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7013 7014 // Whoever is calling forceDexOpt wants a fully compiled package. 7015 // Don't use profiles since that may cause compilation to be skipped. 7016 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7017 false /* useProfiles */, false /* extractOnly */, true /* force */); 7018 7019 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7020 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7021 throw new IllegalStateException("Failed to dexopt: " + res); 7022 } 7023 } 7024 } 7025 7026 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7027 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7028 Slog.w(TAG, "Unable to update from " + oldPkg.name 7029 + " to " + newPkg.packageName 7030 + ": old package not in system partition"); 7031 return false; 7032 } else if (mPackages.get(oldPkg.name) != null) { 7033 Slog.w(TAG, "Unable to update from " + oldPkg.name 7034 + " to " + newPkg.packageName 7035 + ": old package still exists"); 7036 return false; 7037 } 7038 return true; 7039 } 7040 7041 private boolean removeDataDirsLI(String volumeUuid, String packageName) { 7042 // TODO: triage flags as part of 26466827 7043 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7044 7045 boolean res = true; 7046 final int[] users = sUserManager.getUserIds(); 7047 for (int user : users) { 7048 try { 7049 mInstaller.destroyAppData(volumeUuid, packageName, user, flags); 7050 } catch (InstallerException e) { 7051 Slog.w(TAG, "Failed to delete data directory", e); 7052 res = false; 7053 } 7054 } 7055 return res; 7056 } 7057 7058 void removeCodePathLI(File codePath) { 7059 if (codePath.isDirectory()) { 7060 try { 7061 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7062 } catch (InstallerException e) { 7063 Slog.w(TAG, "Failed to remove code path", e); 7064 } 7065 } else { 7066 codePath.delete(); 7067 } 7068 } 7069 7070 void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) { 7071 try { 7072 mInstaller.destroyAppData(volumeUuid, packageName, userId, flags); 7073 } catch (InstallerException e) { 7074 Slog.w(TAG, "Failed to destroy app data", e); 7075 } 7076 } 7077 7078 void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags, 7079 int appId, String seinfo) { 7080 try { 7081 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo); 7082 } catch (InstallerException e) { 7083 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 7084 } 7085 } 7086 7087 private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 7088 final PackageParser.Package pkg; 7089 synchronized (mPackages) { 7090 pkg = mPackages.get(packageName); 7091 } 7092 if (pkg == null) { 7093 Slog.w(TAG, "Failed to delete code cache directory. No package: " + packageName); 7094 return; 7095 } 7096 deleteCodeCacheDirsLI(pkg); 7097 } 7098 7099 private void deleteCodeCacheDirsLI(PackageParser.Package pkg) { 7100 // TODO: triage flags as part of 26466827 7101 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7102 7103 int[] users = sUserManager.getUserIds(); 7104 int res = 0; 7105 for (int user : users) { 7106 // Remove the parent code cache 7107 try { 7108 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, user, 7109 flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7110 } catch (InstallerException e) { 7111 Slog.w(TAG, "Failed to delete code cache directory", e); 7112 } 7113 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7114 for (int i = 0; i < childCount; i++) { 7115 PackageParser.Package childPkg = pkg.childPackages.get(i); 7116 // Remove the child code cache 7117 try { 7118 mInstaller.clearAppData(childPkg.volumeUuid, childPkg.packageName, 7119 user, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7120 } catch (InstallerException e) { 7121 Slog.w(TAG, "Failed to delete code cache directory", e); 7122 } 7123 } 7124 } 7125 } 7126 7127 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7128 long lastUpdateTime) { 7129 // Set parent install/update time 7130 PackageSetting ps = (PackageSetting) pkg.mExtras; 7131 if (ps != null) { 7132 ps.firstInstallTime = firstInstallTime; 7133 ps.lastUpdateTime = lastUpdateTime; 7134 } 7135 // Set children install/update time 7136 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7137 for (int i = 0; i < childCount; i++) { 7138 PackageParser.Package childPkg = pkg.childPackages.get(i); 7139 ps = (PackageSetting) childPkg.mExtras; 7140 if (ps != null) { 7141 ps.firstInstallTime = firstInstallTime; 7142 ps.lastUpdateTime = lastUpdateTime; 7143 } 7144 } 7145 } 7146 7147 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7148 PackageParser.Package changingLib) { 7149 if (file.path != null) { 7150 usesLibraryFiles.add(file.path); 7151 return; 7152 } 7153 PackageParser.Package p = mPackages.get(file.apk); 7154 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7155 // If we are doing this while in the middle of updating a library apk, 7156 // then we need to make sure to use that new apk for determining the 7157 // dependencies here. (We haven't yet finished committing the new apk 7158 // to the package manager state.) 7159 if (p == null || p.packageName.equals(changingLib.packageName)) { 7160 p = changingLib; 7161 } 7162 } 7163 if (p != null) { 7164 usesLibraryFiles.addAll(p.getAllCodePaths()); 7165 } 7166 } 7167 7168 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7169 PackageParser.Package changingLib) throws PackageManagerException { 7170 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7171 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7172 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7173 for (int i=0; i<N; i++) { 7174 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7175 if (file == null) { 7176 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7177 "Package " + pkg.packageName + " requires unavailable shared library " 7178 + pkg.usesLibraries.get(i) + "; failing!"); 7179 } 7180 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7181 } 7182 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7183 for (int i=0; i<N; i++) { 7184 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7185 if (file == null) { 7186 Slog.w(TAG, "Package " + pkg.packageName 7187 + " desires unavailable shared library " 7188 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7189 } else { 7190 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7191 } 7192 } 7193 N = usesLibraryFiles.size(); 7194 if (N > 0) { 7195 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7196 } else { 7197 pkg.usesLibraryFiles = null; 7198 } 7199 } 7200 } 7201 7202 private static boolean hasString(List<String> list, List<String> which) { 7203 if (list == null) { 7204 return false; 7205 } 7206 for (int i=list.size()-1; i>=0; i--) { 7207 for (int j=which.size()-1; j>=0; j--) { 7208 if (which.get(j).equals(list.get(i))) { 7209 return true; 7210 } 7211 } 7212 } 7213 return false; 7214 } 7215 7216 private void updateAllSharedLibrariesLPw() { 7217 for (PackageParser.Package pkg : mPackages.values()) { 7218 try { 7219 updateSharedLibrariesLPw(pkg, null); 7220 } catch (PackageManagerException e) { 7221 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7222 } 7223 } 7224 } 7225 7226 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7227 PackageParser.Package changingPkg) { 7228 ArrayList<PackageParser.Package> res = null; 7229 for (PackageParser.Package pkg : mPackages.values()) { 7230 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7231 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7232 if (res == null) { 7233 res = new ArrayList<PackageParser.Package>(); 7234 } 7235 res.add(pkg); 7236 try { 7237 updateSharedLibrariesLPw(pkg, changingPkg); 7238 } catch (PackageManagerException e) { 7239 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7240 } 7241 } 7242 } 7243 return res; 7244 } 7245 7246 /** 7247 * Derive the value of the {@code cpuAbiOverride} based on the provided 7248 * value and an optional stored value from the package settings. 7249 */ 7250 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7251 String cpuAbiOverride = null; 7252 7253 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7254 cpuAbiOverride = null; 7255 } else if (abiOverride != null) { 7256 cpuAbiOverride = abiOverride; 7257 } else if (settings != null) { 7258 cpuAbiOverride = settings.cpuAbiOverrideString; 7259 } 7260 7261 return cpuAbiOverride; 7262 } 7263 7264 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 7265 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7266 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7267 // If the package has children and this is the first dive in the function 7268 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7269 // whether all packages (parent and children) would be successfully scanned 7270 // before the actual scan since scanning mutates internal state and we want 7271 // to atomically install the package and its children. 7272 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7273 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7274 scanFlags |= SCAN_CHECK_ONLY; 7275 } 7276 } else { 7277 scanFlags &= ~SCAN_CHECK_ONLY; 7278 } 7279 7280 final PackageParser.Package scannedPkg; 7281 try { 7282 // Scan the parent 7283 scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 7284 // Scan the children 7285 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7286 for (int i = 0; i < childCount; i++) { 7287 PackageParser.Package childPkg = pkg.childPackages.get(i); 7288 scanPackageLI(childPkg, parseFlags, 7289 scanFlags, currentTime, user); 7290 } 7291 } finally { 7292 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7293 } 7294 7295 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7296 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 7297 } 7298 7299 return scannedPkg; 7300 } 7301 7302 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 7303 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7304 boolean success = false; 7305 try { 7306 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 7307 currentTime, user); 7308 success = true; 7309 return res; 7310 } finally { 7311 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7312 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 7313 } 7314 } 7315 } 7316 7317 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 7318 int scanFlags, long currentTime, UserHandle user) 7319 throws PackageManagerException { 7320 final File scanFile = new File(pkg.codePath); 7321 if (pkg.applicationInfo.getCodePath() == null || 7322 pkg.applicationInfo.getResourcePath() == null) { 7323 // Bail out. The resource and code paths haven't been set. 7324 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7325 "Code and resource paths haven't been set correctly"); 7326 } 7327 7328 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7329 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7330 } else { 7331 // Only allow system apps to be flagged as core apps. 7332 pkg.coreApp = false; 7333 } 7334 7335 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7336 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7337 } 7338 7339 if (mCustomResolverComponentName != null && 7340 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7341 setUpCustomResolverActivity(pkg); 7342 } 7343 7344 if (pkg.packageName.equals("android")) { 7345 synchronized (mPackages) { 7346 if (mAndroidApplication != null) { 7347 Slog.w(TAG, "*************************************************"); 7348 Slog.w(TAG, "Core android package being redefined. Skipping."); 7349 Slog.w(TAG, " file=" + scanFile); 7350 Slog.w(TAG, "*************************************************"); 7351 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7352 "Core android package being redefined. Skipping."); 7353 } 7354 7355 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7356 // Set up information for our fall-back user intent resolution activity. 7357 mPlatformPackage = pkg; 7358 pkg.mVersionCode = mSdkVersion; 7359 mAndroidApplication = pkg.applicationInfo; 7360 7361 if (!mResolverReplaced) { 7362 mResolveActivity.applicationInfo = mAndroidApplication; 7363 mResolveActivity.name = ResolverActivity.class.getName(); 7364 mResolveActivity.packageName = mAndroidApplication.packageName; 7365 mResolveActivity.processName = "system:ui"; 7366 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7367 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7368 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7369 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7370 mResolveActivity.exported = true; 7371 mResolveActivity.enabled = true; 7372 mResolveInfo.activityInfo = mResolveActivity; 7373 mResolveInfo.priority = 0; 7374 mResolveInfo.preferredOrder = 0; 7375 mResolveInfo.match = 0; 7376 mResolveComponentName = new ComponentName( 7377 mAndroidApplication.packageName, mResolveActivity.name); 7378 } 7379 } 7380 } 7381 } 7382 7383 if (DEBUG_PACKAGE_SCANNING) { 7384 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7385 Log.d(TAG, "Scanning package " + pkg.packageName); 7386 } 7387 7388 synchronized (mPackages) { 7389 if (mPackages.containsKey(pkg.packageName) 7390 || mSharedLibraries.containsKey(pkg.packageName)) { 7391 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7392 "Application package " + pkg.packageName 7393 + " already installed. Skipping duplicate."); 7394 } 7395 7396 // If we're only installing presumed-existing packages, require that the 7397 // scanned APK is both already known and at the path previously established 7398 // for it. Previously unknown packages we pick up normally, but if we have an 7399 // a priori expectation about this package's install presence, enforce it. 7400 // With a singular exception for new system packages. When an OTA contains 7401 // a new system package, we allow the codepath to change from a system location 7402 // to the user-installed location. If we don't allow this change, any newer, 7403 // user-installed version of the application will be ignored. 7404 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7405 if (mExpectingBetter.containsKey(pkg.packageName)) { 7406 logCriticalInfo(Log.WARN, 7407 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7408 } else { 7409 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7410 if (known != null) { 7411 if (DEBUG_PACKAGE_SCANNING) { 7412 Log.d(TAG, "Examining " + pkg.codePath 7413 + " and requiring known paths " + known.codePathString 7414 + " & " + known.resourcePathString); 7415 } 7416 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7417 || !pkg.applicationInfo.getResourcePath().equals( 7418 known.resourcePathString)) { 7419 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7420 "Application package " + pkg.packageName 7421 + " found at " + pkg.applicationInfo.getCodePath() 7422 + " but expected at " + known.codePathString 7423 + "; ignoring."); 7424 } 7425 } 7426 } 7427 } 7428 } 7429 7430 // Initialize package source and resource directories 7431 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7432 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7433 7434 SharedUserSetting suid = null; 7435 PackageSetting pkgSetting = null; 7436 7437 if (!isSystemApp(pkg)) { 7438 // Only system apps can use these features. 7439 pkg.mOriginalPackages = null; 7440 pkg.mRealPackage = null; 7441 pkg.mAdoptPermissions = null; 7442 } 7443 7444 // Getting the package setting may have a side-effect, so if we 7445 // are only checking if scan would succeed, stash a copy of the 7446 // old setting to restore at the end. 7447 PackageSetting nonMutatedPs = null; 7448 7449 // writer 7450 synchronized (mPackages) { 7451 if (pkg.mSharedUserId != null) { 7452 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7453 if (suid == null) { 7454 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7455 "Creating application package " + pkg.packageName 7456 + " for shared user failed"); 7457 } 7458 if (DEBUG_PACKAGE_SCANNING) { 7459 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7460 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7461 + "): packages=" + suid.packages); 7462 } 7463 } 7464 7465 // Check if we are renaming from an original package name. 7466 PackageSetting origPackage = null; 7467 String realName = null; 7468 if (pkg.mOriginalPackages != null) { 7469 // This package may need to be renamed to a previously 7470 // installed name. Let's check on that... 7471 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7472 if (pkg.mOriginalPackages.contains(renamed)) { 7473 // This package had originally been installed as the 7474 // original name, and we have already taken care of 7475 // transitioning to the new one. Just update the new 7476 // one to continue using the old name. 7477 realName = pkg.mRealPackage; 7478 if (!pkg.packageName.equals(renamed)) { 7479 // Callers into this function may have already taken 7480 // care of renaming the package; only do it here if 7481 // it is not already done. 7482 pkg.setPackageName(renamed); 7483 } 7484 7485 } else { 7486 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7487 if ((origPackage = mSettings.peekPackageLPr( 7488 pkg.mOriginalPackages.get(i))) != null) { 7489 // We do have the package already installed under its 7490 // original name... should we use it? 7491 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7492 // New package is not compatible with original. 7493 origPackage = null; 7494 continue; 7495 } else if (origPackage.sharedUser != null) { 7496 // Make sure uid is compatible between packages. 7497 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7498 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7499 + " to " + pkg.packageName + ": old uid " 7500 + origPackage.sharedUser.name 7501 + " differs from " + pkg.mSharedUserId); 7502 origPackage = null; 7503 continue; 7504 } 7505 } else { 7506 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7507 + pkg.packageName + " to old name " + origPackage.name); 7508 } 7509 break; 7510 } 7511 } 7512 } 7513 } 7514 7515 if (mTransferedPackages.contains(pkg.packageName)) { 7516 Slog.w(TAG, "Package " + pkg.packageName 7517 + " was transferred to another, but its .apk remains"); 7518 } 7519 7520 // See comments in nonMutatedPs declaration 7521 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7522 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 7523 if (foundPs != null) { 7524 nonMutatedPs = new PackageSetting(foundPs); 7525 } 7526 } 7527 7528 // Just create the setting, don't add it yet. For already existing packages 7529 // the PkgSetting exists already and doesn't have to be created. 7530 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7531 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7532 pkg.applicationInfo.primaryCpuAbi, 7533 pkg.applicationInfo.secondaryCpuAbi, 7534 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7535 user, false); 7536 if (pkgSetting == null) { 7537 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7538 "Creating application package " + pkg.packageName + " failed"); 7539 } 7540 7541 if (pkgSetting.origPackage != null) { 7542 // If we are first transitioning from an original package, 7543 // fix up the new package's name now. We need to do this after 7544 // looking up the package under its new name, so getPackageLP 7545 // can take care of fiddling things correctly. 7546 pkg.setPackageName(origPackage.name); 7547 7548 // File a report about this. 7549 String msg = "New package " + pkgSetting.realName 7550 + " renamed to replace old package " + pkgSetting.name; 7551 reportSettingsProblem(Log.WARN, msg); 7552 7553 // Make a note of it. 7554 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7555 mTransferedPackages.add(origPackage.name); 7556 } 7557 7558 // No longer need to retain this. 7559 pkgSetting.origPackage = null; 7560 } 7561 7562 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 7563 // Make a note of it. 7564 mTransferedPackages.add(pkg.packageName); 7565 } 7566 7567 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7568 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7569 } 7570 7571 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7572 // Check all shared libraries and map to their actual file path. 7573 // We only do this here for apps not on a system dir, because those 7574 // are the only ones that can fail an install due to this. We 7575 // will take care of the system apps by updating all of their 7576 // library paths after the scan is done. 7577 updateSharedLibrariesLPw(pkg, null); 7578 } 7579 7580 if (mFoundPolicyFile) { 7581 SELinuxMMAC.assignSeinfoValue(pkg); 7582 } 7583 7584 pkg.applicationInfo.uid = pkgSetting.appId; 7585 pkg.mExtras = pkgSetting; 7586 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7587 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7588 // We just determined the app is signed correctly, so bring 7589 // over the latest parsed certs. 7590 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7591 } else { 7592 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7593 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7594 "Package " + pkg.packageName + " upgrade keys do not match the " 7595 + "previously installed version"); 7596 } else { 7597 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7598 String msg = "System package " + pkg.packageName 7599 + " signature changed; retaining data."; 7600 reportSettingsProblem(Log.WARN, msg); 7601 } 7602 } 7603 } else { 7604 try { 7605 verifySignaturesLP(pkgSetting, pkg); 7606 // We just determined the app is signed correctly, so bring 7607 // over the latest parsed certs. 7608 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7609 } catch (PackageManagerException e) { 7610 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7611 throw e; 7612 } 7613 // The signature has changed, but this package is in the system 7614 // image... let's recover! 7615 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7616 // However... if this package is part of a shared user, but it 7617 // doesn't match the signature of the shared user, let's fail. 7618 // What this means is that you can't change the signatures 7619 // associated with an overall shared user, which doesn't seem all 7620 // that unreasonable. 7621 if (pkgSetting.sharedUser != null) { 7622 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7623 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7624 throw new PackageManagerException( 7625 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7626 "Signature mismatch for shared user: " 7627 + pkgSetting.sharedUser); 7628 } 7629 } 7630 // File a report about this. 7631 String msg = "System package " + pkg.packageName 7632 + " signature changed; retaining data."; 7633 reportSettingsProblem(Log.WARN, msg); 7634 } 7635 } 7636 // Verify that this new package doesn't have any content providers 7637 // that conflict with existing packages. Only do this if the 7638 // package isn't already installed, since we don't want to break 7639 // things that are installed. 7640 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7641 final int N = pkg.providers.size(); 7642 int i; 7643 for (i=0; i<N; i++) { 7644 PackageParser.Provider p = pkg.providers.get(i); 7645 if (p.info.authority != null) { 7646 String names[] = p.info.authority.split(";"); 7647 for (int j = 0; j < names.length; j++) { 7648 if (mProvidersByAuthority.containsKey(names[j])) { 7649 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7650 final String otherPackageName = 7651 ((other != null && other.getComponentName() != null) ? 7652 other.getComponentName().getPackageName() : "?"); 7653 throw new PackageManagerException( 7654 INSTALL_FAILED_CONFLICTING_PROVIDER, 7655 "Can't install because provider name " + names[j] 7656 + " (in package " + pkg.applicationInfo.packageName 7657 + ") is already used by " + otherPackageName); 7658 } 7659 } 7660 } 7661 } 7662 } 7663 7664 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 7665 // This package wants to adopt ownership of permissions from 7666 // another package. 7667 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7668 final String origName = pkg.mAdoptPermissions.get(i); 7669 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7670 if (orig != null) { 7671 if (verifyPackageUpdateLPr(orig, pkg)) { 7672 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7673 + pkg.packageName); 7674 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7675 } 7676 } 7677 } 7678 } 7679 } 7680 7681 final String pkgName = pkg.packageName; 7682 7683 final long scanFileTime = scanFile.lastModified(); 7684 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7685 pkg.applicationInfo.processName = fixProcessName( 7686 pkg.applicationInfo.packageName, 7687 pkg.applicationInfo.processName, 7688 pkg.applicationInfo.uid); 7689 7690 if (pkg != mPlatformPackage) { 7691 // Get all of our default paths setup 7692 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7693 } 7694 7695 final String path = scanFile.getPath(); 7696 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7697 7698 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7699 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7700 7701 // Some system apps still use directory structure for native libraries 7702 // in which case we might end up not detecting abi solely based on apk 7703 // structure. Try to detect abi based on directory structure. 7704 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7705 pkg.applicationInfo.primaryCpuAbi == null) { 7706 setBundledAppAbisAndRoots(pkg, pkgSetting); 7707 setNativeLibraryPaths(pkg); 7708 } 7709 7710 } else { 7711 if ((scanFlags & SCAN_MOVE) != 0) { 7712 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7713 // but we already have this packages package info in the PackageSetting. We just 7714 // use that and derive the native library path based on the new codepath. 7715 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7716 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7717 } 7718 7719 // Set native library paths again. For moves, the path will be updated based on the 7720 // ABIs we've determined above. For non-moves, the path will be updated based on the 7721 // ABIs we determined during compilation, but the path will depend on the final 7722 // package path (after the rename away from the stage path). 7723 setNativeLibraryPaths(pkg); 7724 } 7725 7726 // This is a special case for the "system" package, where the ABI is 7727 // dictated by the zygote configuration (and init.rc). We should keep track 7728 // of this ABI so that we can deal with "normal" applications that run under 7729 // the same UID correctly. 7730 if (mPlatformPackage == pkg) { 7731 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7732 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7733 } 7734 7735 // If there's a mismatch between the abi-override in the package setting 7736 // and the abiOverride specified for the install. Warn about this because we 7737 // would've already compiled the app without taking the package setting into 7738 // account. 7739 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7740 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7741 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7742 " for package " + pkg.packageName); 7743 } 7744 } 7745 7746 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7747 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7748 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7749 7750 // Copy the derived override back to the parsed package, so that we can 7751 // update the package settings accordingly. 7752 pkg.cpuAbiOverride = cpuAbiOverride; 7753 7754 if (DEBUG_ABI_SELECTION) { 7755 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7756 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7757 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7758 } 7759 7760 // Push the derived path down into PackageSettings so we know what to 7761 // clean up at uninstall time. 7762 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7763 7764 if (DEBUG_ABI_SELECTION) { 7765 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7766 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7767 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7768 } 7769 7770 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7771 // We don't do this here during boot because we can do it all 7772 // at once after scanning all existing packages. 7773 // 7774 // We also do this *before* we perform dexopt on this package, so that 7775 // we can avoid redundant dexopts, and also to make sure we've got the 7776 // code and package path correct. 7777 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7778 pkg, true /* boot complete */); 7779 } 7780 7781 if (mFactoryTest && pkg.requestedPermissions.contains( 7782 android.Manifest.permission.FACTORY_TEST)) { 7783 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7784 } 7785 7786 ArrayList<PackageParser.Package> clientLibPkgs = null; 7787 7788 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7789 if (nonMutatedPs != null) { 7790 synchronized (mPackages) { 7791 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 7792 } 7793 } 7794 return pkg; 7795 } 7796 7797 // Only privileged apps and updated privileged apps can add child packages. 7798 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 7799 if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) { 7800 throw new PackageManagerException("Only privileged apps and updated " 7801 + "privileged apps can add child packages. Ignoring package " 7802 + pkg.packageName); 7803 } 7804 final int childCount = pkg.childPackages.size(); 7805 for (int i = 0; i < childCount; i++) { 7806 PackageParser.Package childPkg = pkg.childPackages.get(i); 7807 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 7808 childPkg.packageName)) { 7809 throw new PackageManagerException("Cannot override a child package of " 7810 + "another disabled system app. Ignoring package " + pkg.packageName); 7811 } 7812 } 7813 } 7814 7815 // writer 7816 synchronized (mPackages) { 7817 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7818 // Only system apps can add new shared libraries. 7819 if (pkg.libraryNames != null) { 7820 for (int i=0; i<pkg.libraryNames.size(); i++) { 7821 String name = pkg.libraryNames.get(i); 7822 boolean allowed = false; 7823 if (pkg.isUpdatedSystemApp()) { 7824 // New library entries can only be added through the 7825 // system image. This is important to get rid of a lot 7826 // of nasty edge cases: for example if we allowed a non- 7827 // system update of the app to add a library, then uninstalling 7828 // the update would make the library go away, and assumptions 7829 // we made such as through app install filtering would now 7830 // have allowed apps on the device which aren't compatible 7831 // with it. Better to just have the restriction here, be 7832 // conservative, and create many fewer cases that can negatively 7833 // impact the user experience. 7834 final PackageSetting sysPs = mSettings 7835 .getDisabledSystemPkgLPr(pkg.packageName); 7836 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7837 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7838 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7839 allowed = true; 7840 break; 7841 } 7842 } 7843 } 7844 } else { 7845 allowed = true; 7846 } 7847 if (allowed) { 7848 if (!mSharedLibraries.containsKey(name)) { 7849 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7850 } else if (!name.equals(pkg.packageName)) { 7851 Slog.w(TAG, "Package " + pkg.packageName + " library " 7852 + name + " already exists; skipping"); 7853 } 7854 } else { 7855 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7856 + name + " that is not declared on system image; skipping"); 7857 } 7858 } 7859 if ((scanFlags & SCAN_BOOTING) == 0) { 7860 // If we are not booting, we need to update any applications 7861 // that are clients of our shared library. If we are booting, 7862 // this will all be done once the scan is complete. 7863 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7864 } 7865 } 7866 } 7867 } 7868 7869 // Request the ActivityManager to kill the process(only for existing packages) 7870 // so that we do not end up in a confused state while the user is still using the older 7871 // version of the application while the new one gets installed. 7872 if ((scanFlags & SCAN_REPLACING) != 0) { 7873 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7874 7875 killApplication(pkg.applicationInfo.packageName, 7876 pkg.applicationInfo.uid, "replace pkg"); 7877 7878 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7879 } 7880 7881 // Also need to kill any apps that are dependent on the library. 7882 if (clientLibPkgs != null) { 7883 for (int i=0; i<clientLibPkgs.size(); i++) { 7884 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7885 killApplication(clientPkg.applicationInfo.packageName, 7886 clientPkg.applicationInfo.uid, "update lib"); 7887 } 7888 } 7889 7890 // Make sure we're not adding any bogus keyset info 7891 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7892 ksms.assertScannedPackageValid(pkg); 7893 7894 // writer 7895 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7896 7897 boolean createIdmapFailed = false; 7898 synchronized (mPackages) { 7899 // We don't expect installation to fail beyond this point 7900 7901 // Add the new setting to mSettings 7902 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7903 // Add the new setting to mPackages 7904 mPackages.put(pkg.applicationInfo.packageName, pkg); 7905 // Make sure we don't accidentally delete its data. 7906 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7907 while (iter.hasNext()) { 7908 PackageCleanItem item = iter.next(); 7909 if (pkgName.equals(item.packageName)) { 7910 iter.remove(); 7911 } 7912 } 7913 7914 // Take care of first install / last update times. 7915 if (currentTime != 0) { 7916 if (pkgSetting.firstInstallTime == 0) { 7917 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7918 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7919 pkgSetting.lastUpdateTime = currentTime; 7920 } 7921 } else if (pkgSetting.firstInstallTime == 0) { 7922 // We need *something*. Take time time stamp of the file. 7923 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7924 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7925 if (scanFileTime != pkgSetting.timeStamp) { 7926 // A package on the system image has changed; consider this 7927 // to be an update. 7928 pkgSetting.lastUpdateTime = scanFileTime; 7929 } 7930 } 7931 7932 // Add the package's KeySets to the global KeySetManagerService 7933 ksms.addScannedPackageLPw(pkg); 7934 7935 int N = pkg.providers.size(); 7936 StringBuilder r = null; 7937 int i; 7938 for (i=0; i<N; i++) { 7939 PackageParser.Provider p = pkg.providers.get(i); 7940 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7941 p.info.processName, pkg.applicationInfo.uid); 7942 mProviders.addProvider(p); 7943 p.syncable = p.info.isSyncable; 7944 if (p.info.authority != null) { 7945 String names[] = p.info.authority.split(";"); 7946 p.info.authority = null; 7947 for (int j = 0; j < names.length; j++) { 7948 if (j == 1 && p.syncable) { 7949 // We only want the first authority for a provider to possibly be 7950 // syncable, so if we already added this provider using a different 7951 // authority clear the syncable flag. We copy the provider before 7952 // changing it because the mProviders object contains a reference 7953 // to a provider that we don't want to change. 7954 // Only do this for the second authority since the resulting provider 7955 // object can be the same for all future authorities for this provider. 7956 p = new PackageParser.Provider(p); 7957 p.syncable = false; 7958 } 7959 if (!mProvidersByAuthority.containsKey(names[j])) { 7960 mProvidersByAuthority.put(names[j], p); 7961 if (p.info.authority == null) { 7962 p.info.authority = names[j]; 7963 } else { 7964 p.info.authority = p.info.authority + ";" + names[j]; 7965 } 7966 if (DEBUG_PACKAGE_SCANNING) { 7967 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7968 Log.d(TAG, "Registered content provider: " + names[j] 7969 + ", className = " + p.info.name + ", isSyncable = " 7970 + p.info.isSyncable); 7971 } 7972 } else { 7973 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7974 Slog.w(TAG, "Skipping provider name " + names[j] + 7975 " (in package " + pkg.applicationInfo.packageName + 7976 "): name already used by " 7977 + ((other != null && other.getComponentName() != null) 7978 ? other.getComponentName().getPackageName() : "?")); 7979 } 7980 } 7981 } 7982 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7983 if (r == null) { 7984 r = new StringBuilder(256); 7985 } else { 7986 r.append(' '); 7987 } 7988 r.append(p.info.name); 7989 } 7990 } 7991 if (r != null) { 7992 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7993 } 7994 7995 N = pkg.services.size(); 7996 r = null; 7997 for (i=0; i<N; i++) { 7998 PackageParser.Service s = pkg.services.get(i); 7999 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8000 s.info.processName, pkg.applicationInfo.uid); 8001 mServices.addService(s); 8002 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8003 if (r == null) { 8004 r = new StringBuilder(256); 8005 } else { 8006 r.append(' '); 8007 } 8008 r.append(s.info.name); 8009 } 8010 } 8011 if (r != null) { 8012 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8013 } 8014 8015 N = pkg.receivers.size(); 8016 r = null; 8017 for (i=0; i<N; i++) { 8018 PackageParser.Activity a = pkg.receivers.get(i); 8019 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8020 a.info.processName, pkg.applicationInfo.uid); 8021 mReceivers.addActivity(a, "receiver"); 8022 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8023 if (r == null) { 8024 r = new StringBuilder(256); 8025 } else { 8026 r.append(' '); 8027 } 8028 r.append(a.info.name); 8029 } 8030 } 8031 if (r != null) { 8032 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8033 } 8034 8035 N = pkg.activities.size(); 8036 r = null; 8037 for (i=0; i<N; i++) { 8038 PackageParser.Activity a = pkg.activities.get(i); 8039 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8040 a.info.processName, pkg.applicationInfo.uid); 8041 mActivities.addActivity(a, "activity"); 8042 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8043 if (r == null) { 8044 r = new StringBuilder(256); 8045 } else { 8046 r.append(' '); 8047 } 8048 r.append(a.info.name); 8049 } 8050 } 8051 if (r != null) { 8052 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8053 } 8054 8055 N = pkg.permissionGroups.size(); 8056 r = null; 8057 for (i=0; i<N; i++) { 8058 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8059 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8060 if (cur == null) { 8061 mPermissionGroups.put(pg.info.name, pg); 8062 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8063 if (r == null) { 8064 r = new StringBuilder(256); 8065 } else { 8066 r.append(' '); 8067 } 8068 r.append(pg.info.name); 8069 } 8070 } else { 8071 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8072 + pg.info.packageName + " ignored: original from " 8073 + cur.info.packageName); 8074 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8075 if (r == null) { 8076 r = new StringBuilder(256); 8077 } else { 8078 r.append(' '); 8079 } 8080 r.append("DUP:"); 8081 r.append(pg.info.name); 8082 } 8083 } 8084 } 8085 if (r != null) { 8086 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8087 } 8088 8089 N = pkg.permissions.size(); 8090 r = null; 8091 for (i=0; i<N; i++) { 8092 PackageParser.Permission p = pkg.permissions.get(i); 8093 8094 // Assume by default that we did not install this permission into the system. 8095 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8096 8097 // Now that permission groups have a special meaning, we ignore permission 8098 // groups for legacy apps to prevent unexpected behavior. In particular, 8099 // permissions for one app being granted to someone just becase they happen 8100 // to be in a group defined by another app (before this had no implications). 8101 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8102 p.group = mPermissionGroups.get(p.info.group); 8103 // Warn for a permission in an unknown group. 8104 if (p.info.group != null && p.group == null) { 8105 Slog.w(TAG, "Permission " + p.info.name + " from package " 8106 + p.info.packageName + " in an unknown group " + p.info.group); 8107 } 8108 } 8109 8110 ArrayMap<String, BasePermission> permissionMap = 8111 p.tree ? mSettings.mPermissionTrees 8112 : mSettings.mPermissions; 8113 BasePermission bp = permissionMap.get(p.info.name); 8114 8115 // Allow system apps to redefine non-system permissions 8116 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8117 final boolean currentOwnerIsSystem = (bp.perm != null 8118 && isSystemApp(bp.perm.owner)); 8119 if (isSystemApp(p.owner)) { 8120 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8121 // It's a built-in permission and no owner, take ownership now 8122 bp.packageSetting = pkgSetting; 8123 bp.perm = p; 8124 bp.uid = pkg.applicationInfo.uid; 8125 bp.sourcePackage = p.info.packageName; 8126 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8127 } else if (!currentOwnerIsSystem) { 8128 String msg = "New decl " + p.owner + " of permission " 8129 + p.info.name + " is system; overriding " + bp.sourcePackage; 8130 reportSettingsProblem(Log.WARN, msg); 8131 bp = null; 8132 } 8133 } 8134 } 8135 8136 if (bp == null) { 8137 bp = new BasePermission(p.info.name, p.info.packageName, 8138 BasePermission.TYPE_NORMAL); 8139 permissionMap.put(p.info.name, bp); 8140 } 8141 8142 if (bp.perm == null) { 8143 if (bp.sourcePackage == null 8144 || bp.sourcePackage.equals(p.info.packageName)) { 8145 BasePermission tree = findPermissionTreeLP(p.info.name); 8146 if (tree == null 8147 || tree.sourcePackage.equals(p.info.packageName)) { 8148 bp.packageSetting = pkgSetting; 8149 bp.perm = p; 8150 bp.uid = pkg.applicationInfo.uid; 8151 bp.sourcePackage = p.info.packageName; 8152 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8153 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8154 if (r == null) { 8155 r = new StringBuilder(256); 8156 } else { 8157 r.append(' '); 8158 } 8159 r.append(p.info.name); 8160 } 8161 } else { 8162 Slog.w(TAG, "Permission " + p.info.name + " from package " 8163 + p.info.packageName + " ignored: base tree " 8164 + tree.name + " is from package " 8165 + tree.sourcePackage); 8166 } 8167 } else { 8168 Slog.w(TAG, "Permission " + p.info.name + " from package " 8169 + p.info.packageName + " ignored: original from " 8170 + bp.sourcePackage); 8171 } 8172 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8173 if (r == null) { 8174 r = new StringBuilder(256); 8175 } else { 8176 r.append(' '); 8177 } 8178 r.append("DUP:"); 8179 r.append(p.info.name); 8180 } 8181 if (bp.perm == p) { 8182 bp.protectionLevel = p.info.protectionLevel; 8183 } 8184 } 8185 8186 if (r != null) { 8187 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8188 } 8189 8190 N = pkg.instrumentation.size(); 8191 r = null; 8192 for (i=0; i<N; i++) { 8193 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8194 a.info.packageName = pkg.applicationInfo.packageName; 8195 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8196 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8197 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8198 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8199 a.info.dataDir = pkg.applicationInfo.dataDir; 8200 a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir; 8201 a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir; 8202 8203 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8204 // need other information about the application, like the ABI and what not ? 8205 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8206 mInstrumentation.put(a.getComponentName(), a); 8207 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8208 if (r == null) { 8209 r = new StringBuilder(256); 8210 } else { 8211 r.append(' '); 8212 } 8213 r.append(a.info.name); 8214 } 8215 } 8216 if (r != null) { 8217 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8218 } 8219 8220 if (pkg.protectedBroadcasts != null) { 8221 N = pkg.protectedBroadcasts.size(); 8222 for (i=0; i<N; i++) { 8223 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8224 } 8225 } 8226 8227 pkgSetting.setTimeStamp(scanFileTime); 8228 8229 // Create idmap files for pairs of (packages, overlay packages). 8230 // Note: "android", ie framework-res.apk, is handled by native layers. 8231 if (pkg.mOverlayTarget != null) { 8232 // This is an overlay package. 8233 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8234 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8235 mOverlays.put(pkg.mOverlayTarget, 8236 new ArrayMap<String, PackageParser.Package>()); 8237 } 8238 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8239 map.put(pkg.packageName, pkg); 8240 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8241 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8242 createIdmapFailed = true; 8243 } 8244 } 8245 } else if (mOverlays.containsKey(pkg.packageName) && 8246 !pkg.packageName.equals("android")) { 8247 // This is a regular package, with one or more known overlay packages. 8248 createIdmapsForPackageLI(pkg); 8249 } 8250 } 8251 8252 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8253 8254 if (createIdmapFailed) { 8255 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8256 "scanPackageLI failed to createIdmap"); 8257 } 8258 return pkg; 8259 } 8260 8261 /** 8262 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8263 * is derived purely on the basis of the contents of {@code scanFile} and 8264 * {@code cpuAbiOverride}. 8265 * 8266 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8267 */ 8268 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8269 String cpuAbiOverride, boolean extractLibs) 8270 throws PackageManagerException { 8271 // TODO: We can probably be smarter about this stuff. For installed apps, 8272 // we can calculate this information at install time once and for all. For 8273 // system apps, we can probably assume that this information doesn't change 8274 // after the first boot scan. As things stand, we do lots of unnecessary work. 8275 8276 // Give ourselves some initial paths; we'll come back for another 8277 // pass once we've determined ABI below. 8278 setNativeLibraryPaths(pkg); 8279 8280 // We would never need to extract libs for forward-locked and external packages, 8281 // since the container service will do it for us. We shouldn't attempt to 8282 // extract libs from system app when it was not updated. 8283 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8284 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8285 extractLibs = false; 8286 } 8287 8288 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8289 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8290 8291 NativeLibraryHelper.Handle handle = null; 8292 try { 8293 handle = NativeLibraryHelper.Handle.create(pkg); 8294 // TODO(multiArch): This can be null for apps that didn't go through the 8295 // usual installation process. We can calculate it again, like we 8296 // do during install time. 8297 // 8298 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8299 // unnecessary. 8300 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8301 8302 // Null out the abis so that they can be recalculated. 8303 pkg.applicationInfo.primaryCpuAbi = null; 8304 pkg.applicationInfo.secondaryCpuAbi = null; 8305 if (isMultiArch(pkg.applicationInfo)) { 8306 // Warn if we've set an abiOverride for multi-lib packages.. 8307 // By definition, we need to copy both 32 and 64 bit libraries for 8308 // such packages. 8309 if (pkg.cpuAbiOverride != null 8310 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8311 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8312 } 8313 8314 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8315 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8316 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8317 if (extractLibs) { 8318 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8319 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8320 useIsaSpecificSubdirs); 8321 } else { 8322 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8323 } 8324 } 8325 8326 maybeThrowExceptionForMultiArchCopy( 8327 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8328 8329 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8330 if (extractLibs) { 8331 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8332 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8333 useIsaSpecificSubdirs); 8334 } else { 8335 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8336 } 8337 } 8338 8339 maybeThrowExceptionForMultiArchCopy( 8340 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8341 8342 if (abi64 >= 0) { 8343 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8344 } 8345 8346 if (abi32 >= 0) { 8347 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8348 if (abi64 >= 0) { 8349 if (cpuAbiOverride == null && pkg.use32bitAbi) { 8350 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8351 pkg.applicationInfo.primaryCpuAbi = abi; 8352 } else { 8353 pkg.applicationInfo.secondaryCpuAbi = abi; 8354 } 8355 } else { 8356 pkg.applicationInfo.primaryCpuAbi = abi; 8357 } 8358 } 8359 8360 } else { 8361 String[] abiList = (cpuAbiOverride != null) ? 8362 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8363 8364 // Enable gross and lame hacks for apps that are built with old 8365 // SDK tools. We must scan their APKs for renderscript bitcode and 8366 // not launch them if it's present. Don't bother checking on devices 8367 // that don't have 64 bit support. 8368 boolean needsRenderScriptOverride = false; 8369 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8370 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8371 abiList = Build.SUPPORTED_32_BIT_ABIS; 8372 needsRenderScriptOverride = true; 8373 } 8374 8375 final int copyRet; 8376 if (extractLibs) { 8377 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8378 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8379 } else { 8380 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8381 } 8382 8383 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8384 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8385 "Error unpackaging native libs for app, errorCode=" + copyRet); 8386 } 8387 8388 if (copyRet >= 0) { 8389 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8390 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8391 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8392 } else if (needsRenderScriptOverride) { 8393 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8394 } 8395 } 8396 } catch (IOException ioe) { 8397 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8398 } finally { 8399 IoUtils.closeQuietly(handle); 8400 } 8401 8402 // Now that we've calculated the ABIs and determined if it's an internal app, 8403 // we will go ahead and populate the nativeLibraryPath. 8404 setNativeLibraryPaths(pkg); 8405 } 8406 8407 /** 8408 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8409 * i.e, so that all packages can be run inside a single process if required. 8410 * 8411 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8412 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8413 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8414 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8415 * updating a package that belongs to a shared user. 8416 * 8417 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8418 * adds unnecessary complexity. 8419 */ 8420 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8421 PackageParser.Package scannedPackage, boolean bootComplete) { 8422 String requiredInstructionSet = null; 8423 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8424 requiredInstructionSet = VMRuntime.getInstructionSet( 8425 scannedPackage.applicationInfo.primaryCpuAbi); 8426 } 8427 8428 PackageSetting requirer = null; 8429 for (PackageSetting ps : packagesForUser) { 8430 // If packagesForUser contains scannedPackage, we skip it. This will happen 8431 // when scannedPackage is an update of an existing package. Without this check, 8432 // we will never be able to change the ABI of any package belonging to a shared 8433 // user, even if it's compatible with other packages. 8434 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8435 if (ps.primaryCpuAbiString == null) { 8436 continue; 8437 } 8438 8439 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8440 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8441 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8442 // this but there's not much we can do. 8443 String errorMessage = "Instruction set mismatch, " 8444 + ((requirer == null) ? "[caller]" : requirer) 8445 + " requires " + requiredInstructionSet + " whereas " + ps 8446 + " requires " + instructionSet; 8447 Slog.w(TAG, errorMessage); 8448 } 8449 8450 if (requiredInstructionSet == null) { 8451 requiredInstructionSet = instructionSet; 8452 requirer = ps; 8453 } 8454 } 8455 } 8456 8457 if (requiredInstructionSet != null) { 8458 String adjustedAbi; 8459 if (requirer != null) { 8460 // requirer != null implies that either scannedPackage was null or that scannedPackage 8461 // did not require an ABI, in which case we have to adjust scannedPackage to match 8462 // the ABI of the set (which is the same as requirer's ABI) 8463 adjustedAbi = requirer.primaryCpuAbiString; 8464 if (scannedPackage != null) { 8465 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8466 } 8467 } else { 8468 // requirer == null implies that we're updating all ABIs in the set to 8469 // match scannedPackage. 8470 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8471 } 8472 8473 for (PackageSetting ps : packagesForUser) { 8474 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8475 if (ps.primaryCpuAbiString != null) { 8476 continue; 8477 } 8478 8479 ps.primaryCpuAbiString = adjustedAbi; 8480 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8481 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8482 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8483 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8484 + " (requirer=" 8485 + (requirer == null ? "null" : requirer.pkg.packageName) 8486 + ", scannedPackage=" 8487 + (scannedPackage != null ? scannedPackage.packageName : "null") 8488 + ")"); 8489 try { 8490 mInstaller.rmdex(ps.codePathString, 8491 getDexCodeInstructionSet(getPreferredInstructionSet())); 8492 } catch (InstallerException ignored) { 8493 } 8494 } 8495 } 8496 } 8497 } 8498 } 8499 8500 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8501 synchronized (mPackages) { 8502 mResolverReplaced = true; 8503 // Set up information for custom user intent resolution activity. 8504 mResolveActivity.applicationInfo = pkg.applicationInfo; 8505 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8506 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8507 mResolveActivity.processName = pkg.applicationInfo.packageName; 8508 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8509 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8510 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8511 mResolveActivity.theme = 0; 8512 mResolveActivity.exported = true; 8513 mResolveActivity.enabled = true; 8514 mResolveInfo.activityInfo = mResolveActivity; 8515 mResolveInfo.priority = 0; 8516 mResolveInfo.preferredOrder = 0; 8517 mResolveInfo.match = 0; 8518 mResolveComponentName = mCustomResolverComponentName; 8519 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8520 mResolveComponentName); 8521 } 8522 } 8523 8524 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8525 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8526 8527 // Set up information for ephemeral installer activity 8528 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8529 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8530 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8531 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8532 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8533 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8534 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8535 mEphemeralInstallerActivity.theme = 0; 8536 mEphemeralInstallerActivity.exported = true; 8537 mEphemeralInstallerActivity.enabled = true; 8538 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8539 mEphemeralInstallerInfo.priority = 0; 8540 mEphemeralInstallerInfo.preferredOrder = 0; 8541 mEphemeralInstallerInfo.match = 0; 8542 8543 if (DEBUG_EPHEMERAL) { 8544 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8545 } 8546 } 8547 8548 private static String calculateBundledApkRoot(final String codePathString) { 8549 final File codePath = new File(codePathString); 8550 final File codeRoot; 8551 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8552 codeRoot = Environment.getRootDirectory(); 8553 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8554 codeRoot = Environment.getOemDirectory(); 8555 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8556 codeRoot = Environment.getVendorDirectory(); 8557 } else { 8558 // Unrecognized code path; take its top real segment as the apk root: 8559 // e.g. /something/app/blah.apk => /something 8560 try { 8561 File f = codePath.getCanonicalFile(); 8562 File parent = f.getParentFile(); // non-null because codePath is a file 8563 File tmp; 8564 while ((tmp = parent.getParentFile()) != null) { 8565 f = parent; 8566 parent = tmp; 8567 } 8568 codeRoot = f; 8569 Slog.w(TAG, "Unrecognized code path " 8570 + codePath + " - using " + codeRoot); 8571 } catch (IOException e) { 8572 // Can't canonicalize the code path -- shenanigans? 8573 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8574 return Environment.getRootDirectory().getPath(); 8575 } 8576 } 8577 return codeRoot.getPath(); 8578 } 8579 8580 /** 8581 * Derive and set the location of native libraries for the given package, 8582 * which varies depending on where and how the package was installed. 8583 */ 8584 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8585 final ApplicationInfo info = pkg.applicationInfo; 8586 final String codePath = pkg.codePath; 8587 final File codeFile = new File(codePath); 8588 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8589 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8590 8591 info.nativeLibraryRootDir = null; 8592 info.nativeLibraryRootRequiresIsa = false; 8593 info.nativeLibraryDir = null; 8594 info.secondaryNativeLibraryDir = null; 8595 8596 if (isApkFile(codeFile)) { 8597 // Monolithic install 8598 if (bundledApp) { 8599 // If "/system/lib64/apkname" exists, assume that is the per-package 8600 // native library directory to use; otherwise use "/system/lib/apkname". 8601 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8602 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8603 getPrimaryInstructionSet(info)); 8604 8605 // This is a bundled system app so choose the path based on the ABI. 8606 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8607 // is just the default path. 8608 final String apkName = deriveCodePathName(codePath); 8609 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8610 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8611 apkName).getAbsolutePath(); 8612 8613 if (info.secondaryCpuAbi != null) { 8614 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8615 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8616 secondaryLibDir, apkName).getAbsolutePath(); 8617 } 8618 } else if (asecApp) { 8619 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8620 .getAbsolutePath(); 8621 } else { 8622 final String apkName = deriveCodePathName(codePath); 8623 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8624 .getAbsolutePath(); 8625 } 8626 8627 info.nativeLibraryRootRequiresIsa = false; 8628 info.nativeLibraryDir = info.nativeLibraryRootDir; 8629 } else { 8630 // Cluster install 8631 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8632 info.nativeLibraryRootRequiresIsa = true; 8633 8634 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8635 getPrimaryInstructionSet(info)).getAbsolutePath(); 8636 8637 if (info.secondaryCpuAbi != null) { 8638 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8639 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8640 } 8641 } 8642 } 8643 8644 /** 8645 * Calculate the abis and roots for a bundled app. These can uniquely 8646 * be determined from the contents of the system partition, i.e whether 8647 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8648 * of this information, and instead assume that the system was built 8649 * sensibly. 8650 */ 8651 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8652 PackageSetting pkgSetting) { 8653 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8654 8655 // If "/system/lib64/apkname" exists, assume that is the per-package 8656 // native library directory to use; otherwise use "/system/lib/apkname". 8657 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8658 setBundledAppAbi(pkg, apkRoot, apkName); 8659 // pkgSetting might be null during rescan following uninstall of updates 8660 // to a bundled app, so accommodate that possibility. The settings in 8661 // that case will be established later from the parsed package. 8662 // 8663 // If the settings aren't null, sync them up with what we've just derived. 8664 // note that apkRoot isn't stored in the package settings. 8665 if (pkgSetting != null) { 8666 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8667 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8668 } 8669 } 8670 8671 /** 8672 * Deduces the ABI of a bundled app and sets the relevant fields on the 8673 * parsed pkg object. 8674 * 8675 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8676 * under which system libraries are installed. 8677 * @param apkName the name of the installed package. 8678 */ 8679 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8680 final File codeFile = new File(pkg.codePath); 8681 8682 final boolean has64BitLibs; 8683 final boolean has32BitLibs; 8684 if (isApkFile(codeFile)) { 8685 // Monolithic install 8686 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8687 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8688 } else { 8689 // Cluster install 8690 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8691 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8692 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8693 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8694 has64BitLibs = (new File(rootDir, isa)).exists(); 8695 } else { 8696 has64BitLibs = false; 8697 } 8698 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8699 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8700 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8701 has32BitLibs = (new File(rootDir, isa)).exists(); 8702 } else { 8703 has32BitLibs = false; 8704 } 8705 } 8706 8707 if (has64BitLibs && !has32BitLibs) { 8708 // The package has 64 bit libs, but not 32 bit libs. Its primary 8709 // ABI should be 64 bit. We can safely assume here that the bundled 8710 // native libraries correspond to the most preferred ABI in the list. 8711 8712 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8713 pkg.applicationInfo.secondaryCpuAbi = null; 8714 } else if (has32BitLibs && !has64BitLibs) { 8715 // The package has 32 bit libs but not 64 bit libs. Its primary 8716 // ABI should be 32 bit. 8717 8718 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8719 pkg.applicationInfo.secondaryCpuAbi = null; 8720 } else if (has32BitLibs && has64BitLibs) { 8721 // The application has both 64 and 32 bit bundled libraries. We check 8722 // here that the app declares multiArch support, and warn if it doesn't. 8723 // 8724 // We will be lenient here and record both ABIs. The primary will be the 8725 // ABI that's higher on the list, i.e, a device that's configured to prefer 8726 // 64 bit apps will see a 64 bit primary ABI, 8727 8728 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8729 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 8730 } 8731 8732 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8733 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8734 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8735 } else { 8736 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8737 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8738 } 8739 } else { 8740 pkg.applicationInfo.primaryCpuAbi = null; 8741 pkg.applicationInfo.secondaryCpuAbi = null; 8742 } 8743 } 8744 8745 private void killPackage(PackageParser.Package pkg, String reason) { 8746 // Kill the parent package 8747 killApplication(pkg.packageName, pkg.applicationInfo.uid, reason); 8748 // Kill the child packages 8749 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8750 for (int i = 0; i < childCount; i++) { 8751 PackageParser.Package childPkg = pkg.childPackages.get(i); 8752 killApplication(childPkg.packageName, childPkg.applicationInfo.uid, reason); 8753 } 8754 } 8755 8756 private void killApplication(String pkgName, int appId, String reason) { 8757 // Request the ActivityManager to kill the process(only for existing packages) 8758 // so that we do not end up in a confused state while the user is still using the older 8759 // version of the application while the new one gets installed. 8760 IActivityManager am = ActivityManagerNative.getDefault(); 8761 if (am != null) { 8762 try { 8763 am.killApplicationWithAppId(pkgName, appId, reason); 8764 } catch (RemoteException e) { 8765 } 8766 } 8767 } 8768 8769 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 8770 // Remove the parent package setting 8771 PackageSetting ps = (PackageSetting) pkg.mExtras; 8772 if (ps != null) { 8773 removePackageLI(ps, chatty); 8774 } 8775 // Remove the child package setting 8776 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8777 for (int i = 0; i < childCount; i++) { 8778 PackageParser.Package childPkg = pkg.childPackages.get(i); 8779 ps = (PackageSetting) childPkg.mExtras; 8780 if (ps != null) { 8781 removePackageLI(ps, chatty); 8782 } 8783 } 8784 } 8785 8786 void removePackageLI(PackageSetting ps, boolean chatty) { 8787 if (DEBUG_INSTALL) { 8788 if (chatty) 8789 Log.d(TAG, "Removing package " + ps.name); 8790 } 8791 8792 // writer 8793 synchronized (mPackages) { 8794 mPackages.remove(ps.name); 8795 final PackageParser.Package pkg = ps.pkg; 8796 if (pkg != null) { 8797 cleanPackageDataStructuresLILPw(pkg, chatty); 8798 } 8799 } 8800 } 8801 8802 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8803 if (DEBUG_INSTALL) { 8804 if (chatty) 8805 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8806 } 8807 8808 // writer 8809 synchronized (mPackages) { 8810 // Remove the parent package 8811 mPackages.remove(pkg.applicationInfo.packageName); 8812 cleanPackageDataStructuresLILPw(pkg, chatty); 8813 8814 // Remove the child packages 8815 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8816 for (int i = 0; i < childCount; i++) { 8817 PackageParser.Package childPkg = pkg.childPackages.get(i); 8818 mPackages.remove(childPkg.applicationInfo.packageName); 8819 cleanPackageDataStructuresLILPw(childPkg, chatty); 8820 } 8821 } 8822 } 8823 8824 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8825 int N = pkg.providers.size(); 8826 StringBuilder r = null; 8827 int i; 8828 for (i=0; i<N; i++) { 8829 PackageParser.Provider p = pkg.providers.get(i); 8830 mProviders.removeProvider(p); 8831 if (p.info.authority == null) { 8832 8833 /* There was another ContentProvider with this authority when 8834 * this app was installed so this authority is null, 8835 * Ignore it as we don't have to unregister the provider. 8836 */ 8837 continue; 8838 } 8839 String names[] = p.info.authority.split(";"); 8840 for (int j = 0; j < names.length; j++) { 8841 if (mProvidersByAuthority.get(names[j]) == p) { 8842 mProvidersByAuthority.remove(names[j]); 8843 if (DEBUG_REMOVE) { 8844 if (chatty) 8845 Log.d(TAG, "Unregistered content provider: " + names[j] 8846 + ", className = " + p.info.name + ", isSyncable = " 8847 + p.info.isSyncable); 8848 } 8849 } 8850 } 8851 if (DEBUG_REMOVE && chatty) { 8852 if (r == null) { 8853 r = new StringBuilder(256); 8854 } else { 8855 r.append(' '); 8856 } 8857 r.append(p.info.name); 8858 } 8859 } 8860 if (r != null) { 8861 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8862 } 8863 8864 N = pkg.services.size(); 8865 r = null; 8866 for (i=0; i<N; i++) { 8867 PackageParser.Service s = pkg.services.get(i); 8868 mServices.removeService(s); 8869 if (chatty) { 8870 if (r == null) { 8871 r = new StringBuilder(256); 8872 } else { 8873 r.append(' '); 8874 } 8875 r.append(s.info.name); 8876 } 8877 } 8878 if (r != null) { 8879 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8880 } 8881 8882 N = pkg.receivers.size(); 8883 r = null; 8884 for (i=0; i<N; i++) { 8885 PackageParser.Activity a = pkg.receivers.get(i); 8886 mReceivers.removeActivity(a, "receiver"); 8887 if (DEBUG_REMOVE && chatty) { 8888 if (r == null) { 8889 r = new StringBuilder(256); 8890 } else { 8891 r.append(' '); 8892 } 8893 r.append(a.info.name); 8894 } 8895 } 8896 if (r != null) { 8897 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8898 } 8899 8900 N = pkg.activities.size(); 8901 r = null; 8902 for (i=0; i<N; i++) { 8903 PackageParser.Activity a = pkg.activities.get(i); 8904 mActivities.removeActivity(a, "activity"); 8905 if (DEBUG_REMOVE && chatty) { 8906 if (r == null) { 8907 r = new StringBuilder(256); 8908 } else { 8909 r.append(' '); 8910 } 8911 r.append(a.info.name); 8912 } 8913 } 8914 if (r != null) { 8915 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8916 } 8917 8918 N = pkg.permissions.size(); 8919 r = null; 8920 for (i=0; i<N; i++) { 8921 PackageParser.Permission p = pkg.permissions.get(i); 8922 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8923 if (bp == null) { 8924 bp = mSettings.mPermissionTrees.get(p.info.name); 8925 } 8926 if (bp != null && bp.perm == p) { 8927 bp.perm = null; 8928 if (DEBUG_REMOVE && chatty) { 8929 if (r == null) { 8930 r = new StringBuilder(256); 8931 } else { 8932 r.append(' '); 8933 } 8934 r.append(p.info.name); 8935 } 8936 } 8937 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8938 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 8939 if (appOpPkgs != null) { 8940 appOpPkgs.remove(pkg.packageName); 8941 } 8942 } 8943 } 8944 if (r != null) { 8945 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8946 } 8947 8948 N = pkg.requestedPermissions.size(); 8949 r = null; 8950 for (i=0; i<N; i++) { 8951 String perm = pkg.requestedPermissions.get(i); 8952 BasePermission bp = mSettings.mPermissions.get(perm); 8953 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8954 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 8955 if (appOpPkgs != null) { 8956 appOpPkgs.remove(pkg.packageName); 8957 if (appOpPkgs.isEmpty()) { 8958 mAppOpPermissionPackages.remove(perm); 8959 } 8960 } 8961 } 8962 } 8963 if (r != null) { 8964 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8965 } 8966 8967 N = pkg.instrumentation.size(); 8968 r = null; 8969 for (i=0; i<N; i++) { 8970 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8971 mInstrumentation.remove(a.getComponentName()); 8972 if (DEBUG_REMOVE && chatty) { 8973 if (r == null) { 8974 r = new StringBuilder(256); 8975 } else { 8976 r.append(' '); 8977 } 8978 r.append(a.info.name); 8979 } 8980 } 8981 if (r != null) { 8982 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8983 } 8984 8985 r = null; 8986 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8987 // Only system apps can hold shared libraries. 8988 if (pkg.libraryNames != null) { 8989 for (i=0; i<pkg.libraryNames.size(); i++) { 8990 String name = pkg.libraryNames.get(i); 8991 SharedLibraryEntry cur = mSharedLibraries.get(name); 8992 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8993 mSharedLibraries.remove(name); 8994 if (DEBUG_REMOVE && chatty) { 8995 if (r == null) { 8996 r = new StringBuilder(256); 8997 } else { 8998 r.append(' '); 8999 } 9000 r.append(name); 9001 } 9002 } 9003 } 9004 } 9005 } 9006 if (r != null) { 9007 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9008 } 9009 } 9010 9011 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9012 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9013 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9014 return true; 9015 } 9016 } 9017 return false; 9018 } 9019 9020 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9021 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9022 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9023 9024 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9025 // Update the parent permissions 9026 updatePermissionsLPw(pkg.packageName, pkg, flags); 9027 // Update the child permissions 9028 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9029 for (int i = 0; i < childCount; i++) { 9030 PackageParser.Package childPkg = pkg.childPackages.get(i); 9031 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9032 } 9033 } 9034 9035 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9036 int flags) { 9037 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9038 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9039 } 9040 9041 private void updatePermissionsLPw(String changingPkg, 9042 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9043 // Make sure there are no dangling permission trees. 9044 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9045 while (it.hasNext()) { 9046 final BasePermission bp = it.next(); 9047 if (bp.packageSetting == null) { 9048 // We may not yet have parsed the package, so just see if 9049 // we still know about its settings. 9050 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9051 } 9052 if (bp.packageSetting == null) { 9053 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9054 + " from package " + bp.sourcePackage); 9055 it.remove(); 9056 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9057 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9058 Slog.i(TAG, "Removing old permission tree: " + bp.name 9059 + " from package " + bp.sourcePackage); 9060 flags |= UPDATE_PERMISSIONS_ALL; 9061 it.remove(); 9062 } 9063 } 9064 } 9065 9066 // Make sure all dynamic permissions have been assigned to a package, 9067 // and make sure there are no dangling permissions. 9068 it = mSettings.mPermissions.values().iterator(); 9069 while (it.hasNext()) { 9070 final BasePermission bp = it.next(); 9071 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9072 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9073 + bp.name + " pkg=" + bp.sourcePackage 9074 + " info=" + bp.pendingInfo); 9075 if (bp.packageSetting == null && bp.pendingInfo != null) { 9076 final BasePermission tree = findPermissionTreeLP(bp.name); 9077 if (tree != null && tree.perm != null) { 9078 bp.packageSetting = tree.packageSetting; 9079 bp.perm = new PackageParser.Permission(tree.perm.owner, 9080 new PermissionInfo(bp.pendingInfo)); 9081 bp.perm.info.packageName = tree.perm.info.packageName; 9082 bp.perm.info.name = bp.name; 9083 bp.uid = tree.uid; 9084 } 9085 } 9086 } 9087 if (bp.packageSetting == null) { 9088 // We may not yet have parsed the package, so just see if 9089 // we still know about its settings. 9090 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9091 } 9092 if (bp.packageSetting == null) { 9093 Slog.w(TAG, "Removing dangling permission: " + bp.name 9094 + " from package " + bp.sourcePackage); 9095 it.remove(); 9096 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9097 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9098 Slog.i(TAG, "Removing old permission: " + bp.name 9099 + " from package " + bp.sourcePackage); 9100 flags |= UPDATE_PERMISSIONS_ALL; 9101 it.remove(); 9102 } 9103 } 9104 } 9105 9106 // Now update the permissions for all packages, in particular 9107 // replace the granted permissions of the system packages. 9108 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9109 for (PackageParser.Package pkg : mPackages.values()) { 9110 if (pkg != pkgInfo) { 9111 // Only replace for packages on requested volume 9112 final String volumeUuid = getVolumeUuidForPackage(pkg); 9113 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9114 && Objects.equals(replaceVolumeUuid, volumeUuid); 9115 grantPermissionsLPw(pkg, replace, changingPkg); 9116 } 9117 } 9118 } 9119 9120 if (pkgInfo != null) { 9121 // Only replace for packages on requested volume 9122 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9123 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9124 && Objects.equals(replaceVolumeUuid, volumeUuid); 9125 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9126 } 9127 } 9128 9129 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9130 String packageOfInterest) { 9131 // IMPORTANT: There are two types of permissions: install and runtime. 9132 // Install time permissions are granted when the app is installed to 9133 // all device users and users added in the future. Runtime permissions 9134 // are granted at runtime explicitly to specific users. Normal and signature 9135 // protected permissions are install time permissions. Dangerous permissions 9136 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9137 // otherwise they are runtime permissions. This function does not manage 9138 // runtime permissions except for the case an app targeting Lollipop MR1 9139 // being upgraded to target a newer SDK, in which case dangerous permissions 9140 // are transformed from install time to runtime ones. 9141 9142 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9143 if (ps == null) { 9144 return; 9145 } 9146 9147 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9148 9149 PermissionsState permissionsState = ps.getPermissionsState(); 9150 PermissionsState origPermissions = permissionsState; 9151 9152 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9153 9154 boolean runtimePermissionsRevoked = false; 9155 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9156 9157 boolean changedInstallPermission = false; 9158 9159 if (replace) { 9160 ps.installPermissionsFixed = false; 9161 if (!ps.isSharedUser()) { 9162 origPermissions = new PermissionsState(permissionsState); 9163 permissionsState.reset(); 9164 } else { 9165 // We need to know only about runtime permission changes since the 9166 // calling code always writes the install permissions state but 9167 // the runtime ones are written only if changed. The only cases of 9168 // changed runtime permissions here are promotion of an install to 9169 // runtime and revocation of a runtime from a shared user. 9170 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9171 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9172 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9173 runtimePermissionsRevoked = true; 9174 } 9175 } 9176 } 9177 9178 permissionsState.setGlobalGids(mGlobalGids); 9179 9180 final int N = pkg.requestedPermissions.size(); 9181 for (int i=0; i<N; i++) { 9182 final String name = pkg.requestedPermissions.get(i); 9183 final BasePermission bp = mSettings.mPermissions.get(name); 9184 9185 if (DEBUG_INSTALL) { 9186 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9187 } 9188 9189 if (bp == null || bp.packageSetting == null) { 9190 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9191 Slog.w(TAG, "Unknown permission " + name 9192 + " in package " + pkg.packageName); 9193 } 9194 continue; 9195 } 9196 9197 final String perm = bp.name; 9198 boolean allowedSig = false; 9199 int grant = GRANT_DENIED; 9200 9201 // Keep track of app op permissions. 9202 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9203 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9204 if (pkgs == null) { 9205 pkgs = new ArraySet<>(); 9206 mAppOpPermissionPackages.put(bp.name, pkgs); 9207 } 9208 pkgs.add(pkg.packageName); 9209 } 9210 9211 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9212 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9213 >= Build.VERSION_CODES.M; 9214 switch (level) { 9215 case PermissionInfo.PROTECTION_NORMAL: { 9216 // For all apps normal permissions are install time ones. 9217 grant = GRANT_INSTALL; 9218 } break; 9219 9220 case PermissionInfo.PROTECTION_DANGEROUS: { 9221 // If a permission review is required for legacy apps we represent 9222 // their permissions as always granted runtime ones since we need 9223 // to keep the review required permission flag per user while an 9224 // install permission's state is shared across all users. 9225 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9226 // For legacy apps dangerous permissions are install time ones. 9227 grant = GRANT_INSTALL; 9228 } else if (origPermissions.hasInstallPermission(bp.name)) { 9229 // For legacy apps that became modern, install becomes runtime. 9230 grant = GRANT_UPGRADE; 9231 } else if (mPromoteSystemApps 9232 && isSystemApp(ps) 9233 && mExistingSystemPackages.contains(ps.name)) { 9234 // For legacy system apps, install becomes runtime. 9235 // We cannot check hasInstallPermission() for system apps since those 9236 // permissions were granted implicitly and not persisted pre-M. 9237 grant = GRANT_UPGRADE; 9238 } else { 9239 // For modern apps keep runtime permissions unchanged. 9240 grant = GRANT_RUNTIME; 9241 } 9242 } break; 9243 9244 case PermissionInfo.PROTECTION_SIGNATURE: { 9245 // For all apps signature permissions are install time ones. 9246 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9247 if (allowedSig) { 9248 grant = GRANT_INSTALL; 9249 } 9250 } break; 9251 } 9252 9253 if (DEBUG_INSTALL) { 9254 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9255 } 9256 9257 if (grant != GRANT_DENIED) { 9258 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9259 // If this is an existing, non-system package, then 9260 // we can't add any new permissions to it. 9261 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9262 // Except... if this is a permission that was added 9263 // to the platform (note: need to only do this when 9264 // updating the platform). 9265 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9266 grant = GRANT_DENIED; 9267 } 9268 } 9269 } 9270 9271 switch (grant) { 9272 case GRANT_INSTALL: { 9273 // Revoke this as runtime permission to handle the case of 9274 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 9275 for (int userId : UserManagerService.getInstance().getUserIds()) { 9276 if (origPermissions.getRuntimePermissionState( 9277 bp.name, userId) != null) { 9278 // Revoke the runtime permission and clear the flags. 9279 origPermissions.revokeRuntimePermission(bp, userId); 9280 origPermissions.updatePermissionFlags(bp, userId, 9281 PackageManager.MASK_PERMISSION_FLAGS, 0); 9282 // If we revoked a permission permission, we have to write. 9283 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9284 changedRuntimePermissionUserIds, userId); 9285 } 9286 } 9287 // Grant an install permission. 9288 if (permissionsState.grantInstallPermission(bp) != 9289 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9290 changedInstallPermission = true; 9291 } 9292 } break; 9293 9294 case GRANT_RUNTIME: { 9295 // Grant previously granted runtime permissions. 9296 for (int userId : UserManagerService.getInstance().getUserIds()) { 9297 PermissionState permissionState = origPermissions 9298 .getRuntimePermissionState(bp.name, userId); 9299 int flags = permissionState != null 9300 ? permissionState.getFlags() : 0; 9301 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9302 if (permissionsState.grantRuntimePermission(bp, userId) == 9303 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9304 // If we cannot put the permission as it was, we have to write. 9305 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9306 changedRuntimePermissionUserIds, userId); 9307 } 9308 // If the app supports runtime permissions no need for a review. 9309 if (Build.PERMISSIONS_REVIEW_REQUIRED 9310 && appSupportsRuntimePermissions 9311 && (flags & PackageManager 9312 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9313 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9314 // Since we changed the flags, we have to write. 9315 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9316 changedRuntimePermissionUserIds, userId); 9317 } 9318 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9319 && !appSupportsRuntimePermissions) { 9320 // For legacy apps that need a permission review, every new 9321 // runtime permission is granted but it is pending a review. 9322 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9323 permissionsState.grantRuntimePermission(bp, userId); 9324 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9325 // We changed the permission and flags, hence have to write. 9326 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9327 changedRuntimePermissionUserIds, userId); 9328 } 9329 } 9330 // Propagate the permission flags. 9331 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9332 } 9333 } break; 9334 9335 case GRANT_UPGRADE: { 9336 // Grant runtime permissions for a previously held install permission. 9337 PermissionState permissionState = origPermissions 9338 .getInstallPermissionState(bp.name); 9339 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9340 9341 if (origPermissions.revokeInstallPermission(bp) 9342 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9343 // We will be transferring the permission flags, so clear them. 9344 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9345 PackageManager.MASK_PERMISSION_FLAGS, 0); 9346 changedInstallPermission = true; 9347 } 9348 9349 // If the permission is not to be promoted to runtime we ignore it and 9350 // also its other flags as they are not applicable to install permissions. 9351 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9352 for (int userId : currentUserIds) { 9353 if (permissionsState.grantRuntimePermission(bp, userId) != 9354 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9355 // Transfer the permission flags. 9356 permissionsState.updatePermissionFlags(bp, userId, 9357 flags, flags); 9358 // If we granted the permission, we have to write. 9359 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9360 changedRuntimePermissionUserIds, userId); 9361 } 9362 } 9363 } 9364 } break; 9365 9366 default: { 9367 if (packageOfInterest == null 9368 || packageOfInterest.equals(pkg.packageName)) { 9369 Slog.w(TAG, "Not granting permission " + perm 9370 + " to package " + pkg.packageName 9371 + " because it was previously installed without"); 9372 } 9373 } break; 9374 } 9375 } else { 9376 if (permissionsState.revokeInstallPermission(bp) != 9377 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9378 // Also drop the permission flags. 9379 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9380 PackageManager.MASK_PERMISSION_FLAGS, 0); 9381 changedInstallPermission = true; 9382 Slog.i(TAG, "Un-granting permission " + perm 9383 + " from package " + pkg.packageName 9384 + " (protectionLevel=" + bp.protectionLevel 9385 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9386 + ")"); 9387 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9388 // Don't print warning for app op permissions, since it is fine for them 9389 // not to be granted, there is a UI for the user to decide. 9390 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9391 Slog.w(TAG, "Not granting permission " + perm 9392 + " to package " + pkg.packageName 9393 + " (protectionLevel=" + bp.protectionLevel 9394 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9395 + ")"); 9396 } 9397 } 9398 } 9399 } 9400 9401 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9402 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9403 // This is the first that we have heard about this package, so the 9404 // permissions we have now selected are fixed until explicitly 9405 // changed. 9406 ps.installPermissionsFixed = true; 9407 } 9408 9409 // Persist the runtime permissions state for users with changes. If permissions 9410 // were revoked because no app in the shared user declares them we have to 9411 // write synchronously to avoid losing runtime permissions state. 9412 for (int userId : changedRuntimePermissionUserIds) { 9413 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9414 } 9415 9416 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9417 } 9418 9419 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9420 boolean allowed = false; 9421 final int NP = PackageParser.NEW_PERMISSIONS.length; 9422 for (int ip=0; ip<NP; ip++) { 9423 final PackageParser.NewPermissionInfo npi 9424 = PackageParser.NEW_PERMISSIONS[ip]; 9425 if (npi.name.equals(perm) 9426 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9427 allowed = true; 9428 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9429 + pkg.packageName); 9430 break; 9431 } 9432 } 9433 return allowed; 9434 } 9435 9436 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9437 BasePermission bp, PermissionsState origPermissions) { 9438 boolean allowed; 9439 allowed = (compareSignatures( 9440 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9441 == PackageManager.SIGNATURE_MATCH) 9442 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9443 == PackageManager.SIGNATURE_MATCH); 9444 if (!allowed && (bp.protectionLevel 9445 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9446 if (isSystemApp(pkg)) { 9447 // For updated system applications, a system permission 9448 // is granted only if it had been defined by the original application. 9449 if (pkg.isUpdatedSystemApp()) { 9450 final PackageSetting sysPs = mSettings 9451 .getDisabledSystemPkgLPr(pkg.packageName); 9452 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9453 // If the original was granted this permission, we take 9454 // that grant decision as read and propagate it to the 9455 // update. 9456 if (sysPs.isPrivileged()) { 9457 allowed = true; 9458 } 9459 } else { 9460 // The system apk may have been updated with an older 9461 // version of the one on the data partition, but which 9462 // granted a new system permission that it didn't have 9463 // before. In this case we do want to allow the app to 9464 // now get the new permission if the ancestral apk is 9465 // privileged to get it. 9466 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9467 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9468 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9469 allowed = true; 9470 break; 9471 } 9472 } 9473 } 9474 // Also if a privileged parent package on the system image or any of 9475 // its children requested a privileged permission, the updated child 9476 // packages can also get the permission. 9477 if (pkg.parentPackage != null) { 9478 final PackageSetting disabledSysParentPs = mSettings 9479 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 9480 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 9481 && disabledSysParentPs.isPrivileged()) { 9482 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 9483 allowed = true; 9484 } else if (disabledSysParentPs.pkg.childPackages != null) { 9485 final int count = disabledSysParentPs.pkg.childPackages.size(); 9486 for (int i = 0; i < count; i++) { 9487 PackageParser.Package disabledSysChildPkg = 9488 disabledSysParentPs.pkg.childPackages.get(i); 9489 if (isPackageRequestingPermission(disabledSysChildPkg, 9490 perm)) { 9491 allowed = true; 9492 break; 9493 } 9494 } 9495 } 9496 } 9497 } 9498 } 9499 } else { 9500 allowed = isPrivilegedApp(pkg); 9501 } 9502 } 9503 } 9504 if (!allowed) { 9505 if (!allowed && (bp.protectionLevel 9506 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9507 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9508 // If this was a previously normal/dangerous permission that got moved 9509 // to a system permission as part of the runtime permission redesign, then 9510 // we still want to blindly grant it to old apps. 9511 allowed = true; 9512 } 9513 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9514 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9515 // If this permission is to be granted to the system installer and 9516 // this app is an installer, then it gets the permission. 9517 allowed = true; 9518 } 9519 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9520 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9521 // If this permission is to be granted to the system verifier and 9522 // this app is a verifier, then it gets the permission. 9523 allowed = true; 9524 } 9525 if (!allowed && (bp.protectionLevel 9526 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9527 && isSystemApp(pkg)) { 9528 // Any pre-installed system app is allowed to get this permission. 9529 allowed = true; 9530 } 9531 if (!allowed && (bp.protectionLevel 9532 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9533 // For development permissions, a development permission 9534 // is granted only if it was already granted. 9535 allowed = origPermissions.hasInstallPermission(perm); 9536 } 9537 } 9538 return allowed; 9539 } 9540 9541 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 9542 final int permCount = pkg.requestedPermissions.size(); 9543 for (int j = 0; j < permCount; j++) { 9544 String requestedPermission = pkg.requestedPermissions.get(j); 9545 if (permission.equals(requestedPermission)) { 9546 return true; 9547 } 9548 } 9549 return false; 9550 } 9551 9552 final class ActivityIntentResolver 9553 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9554 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9555 boolean defaultOnly, int userId) { 9556 if (!sUserManager.exists(userId)) return null; 9557 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9558 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9559 } 9560 9561 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9562 int userId) { 9563 if (!sUserManager.exists(userId)) return null; 9564 mFlags = flags; 9565 return super.queryIntent(intent, resolvedType, 9566 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9567 } 9568 9569 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9570 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9571 if (!sUserManager.exists(userId)) return null; 9572 if (packageActivities == null) { 9573 return null; 9574 } 9575 mFlags = flags; 9576 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9577 final int N = packageActivities.size(); 9578 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9579 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9580 9581 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9582 for (int i = 0; i < N; ++i) { 9583 intentFilters = packageActivities.get(i).intents; 9584 if (intentFilters != null && intentFilters.size() > 0) { 9585 PackageParser.ActivityIntentInfo[] array = 9586 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9587 intentFilters.toArray(array); 9588 listCut.add(array); 9589 } 9590 } 9591 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9592 } 9593 9594 public final void addActivity(PackageParser.Activity a, String type) { 9595 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 9596 mActivities.put(a.getComponentName(), a); 9597 if (DEBUG_SHOW_INFO) 9598 Log.v( 9599 TAG, " " + type + " " + 9600 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 9601 if (DEBUG_SHOW_INFO) 9602 Log.v(TAG, " Class=" + a.info.name); 9603 final int NI = a.intents.size(); 9604 for (int j=0; j<NI; j++) { 9605 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9606 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 9607 intent.setPriority(0); 9608 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 9609 + a.className + " with priority > 0, forcing to 0"); 9610 } 9611 if (DEBUG_SHOW_INFO) { 9612 Log.v(TAG, " IntentFilter:"); 9613 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9614 } 9615 if (!intent.debugCheck()) { 9616 Log.w(TAG, "==> For Activity " + a.info.name); 9617 } 9618 addFilter(intent); 9619 } 9620 } 9621 9622 public final void removeActivity(PackageParser.Activity a, String type) { 9623 mActivities.remove(a.getComponentName()); 9624 if (DEBUG_SHOW_INFO) { 9625 Log.v(TAG, " " + type + " " 9626 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 9627 : a.info.name) + ":"); 9628 Log.v(TAG, " Class=" + a.info.name); 9629 } 9630 final int NI = a.intents.size(); 9631 for (int j=0; j<NI; j++) { 9632 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9633 if (DEBUG_SHOW_INFO) { 9634 Log.v(TAG, " IntentFilter:"); 9635 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9636 } 9637 removeFilter(intent); 9638 } 9639 } 9640 9641 @Override 9642 protected boolean allowFilterResult( 9643 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 9644 ActivityInfo filterAi = filter.activity.info; 9645 for (int i=dest.size()-1; i>=0; i--) { 9646 ActivityInfo destAi = dest.get(i).activityInfo; 9647 if (destAi.name == filterAi.name 9648 && destAi.packageName == filterAi.packageName) { 9649 return false; 9650 } 9651 } 9652 return true; 9653 } 9654 9655 @Override 9656 protected ActivityIntentInfo[] newArray(int size) { 9657 return new ActivityIntentInfo[size]; 9658 } 9659 9660 @Override 9661 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 9662 if (!sUserManager.exists(userId)) return true; 9663 PackageParser.Package p = filter.activity.owner; 9664 if (p != null) { 9665 PackageSetting ps = (PackageSetting)p.mExtras; 9666 if (ps != null) { 9667 // System apps are never considered stopped for purposes of 9668 // filtering, because there may be no way for the user to 9669 // actually re-launch them. 9670 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 9671 && ps.getStopped(userId); 9672 } 9673 } 9674 return false; 9675 } 9676 9677 @Override 9678 protected boolean isPackageForFilter(String packageName, 9679 PackageParser.ActivityIntentInfo info) { 9680 return packageName.equals(info.activity.owner.packageName); 9681 } 9682 9683 @Override 9684 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 9685 int match, int userId) { 9686 if (!sUserManager.exists(userId)) return null; 9687 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 9688 return null; 9689 } 9690 final PackageParser.Activity activity = info.activity; 9691 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 9692 if (ps == null) { 9693 return null; 9694 } 9695 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 9696 ps.readUserState(userId), userId); 9697 if (ai == null) { 9698 return null; 9699 } 9700 final ResolveInfo res = new ResolveInfo(); 9701 res.activityInfo = ai; 9702 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9703 res.filter = info; 9704 } 9705 if (info != null) { 9706 res.handleAllWebDataURI = info.handleAllWebDataURI(); 9707 } 9708 res.priority = info.getPriority(); 9709 res.preferredOrder = activity.owner.mPreferredOrder; 9710 //System.out.println("Result: " + res.activityInfo.className + 9711 // " = " + res.priority); 9712 res.match = match; 9713 res.isDefault = info.hasDefault; 9714 res.labelRes = info.labelRes; 9715 res.nonLocalizedLabel = info.nonLocalizedLabel; 9716 if (userNeedsBadging(userId)) { 9717 res.noResourceId = true; 9718 } else { 9719 res.icon = info.icon; 9720 } 9721 res.iconResourceId = info.icon; 9722 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9723 return res; 9724 } 9725 9726 @Override 9727 protected void sortResults(List<ResolveInfo> results) { 9728 Collections.sort(results, mResolvePrioritySorter); 9729 } 9730 9731 @Override 9732 protected void dumpFilter(PrintWriter out, String prefix, 9733 PackageParser.ActivityIntentInfo filter) { 9734 out.print(prefix); out.print( 9735 Integer.toHexString(System.identityHashCode(filter.activity))); 9736 out.print(' '); 9737 filter.activity.printComponentShortName(out); 9738 out.print(" filter "); 9739 out.println(Integer.toHexString(System.identityHashCode(filter))); 9740 } 9741 9742 @Override 9743 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9744 return filter.activity; 9745 } 9746 9747 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9748 PackageParser.Activity activity = (PackageParser.Activity)label; 9749 out.print(prefix); out.print( 9750 Integer.toHexString(System.identityHashCode(activity))); 9751 out.print(' '); 9752 activity.printComponentShortName(out); 9753 if (count > 1) { 9754 out.print(" ("); out.print(count); out.print(" filters)"); 9755 } 9756 out.println(); 9757 } 9758 9759// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9760// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9761// final List<ResolveInfo> retList = Lists.newArrayList(); 9762// while (i.hasNext()) { 9763// final ResolveInfo resolveInfo = i.next(); 9764// if (isEnabledLP(resolveInfo.activityInfo)) { 9765// retList.add(resolveInfo); 9766// } 9767// } 9768// return retList; 9769// } 9770 9771 // Keys are String (activity class name), values are Activity. 9772 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9773 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9774 private int mFlags; 9775 } 9776 9777 private final class ServiceIntentResolver 9778 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9779 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9780 boolean defaultOnly, int userId) { 9781 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9782 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9783 } 9784 9785 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9786 int userId) { 9787 if (!sUserManager.exists(userId)) return null; 9788 mFlags = flags; 9789 return super.queryIntent(intent, resolvedType, 9790 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9791 } 9792 9793 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9794 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9795 if (!sUserManager.exists(userId)) return null; 9796 if (packageServices == null) { 9797 return null; 9798 } 9799 mFlags = flags; 9800 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9801 final int N = packageServices.size(); 9802 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9803 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9804 9805 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9806 for (int i = 0; i < N; ++i) { 9807 intentFilters = packageServices.get(i).intents; 9808 if (intentFilters != null && intentFilters.size() > 0) { 9809 PackageParser.ServiceIntentInfo[] array = 9810 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9811 intentFilters.toArray(array); 9812 listCut.add(array); 9813 } 9814 } 9815 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9816 } 9817 9818 public final void addService(PackageParser.Service s) { 9819 mServices.put(s.getComponentName(), s); 9820 if (DEBUG_SHOW_INFO) { 9821 Log.v(TAG, " " 9822 + (s.info.nonLocalizedLabel != null 9823 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9824 Log.v(TAG, " Class=" + s.info.name); 9825 } 9826 final int NI = s.intents.size(); 9827 int j; 9828 for (j=0; j<NI; j++) { 9829 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9830 if (DEBUG_SHOW_INFO) { 9831 Log.v(TAG, " IntentFilter:"); 9832 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9833 } 9834 if (!intent.debugCheck()) { 9835 Log.w(TAG, "==> For Service " + s.info.name); 9836 } 9837 addFilter(intent); 9838 } 9839 } 9840 9841 public final void removeService(PackageParser.Service s) { 9842 mServices.remove(s.getComponentName()); 9843 if (DEBUG_SHOW_INFO) { 9844 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9845 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9846 Log.v(TAG, " Class=" + s.info.name); 9847 } 9848 final int NI = s.intents.size(); 9849 int j; 9850 for (j=0; j<NI; j++) { 9851 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9852 if (DEBUG_SHOW_INFO) { 9853 Log.v(TAG, " IntentFilter:"); 9854 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9855 } 9856 removeFilter(intent); 9857 } 9858 } 9859 9860 @Override 9861 protected boolean allowFilterResult( 9862 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9863 ServiceInfo filterSi = filter.service.info; 9864 for (int i=dest.size()-1; i>=0; i--) { 9865 ServiceInfo destAi = dest.get(i).serviceInfo; 9866 if (destAi.name == filterSi.name 9867 && destAi.packageName == filterSi.packageName) { 9868 return false; 9869 } 9870 } 9871 return true; 9872 } 9873 9874 @Override 9875 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9876 return new PackageParser.ServiceIntentInfo[size]; 9877 } 9878 9879 @Override 9880 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9881 if (!sUserManager.exists(userId)) return true; 9882 PackageParser.Package p = filter.service.owner; 9883 if (p != null) { 9884 PackageSetting ps = (PackageSetting)p.mExtras; 9885 if (ps != null) { 9886 // System apps are never considered stopped for purposes of 9887 // filtering, because there may be no way for the user to 9888 // actually re-launch them. 9889 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9890 && ps.getStopped(userId); 9891 } 9892 } 9893 return false; 9894 } 9895 9896 @Override 9897 protected boolean isPackageForFilter(String packageName, 9898 PackageParser.ServiceIntentInfo info) { 9899 return packageName.equals(info.service.owner.packageName); 9900 } 9901 9902 @Override 9903 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9904 int match, int userId) { 9905 if (!sUserManager.exists(userId)) return null; 9906 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9907 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 9908 return null; 9909 } 9910 final PackageParser.Service service = info.service; 9911 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9912 if (ps == null) { 9913 return null; 9914 } 9915 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9916 ps.readUserState(userId), userId); 9917 if (si == null) { 9918 return null; 9919 } 9920 final ResolveInfo res = new ResolveInfo(); 9921 res.serviceInfo = si; 9922 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9923 res.filter = filter; 9924 } 9925 res.priority = info.getPriority(); 9926 res.preferredOrder = service.owner.mPreferredOrder; 9927 res.match = match; 9928 res.isDefault = info.hasDefault; 9929 res.labelRes = info.labelRes; 9930 res.nonLocalizedLabel = info.nonLocalizedLabel; 9931 res.icon = info.icon; 9932 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9933 return res; 9934 } 9935 9936 @Override 9937 protected void sortResults(List<ResolveInfo> results) { 9938 Collections.sort(results, mResolvePrioritySorter); 9939 } 9940 9941 @Override 9942 protected void dumpFilter(PrintWriter out, String prefix, 9943 PackageParser.ServiceIntentInfo filter) { 9944 out.print(prefix); out.print( 9945 Integer.toHexString(System.identityHashCode(filter.service))); 9946 out.print(' '); 9947 filter.service.printComponentShortName(out); 9948 out.print(" filter "); 9949 out.println(Integer.toHexString(System.identityHashCode(filter))); 9950 } 9951 9952 @Override 9953 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9954 return filter.service; 9955 } 9956 9957 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9958 PackageParser.Service service = (PackageParser.Service)label; 9959 out.print(prefix); out.print( 9960 Integer.toHexString(System.identityHashCode(service))); 9961 out.print(' '); 9962 service.printComponentShortName(out); 9963 if (count > 1) { 9964 out.print(" ("); out.print(count); out.print(" filters)"); 9965 } 9966 out.println(); 9967 } 9968 9969// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9970// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9971// final List<ResolveInfo> retList = Lists.newArrayList(); 9972// while (i.hasNext()) { 9973// final ResolveInfo resolveInfo = (ResolveInfo) i; 9974// if (isEnabledLP(resolveInfo.serviceInfo)) { 9975// retList.add(resolveInfo); 9976// } 9977// } 9978// return retList; 9979// } 9980 9981 // Keys are String (activity class name), values are Activity. 9982 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9983 = new ArrayMap<ComponentName, PackageParser.Service>(); 9984 private int mFlags; 9985 }; 9986 9987 private final class ProviderIntentResolver 9988 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9989 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9990 boolean defaultOnly, int userId) { 9991 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9992 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9993 } 9994 9995 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9996 int userId) { 9997 if (!sUserManager.exists(userId)) 9998 return null; 9999 mFlags = flags; 10000 return super.queryIntent(intent, resolvedType, 10001 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10002 } 10003 10004 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10005 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10006 if (!sUserManager.exists(userId)) 10007 return null; 10008 if (packageProviders == null) { 10009 return null; 10010 } 10011 mFlags = flags; 10012 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10013 final int N = packageProviders.size(); 10014 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10015 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10016 10017 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10018 for (int i = 0; i < N; ++i) { 10019 intentFilters = packageProviders.get(i).intents; 10020 if (intentFilters != null && intentFilters.size() > 0) { 10021 PackageParser.ProviderIntentInfo[] array = 10022 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10023 intentFilters.toArray(array); 10024 listCut.add(array); 10025 } 10026 } 10027 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10028 } 10029 10030 public final void addProvider(PackageParser.Provider p) { 10031 if (mProviders.containsKey(p.getComponentName())) { 10032 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10033 return; 10034 } 10035 10036 mProviders.put(p.getComponentName(), p); 10037 if (DEBUG_SHOW_INFO) { 10038 Log.v(TAG, " " 10039 + (p.info.nonLocalizedLabel != null 10040 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10041 Log.v(TAG, " Class=" + p.info.name); 10042 } 10043 final int NI = p.intents.size(); 10044 int j; 10045 for (j = 0; j < NI; j++) { 10046 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10047 if (DEBUG_SHOW_INFO) { 10048 Log.v(TAG, " IntentFilter:"); 10049 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10050 } 10051 if (!intent.debugCheck()) { 10052 Log.w(TAG, "==> For Provider " + p.info.name); 10053 } 10054 addFilter(intent); 10055 } 10056 } 10057 10058 public final void removeProvider(PackageParser.Provider p) { 10059 mProviders.remove(p.getComponentName()); 10060 if (DEBUG_SHOW_INFO) { 10061 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10062 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10063 Log.v(TAG, " Class=" + p.info.name); 10064 } 10065 final int NI = p.intents.size(); 10066 int j; 10067 for (j = 0; j < NI; j++) { 10068 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10069 if (DEBUG_SHOW_INFO) { 10070 Log.v(TAG, " IntentFilter:"); 10071 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10072 } 10073 removeFilter(intent); 10074 } 10075 } 10076 10077 @Override 10078 protected boolean allowFilterResult( 10079 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10080 ProviderInfo filterPi = filter.provider.info; 10081 for (int i = dest.size() - 1; i >= 0; i--) { 10082 ProviderInfo destPi = dest.get(i).providerInfo; 10083 if (destPi.name == filterPi.name 10084 && destPi.packageName == filterPi.packageName) { 10085 return false; 10086 } 10087 } 10088 return true; 10089 } 10090 10091 @Override 10092 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10093 return new PackageParser.ProviderIntentInfo[size]; 10094 } 10095 10096 @Override 10097 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10098 if (!sUserManager.exists(userId)) 10099 return true; 10100 PackageParser.Package p = filter.provider.owner; 10101 if (p != null) { 10102 PackageSetting ps = (PackageSetting) p.mExtras; 10103 if (ps != null) { 10104 // System apps are never considered stopped for purposes of 10105 // filtering, because there may be no way for the user to 10106 // actually re-launch them. 10107 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10108 && ps.getStopped(userId); 10109 } 10110 } 10111 return false; 10112 } 10113 10114 @Override 10115 protected boolean isPackageForFilter(String packageName, 10116 PackageParser.ProviderIntentInfo info) { 10117 return packageName.equals(info.provider.owner.packageName); 10118 } 10119 10120 @Override 10121 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10122 int match, int userId) { 10123 if (!sUserManager.exists(userId)) 10124 return null; 10125 final PackageParser.ProviderIntentInfo info = filter; 10126 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10127 return null; 10128 } 10129 final PackageParser.Provider provider = info.provider; 10130 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10131 if (ps == null) { 10132 return null; 10133 } 10134 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10135 ps.readUserState(userId), userId); 10136 if (pi == null) { 10137 return null; 10138 } 10139 final ResolveInfo res = new ResolveInfo(); 10140 res.providerInfo = pi; 10141 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10142 res.filter = filter; 10143 } 10144 res.priority = info.getPriority(); 10145 res.preferredOrder = provider.owner.mPreferredOrder; 10146 res.match = match; 10147 res.isDefault = info.hasDefault; 10148 res.labelRes = info.labelRes; 10149 res.nonLocalizedLabel = info.nonLocalizedLabel; 10150 res.icon = info.icon; 10151 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10152 return res; 10153 } 10154 10155 @Override 10156 protected void sortResults(List<ResolveInfo> results) { 10157 Collections.sort(results, mResolvePrioritySorter); 10158 } 10159 10160 @Override 10161 protected void dumpFilter(PrintWriter out, String prefix, 10162 PackageParser.ProviderIntentInfo filter) { 10163 out.print(prefix); 10164 out.print( 10165 Integer.toHexString(System.identityHashCode(filter.provider))); 10166 out.print(' '); 10167 filter.provider.printComponentShortName(out); 10168 out.print(" filter "); 10169 out.println(Integer.toHexString(System.identityHashCode(filter))); 10170 } 10171 10172 @Override 10173 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 10174 return filter.provider; 10175 } 10176 10177 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10178 PackageParser.Provider provider = (PackageParser.Provider)label; 10179 out.print(prefix); out.print( 10180 Integer.toHexString(System.identityHashCode(provider))); 10181 out.print(' '); 10182 provider.printComponentShortName(out); 10183 if (count > 1) { 10184 out.print(" ("); out.print(count); out.print(" filters)"); 10185 } 10186 out.println(); 10187 } 10188 10189 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 10190 = new ArrayMap<ComponentName, PackageParser.Provider>(); 10191 private int mFlags; 10192 } 10193 10194 private static final class EphemeralIntentResolver 10195 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 10196 @Override 10197 protected EphemeralResolveIntentInfo[] newArray(int size) { 10198 return new EphemeralResolveIntentInfo[size]; 10199 } 10200 10201 @Override 10202 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 10203 return true; 10204 } 10205 10206 @Override 10207 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 10208 int userId) { 10209 if (!sUserManager.exists(userId)) { 10210 return null; 10211 } 10212 return info.getEphemeralResolveInfo(); 10213 } 10214 } 10215 10216 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 10217 new Comparator<ResolveInfo>() { 10218 public int compare(ResolveInfo r1, ResolveInfo r2) { 10219 int v1 = r1.priority; 10220 int v2 = r2.priority; 10221 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 10222 if (v1 != v2) { 10223 return (v1 > v2) ? -1 : 1; 10224 } 10225 v1 = r1.preferredOrder; 10226 v2 = r2.preferredOrder; 10227 if (v1 != v2) { 10228 return (v1 > v2) ? -1 : 1; 10229 } 10230 if (r1.isDefault != r2.isDefault) { 10231 return r1.isDefault ? -1 : 1; 10232 } 10233 v1 = r1.match; 10234 v2 = r2.match; 10235 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 10236 if (v1 != v2) { 10237 return (v1 > v2) ? -1 : 1; 10238 } 10239 if (r1.system != r2.system) { 10240 return r1.system ? -1 : 1; 10241 } 10242 if (r1.activityInfo != null) { 10243 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 10244 } 10245 if (r1.serviceInfo != null) { 10246 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 10247 } 10248 if (r1.providerInfo != null) { 10249 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 10250 } 10251 return 0; 10252 } 10253 }; 10254 10255 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 10256 new Comparator<ProviderInfo>() { 10257 public int compare(ProviderInfo p1, ProviderInfo p2) { 10258 final int v1 = p1.initOrder; 10259 final int v2 = p2.initOrder; 10260 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 10261 } 10262 }; 10263 10264 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 10265 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 10266 final int[] userIds) { 10267 mHandler.post(new Runnable() { 10268 @Override 10269 public void run() { 10270 try { 10271 final IActivityManager am = ActivityManagerNative.getDefault(); 10272 if (am == null) return; 10273 final int[] resolvedUserIds; 10274 if (userIds == null) { 10275 resolvedUserIds = am.getRunningUserIds(); 10276 } else { 10277 resolvedUserIds = userIds; 10278 } 10279 for (int id : resolvedUserIds) { 10280 final Intent intent = new Intent(action, 10281 pkg != null ? Uri.fromParts("package", pkg, null) : null); 10282 if (extras != null) { 10283 intent.putExtras(extras); 10284 } 10285 if (targetPkg != null) { 10286 intent.setPackage(targetPkg); 10287 } 10288 // Modify the UID when posting to other users 10289 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 10290 if (uid > 0 && UserHandle.getUserId(uid) != id) { 10291 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 10292 intent.putExtra(Intent.EXTRA_UID, uid); 10293 } 10294 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 10295 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 10296 if (DEBUG_BROADCASTS) { 10297 RuntimeException here = new RuntimeException("here"); 10298 here.fillInStackTrace(); 10299 Slog.d(TAG, "Sending to user " + id + ": " 10300 + intent.toShortString(false, true, false, false) 10301 + " " + intent.getExtras(), here); 10302 } 10303 am.broadcastIntent(null, intent, null, finishedReceiver, 10304 0, null, null, null, android.app.AppOpsManager.OP_NONE, 10305 null, finishedReceiver != null, false, id); 10306 } 10307 } catch (RemoteException ex) { 10308 } 10309 } 10310 }); 10311 } 10312 10313 /** 10314 * Check if the external storage media is available. This is true if there 10315 * is a mounted external storage medium or if the external storage is 10316 * emulated. 10317 */ 10318 private boolean isExternalMediaAvailable() { 10319 return mMediaMounted || Environment.isExternalStorageEmulated(); 10320 } 10321 10322 @Override 10323 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 10324 // writer 10325 synchronized (mPackages) { 10326 if (!isExternalMediaAvailable()) { 10327 // If the external storage is no longer mounted at this point, 10328 // the caller may not have been able to delete all of this 10329 // packages files and can not delete any more. Bail. 10330 return null; 10331 } 10332 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 10333 if (lastPackage != null) { 10334 pkgs.remove(lastPackage); 10335 } 10336 if (pkgs.size() > 0) { 10337 return pkgs.get(0); 10338 } 10339 } 10340 return null; 10341 } 10342 10343 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 10344 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 10345 userId, andCode ? 1 : 0, packageName); 10346 if (mSystemReady) { 10347 msg.sendToTarget(); 10348 } else { 10349 if (mPostSystemReadyMessages == null) { 10350 mPostSystemReadyMessages = new ArrayList<>(); 10351 } 10352 mPostSystemReadyMessages.add(msg); 10353 } 10354 } 10355 10356 void startCleaningPackages() { 10357 // reader 10358 synchronized (mPackages) { 10359 if (!isExternalMediaAvailable()) { 10360 return; 10361 } 10362 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 10363 return; 10364 } 10365 } 10366 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 10367 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 10368 IActivityManager am = ActivityManagerNative.getDefault(); 10369 if (am != null) { 10370 try { 10371 am.startService(null, intent, null, mContext.getOpPackageName(), 10372 UserHandle.USER_SYSTEM); 10373 } catch (RemoteException e) { 10374 } 10375 } 10376 } 10377 10378 @Override 10379 public void installPackage(String originPath, IPackageInstallObserver2 observer, 10380 int installFlags, String installerPackageName, VerificationParams verificationParams, 10381 String packageAbiOverride) { 10382 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 10383 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 10384 } 10385 10386 @Override 10387 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 10388 int installFlags, String installerPackageName, VerificationParams verificationParams, 10389 String packageAbiOverride, int userId) { 10390 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 10391 10392 final int callingUid = Binder.getCallingUid(); 10393 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 10394 10395 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10396 try { 10397 if (observer != null) { 10398 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 10399 } 10400 } catch (RemoteException re) { 10401 } 10402 return; 10403 } 10404 10405 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 10406 installFlags |= PackageManager.INSTALL_FROM_ADB; 10407 10408 } else { 10409 // Caller holds INSTALL_PACKAGES permission, so we're less strict 10410 // about installerPackageName. 10411 10412 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 10413 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 10414 } 10415 10416 UserHandle user; 10417 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 10418 user = UserHandle.ALL; 10419 } else { 10420 user = new UserHandle(userId); 10421 } 10422 10423 // Only system components can circumvent runtime permissions when installing. 10424 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 10425 && mContext.checkCallingOrSelfPermission(Manifest.permission 10426 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 10427 throw new SecurityException("You need the " 10428 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 10429 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 10430 } 10431 10432 verificationParams.setInstallerUid(callingUid); 10433 10434 final File originFile = new File(originPath); 10435 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 10436 10437 final Message msg = mHandler.obtainMessage(INIT_COPY); 10438 final InstallParams params = new InstallParams(origin, null, observer, installFlags, 10439 installerPackageName, null, verificationParams, user, packageAbiOverride, null); 10440 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 10441 msg.obj = params; 10442 10443 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 10444 System.identityHashCode(msg.obj)); 10445 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10446 System.identityHashCode(msg.obj)); 10447 10448 mHandler.sendMessage(msg); 10449 } 10450 10451 void installStage(String packageName, File stagedDir, String stagedCid, 10452 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 10453 String installerPackageName, int installerUid, UserHandle user) { 10454 if (DEBUG_EPHEMERAL) { 10455 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10456 Slog.d(TAG, "Ephemeral install of " + packageName); 10457 } 10458 } 10459 final VerificationParams verifParams = new VerificationParams( 10460 null, sessionParams.originatingUri, sessionParams.referrerUri, 10461 sessionParams.originatingUid); 10462 verifParams.setInstallerUid(installerUid); 10463 10464 final OriginInfo origin; 10465 if (stagedDir != null) { 10466 origin = OriginInfo.fromStagedFile(stagedDir); 10467 } else { 10468 origin = OriginInfo.fromStagedContainer(stagedCid); 10469 } 10470 10471 final Message msg = mHandler.obtainMessage(INIT_COPY); 10472 final InstallParams params = new InstallParams(origin, null, observer, 10473 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 10474 verifParams, user, sessionParams.abiOverride, 10475 sessionParams.grantedRuntimePermissions); 10476 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 10477 msg.obj = params; 10478 10479 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 10480 System.identityHashCode(msg.obj)); 10481 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10482 System.identityHashCode(msg.obj)); 10483 10484 mHandler.sendMessage(msg); 10485 } 10486 10487 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 10488 int userId) { 10489 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 10490 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 10491 } 10492 10493 private void sendPackageAddedForUser(String packageName, boolean isSystem, 10494 int appId, int userId) { 10495 Bundle extras = new Bundle(1); 10496 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 10497 10498 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 10499 packageName, extras, 0, null, null, new int[] {userId}); 10500 try { 10501 IActivityManager am = ActivityManagerNative.getDefault(); 10502 if (isSystem && am.isUserRunning(userId, 0)) { 10503 // The just-installed/enabled app is bundled on the system, so presumed 10504 // to be able to run automatically without needing an explicit launch. 10505 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 10506 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 10507 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 10508 .setPackage(packageName); 10509 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 10510 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 10511 } 10512 } catch (RemoteException e) { 10513 // shouldn't happen 10514 Slog.w(TAG, "Unable to bootstrap installed package", e); 10515 } 10516 } 10517 10518 @Override 10519 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 10520 int userId) { 10521 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10522 PackageSetting pkgSetting; 10523 final int uid = Binder.getCallingUid(); 10524 enforceCrossUserPermission(uid, userId, true, true, 10525 "setApplicationHiddenSetting for user " + userId); 10526 10527 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 10528 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 10529 return false; 10530 } 10531 10532 long callingId = Binder.clearCallingIdentity(); 10533 try { 10534 boolean sendAdded = false; 10535 boolean sendRemoved = false; 10536 // writer 10537 synchronized (mPackages) { 10538 pkgSetting = mSettings.mPackages.get(packageName); 10539 if (pkgSetting == null) { 10540 return false; 10541 } 10542 if (pkgSetting.getHidden(userId) != hidden) { 10543 pkgSetting.setHidden(hidden, userId); 10544 mSettings.writePackageRestrictionsLPr(userId); 10545 if (hidden) { 10546 sendRemoved = true; 10547 } else { 10548 sendAdded = true; 10549 } 10550 } 10551 } 10552 if (sendAdded) { 10553 sendPackageAddedForUser(packageName, pkgSetting, userId); 10554 return true; 10555 } 10556 if (sendRemoved) { 10557 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 10558 "hiding pkg"); 10559 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 10560 return true; 10561 } 10562 } finally { 10563 Binder.restoreCallingIdentity(callingId); 10564 } 10565 return false; 10566 } 10567 10568 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 10569 int userId) { 10570 final PackageRemovedInfo info = new PackageRemovedInfo(); 10571 info.removedPackage = packageName; 10572 info.removedUsers = new int[] {userId}; 10573 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 10574 info.sendPackageRemovedBroadcasts(); 10575 } 10576 10577 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 10578 if (pkgList.length > 0) { 10579 Bundle extras = new Bundle(1); 10580 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 10581 10582 sendPackageBroadcast( 10583 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 10584 : Intent.ACTION_PACKAGES_UNSUSPENDED, 10585 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 10586 new int[] {userId}); 10587 } 10588 } 10589 10590 /** 10591 * Returns true if application is not found or there was an error. Otherwise it returns 10592 * the hidden state of the package for the given user. 10593 */ 10594 @Override 10595 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 10596 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10597 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 10598 false, "getApplicationHidden for user " + userId); 10599 PackageSetting pkgSetting; 10600 long callingId = Binder.clearCallingIdentity(); 10601 try { 10602 // writer 10603 synchronized (mPackages) { 10604 pkgSetting = mSettings.mPackages.get(packageName); 10605 if (pkgSetting == null) { 10606 return true; 10607 } 10608 return pkgSetting.getHidden(userId); 10609 } 10610 } finally { 10611 Binder.restoreCallingIdentity(callingId); 10612 } 10613 } 10614 10615 /** 10616 * @hide 10617 */ 10618 @Override 10619 public int installExistingPackageAsUser(String packageName, int userId) { 10620 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 10621 null); 10622 PackageSetting pkgSetting; 10623 final int uid = Binder.getCallingUid(); 10624 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 10625 + userId); 10626 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10627 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 10628 } 10629 10630 long callingId = Binder.clearCallingIdentity(); 10631 try { 10632 boolean installed = false; 10633 10634 // writer 10635 synchronized (mPackages) { 10636 pkgSetting = mSettings.mPackages.get(packageName); 10637 if (pkgSetting == null) { 10638 return PackageManager.INSTALL_FAILED_INVALID_URI; 10639 } 10640 if (!pkgSetting.getInstalled(userId)) { 10641 pkgSetting.setInstalled(true, userId); 10642 pkgSetting.setHidden(false, userId); 10643 mSettings.writePackageRestrictionsLPr(userId); 10644 installed = true; 10645 } 10646 } 10647 10648 if (installed) { 10649 if (pkgSetting.pkg != null) { 10650 prepareAppDataAfterInstall(pkgSetting.pkg); 10651 } 10652 sendPackageAddedForUser(packageName, pkgSetting, userId); 10653 } 10654 } finally { 10655 Binder.restoreCallingIdentity(callingId); 10656 } 10657 10658 return PackageManager.INSTALL_SUCCEEDED; 10659 } 10660 10661 boolean isUserRestricted(int userId, String restrictionKey) { 10662 Bundle restrictions = sUserManager.getUserRestrictions(userId); 10663 if (restrictions.getBoolean(restrictionKey, false)) { 10664 Log.w(TAG, "User is restricted: " + restrictionKey); 10665 return true; 10666 } 10667 return false; 10668 } 10669 10670 @Override 10671 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 10672 int userId) { 10673 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10674 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true, 10675 "setPackagesSuspended for user " + userId); 10676 10677 if (ArrayUtils.isEmpty(packageNames)) { 10678 return packageNames; 10679 } 10680 10681 // List of package names for whom the suspended state has changed. 10682 List<String> changedPackages = new ArrayList<>(packageNames.length); 10683 // List of package names for whom the suspended state is not set as requested in this 10684 // method. 10685 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 10686 for (int i = 0; i < packageNames.length; i++) { 10687 String packageName = packageNames[i]; 10688 long callingId = Binder.clearCallingIdentity(); 10689 try { 10690 boolean changed = false; 10691 final int appId; 10692 synchronized (mPackages) { 10693 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10694 if (pkgSetting == null) { 10695 Slog.w(TAG, "Could not find package setting for package \"" + packageName 10696 + "\". Skipping suspending/un-suspending."); 10697 unactionedPackages.add(packageName); 10698 continue; 10699 } 10700 appId = pkgSetting.appId; 10701 if (pkgSetting.getSuspended(userId) != suspended) { 10702 if (!canSuspendPackageForUserLocked(packageName, userId)) { 10703 unactionedPackages.add(packageName); 10704 continue; 10705 } 10706 pkgSetting.setSuspended(suspended, userId); 10707 mSettings.writePackageRestrictionsLPr(userId); 10708 changed = true; 10709 changedPackages.add(packageName); 10710 } 10711 } 10712 10713 if (changed && suspended) { 10714 killApplication(packageName, UserHandle.getUid(userId, appId), 10715 "suspending package"); 10716 } 10717 } finally { 10718 Binder.restoreCallingIdentity(callingId); 10719 } 10720 } 10721 10722 if (!changedPackages.isEmpty()) { 10723 sendPackagesSuspendedForUser(changedPackages.toArray( 10724 new String[changedPackages.size()]), userId, suspended); 10725 } 10726 10727 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 10728 } 10729 10730 @Override 10731 public boolean isPackageSuspendedForUser(String packageName, int userId) { 10732 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 10733 false, "isPackageSuspendedForUser for user " + userId); 10734 synchronized (mPackages) { 10735 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10736 return pkgSetting != null && pkgSetting.getSuspended(userId); 10737 } 10738 } 10739 10740 // TODO: investigate and add more restrictions for suspending crucial packages. 10741 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 10742 if (isPackageDeviceAdmin(packageName, userId)) { 10743 Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName 10744 + "\": has active device admin"); 10745 return false; 10746 } 10747 10748 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 10749 if (packageName.equals(activeLauncherPackageName)) { 10750 Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName 10751 + "\" because it is set as the active launcher"); 10752 return false; 10753 } 10754 10755 final PackageParser.Package pkg = mPackages.get(packageName); 10756 if (pkg != null && isPrivilegedApp(pkg)) { 10757 Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName 10758 + "\" because it is a privileged app"); 10759 return false; 10760 } 10761 10762 return true; 10763 } 10764 10765 private String getActiveLauncherPackageName(int userId) { 10766 Intent intent = new Intent(Intent.ACTION_MAIN); 10767 intent.addCategory(Intent.CATEGORY_HOME); 10768 ResolveInfo resolveInfo = resolveIntent( 10769 intent, 10770 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 10771 PackageManager.MATCH_DEFAULT_ONLY, 10772 userId); 10773 10774 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 10775 } 10776 10777 @Override 10778 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 10779 mContext.enforceCallingOrSelfPermission( 10780 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10781 "Only package verification agents can verify applications"); 10782 10783 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10784 final PackageVerificationResponse response = new PackageVerificationResponse( 10785 verificationCode, Binder.getCallingUid()); 10786 msg.arg1 = id; 10787 msg.obj = response; 10788 mHandler.sendMessage(msg); 10789 } 10790 10791 @Override 10792 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 10793 long millisecondsToDelay) { 10794 mContext.enforceCallingOrSelfPermission( 10795 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10796 "Only package verification agents can extend verification timeouts"); 10797 10798 final PackageVerificationState state = mPendingVerification.get(id); 10799 final PackageVerificationResponse response = new PackageVerificationResponse( 10800 verificationCodeAtTimeout, Binder.getCallingUid()); 10801 10802 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 10803 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 10804 } 10805 if (millisecondsToDelay < 0) { 10806 millisecondsToDelay = 0; 10807 } 10808 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 10809 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 10810 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 10811 } 10812 10813 if ((state != null) && !state.timeoutExtended()) { 10814 state.extendTimeout(); 10815 10816 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10817 msg.arg1 = id; 10818 msg.obj = response; 10819 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 10820 } 10821 } 10822 10823 private void broadcastPackageVerified(int verificationId, Uri packageUri, 10824 int verificationCode, UserHandle user) { 10825 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 10826 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 10827 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10828 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10829 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 10830 10831 mContext.sendBroadcastAsUser(intent, user, 10832 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 10833 } 10834 10835 private ComponentName matchComponentForVerifier(String packageName, 10836 List<ResolveInfo> receivers) { 10837 ActivityInfo targetReceiver = null; 10838 10839 final int NR = receivers.size(); 10840 for (int i = 0; i < NR; i++) { 10841 final ResolveInfo info = receivers.get(i); 10842 if (info.activityInfo == null) { 10843 continue; 10844 } 10845 10846 if (packageName.equals(info.activityInfo.packageName)) { 10847 targetReceiver = info.activityInfo; 10848 break; 10849 } 10850 } 10851 10852 if (targetReceiver == null) { 10853 return null; 10854 } 10855 10856 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 10857 } 10858 10859 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 10860 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 10861 if (pkgInfo.verifiers.length == 0) { 10862 return null; 10863 } 10864 10865 final int N = pkgInfo.verifiers.length; 10866 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 10867 for (int i = 0; i < N; i++) { 10868 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 10869 10870 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 10871 receivers); 10872 if (comp == null) { 10873 continue; 10874 } 10875 10876 final int verifierUid = getUidForVerifier(verifierInfo); 10877 if (verifierUid == -1) { 10878 continue; 10879 } 10880 10881 if (DEBUG_VERIFY) { 10882 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 10883 + " with the correct signature"); 10884 } 10885 sufficientVerifiers.add(comp); 10886 verificationState.addSufficientVerifier(verifierUid); 10887 } 10888 10889 return sufficientVerifiers; 10890 } 10891 10892 private int getUidForVerifier(VerifierInfo verifierInfo) { 10893 synchronized (mPackages) { 10894 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 10895 if (pkg == null) { 10896 return -1; 10897 } else if (pkg.mSignatures.length != 1) { 10898 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10899 + " has more than one signature; ignoring"); 10900 return -1; 10901 } 10902 10903 /* 10904 * If the public key of the package's signature does not match 10905 * our expected public key, then this is a different package and 10906 * we should skip. 10907 */ 10908 10909 final byte[] expectedPublicKey; 10910 try { 10911 final Signature verifierSig = pkg.mSignatures[0]; 10912 final PublicKey publicKey = verifierSig.getPublicKey(); 10913 expectedPublicKey = publicKey.getEncoded(); 10914 } catch (CertificateException e) { 10915 return -1; 10916 } 10917 10918 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 10919 10920 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 10921 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10922 + " does not have the expected public key; ignoring"); 10923 return -1; 10924 } 10925 10926 return pkg.applicationInfo.uid; 10927 } 10928 } 10929 10930 @Override 10931 public void finishPackageInstall(int token) { 10932 enforceSystemOrRoot("Only the system is allowed to finish installs"); 10933 10934 if (DEBUG_INSTALL) { 10935 Slog.v(TAG, "BM finishing package install for " + token); 10936 } 10937 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10938 10939 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10940 mHandler.sendMessage(msg); 10941 } 10942 10943 /** 10944 * Get the verification agent timeout. 10945 * 10946 * @return verification timeout in milliseconds 10947 */ 10948 private long getVerificationTimeout() { 10949 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 10950 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 10951 DEFAULT_VERIFICATION_TIMEOUT); 10952 } 10953 10954 /** 10955 * Get the default verification agent response code. 10956 * 10957 * @return default verification response code 10958 */ 10959 private int getDefaultVerificationResponse() { 10960 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10961 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 10962 DEFAULT_VERIFICATION_RESPONSE); 10963 } 10964 10965 /** 10966 * Check whether or not package verification has been enabled. 10967 * 10968 * @return true if verification should be performed 10969 */ 10970 private boolean isVerificationEnabled(int userId, int installFlags) { 10971 if (!DEFAULT_VERIFY_ENABLE) { 10972 return false; 10973 } 10974 // Ephemeral apps don't get the full verification treatment 10975 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10976 if (DEBUG_EPHEMERAL) { 10977 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 10978 } 10979 return false; 10980 } 10981 10982 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 10983 10984 // Check if installing from ADB 10985 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 10986 // Do not run verification in a test harness environment 10987 if (ActivityManager.isRunningInTestHarness()) { 10988 return false; 10989 } 10990 if (ensureVerifyAppsEnabled) { 10991 return true; 10992 } 10993 // Check if the developer does not want package verification for ADB installs 10994 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10995 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 10996 return false; 10997 } 10998 } 10999 11000 if (ensureVerifyAppsEnabled) { 11001 return true; 11002 } 11003 11004 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11005 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11006 } 11007 11008 @Override 11009 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11010 throws RemoteException { 11011 mContext.enforceCallingOrSelfPermission( 11012 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11013 "Only intentfilter verification agents can verify applications"); 11014 11015 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11016 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11017 Binder.getCallingUid(), verificationCode, failedDomains); 11018 msg.arg1 = id; 11019 msg.obj = response; 11020 mHandler.sendMessage(msg); 11021 } 11022 11023 @Override 11024 public int getIntentVerificationStatus(String packageName, int userId) { 11025 synchronized (mPackages) { 11026 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11027 } 11028 } 11029 11030 @Override 11031 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11032 mContext.enforceCallingOrSelfPermission( 11033 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11034 11035 boolean result = false; 11036 synchronized (mPackages) { 11037 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11038 } 11039 if (result) { 11040 scheduleWritePackageRestrictionsLocked(userId); 11041 } 11042 return result; 11043 } 11044 11045 @Override 11046 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 11047 synchronized (mPackages) { 11048 return mSettings.getIntentFilterVerificationsLPr(packageName); 11049 } 11050 } 11051 11052 @Override 11053 public List<IntentFilter> getAllIntentFilters(String packageName) { 11054 if (TextUtils.isEmpty(packageName)) { 11055 return Collections.<IntentFilter>emptyList(); 11056 } 11057 synchronized (mPackages) { 11058 PackageParser.Package pkg = mPackages.get(packageName); 11059 if (pkg == null || pkg.activities == null) { 11060 return Collections.<IntentFilter>emptyList(); 11061 } 11062 final int count = pkg.activities.size(); 11063 ArrayList<IntentFilter> result = new ArrayList<>(); 11064 for (int n=0; n<count; n++) { 11065 PackageParser.Activity activity = pkg.activities.get(n); 11066 if (activity.intents != null && activity.intents.size() > 0) { 11067 result.addAll(activity.intents); 11068 } 11069 } 11070 return result; 11071 } 11072 } 11073 11074 @Override 11075 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11076 mContext.enforceCallingOrSelfPermission( 11077 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11078 11079 synchronized (mPackages) { 11080 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11081 if (packageName != null) { 11082 result |= updateIntentVerificationStatus(packageName, 11083 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11084 userId); 11085 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11086 packageName, userId); 11087 } 11088 return result; 11089 } 11090 } 11091 11092 @Override 11093 public String getDefaultBrowserPackageName(int userId) { 11094 synchronized (mPackages) { 11095 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11096 } 11097 } 11098 11099 /** 11100 * Get the "allow unknown sources" setting. 11101 * 11102 * @return the current "allow unknown sources" setting 11103 */ 11104 private int getUnknownSourcesSettings() { 11105 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11106 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 11107 -1); 11108 } 11109 11110 @Override 11111 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11112 final int uid = Binder.getCallingUid(); 11113 // writer 11114 synchronized (mPackages) { 11115 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11116 if (targetPackageSetting == null) { 11117 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11118 } 11119 11120 PackageSetting installerPackageSetting; 11121 if (installerPackageName != null) { 11122 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11123 if (installerPackageSetting == null) { 11124 throw new IllegalArgumentException("Unknown installer package: " 11125 + installerPackageName); 11126 } 11127 } else { 11128 installerPackageSetting = null; 11129 } 11130 11131 Signature[] callerSignature; 11132 Object obj = mSettings.getUserIdLPr(uid); 11133 if (obj != null) { 11134 if (obj instanceof SharedUserSetting) { 11135 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11136 } else if (obj instanceof PackageSetting) { 11137 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11138 } else { 11139 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11140 } 11141 } else { 11142 throw new SecurityException("Unknown calling UID: " + uid); 11143 } 11144 11145 // Verify: can't set installerPackageName to a package that is 11146 // not signed with the same cert as the caller. 11147 if (installerPackageSetting != null) { 11148 if (compareSignatures(callerSignature, 11149 installerPackageSetting.signatures.mSignatures) 11150 != PackageManager.SIGNATURE_MATCH) { 11151 throw new SecurityException( 11152 "Caller does not have same cert as new installer package " 11153 + installerPackageName); 11154 } 11155 } 11156 11157 // Verify: if target already has an installer package, it must 11158 // be signed with the same cert as the caller. 11159 if (targetPackageSetting.installerPackageName != null) { 11160 PackageSetting setting = mSettings.mPackages.get( 11161 targetPackageSetting.installerPackageName); 11162 // If the currently set package isn't valid, then it's always 11163 // okay to change it. 11164 if (setting != null) { 11165 if (compareSignatures(callerSignature, 11166 setting.signatures.mSignatures) 11167 != PackageManager.SIGNATURE_MATCH) { 11168 throw new SecurityException( 11169 "Caller does not have same cert as old installer package " 11170 + targetPackageSetting.installerPackageName); 11171 } 11172 } 11173 } 11174 11175 // Okay! 11176 targetPackageSetting.installerPackageName = installerPackageName; 11177 scheduleWriteSettingsLocked(); 11178 } 11179 } 11180 11181 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 11182 // Queue up an async operation since the package installation may take a little while. 11183 mHandler.post(new Runnable() { 11184 public void run() { 11185 mHandler.removeCallbacks(this); 11186 // Result object to be returned 11187 PackageInstalledInfo res = new PackageInstalledInfo(); 11188 res.setReturnCode(currentStatus); 11189 res.uid = -1; 11190 res.pkg = null; 11191 res.removedInfo = null; 11192 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11193 args.doPreInstall(res.returnCode); 11194 synchronized (mInstallLock) { 11195 installPackageTracedLI(args, res); 11196 } 11197 args.doPostInstall(res.returnCode, res.uid); 11198 } 11199 11200 // A restore should be performed at this point if (a) the install 11201 // succeeded, (b) the operation is not an update, and (c) the new 11202 // package has not opted out of backup participation. 11203 final boolean update = res.removedInfo != null 11204 && res.removedInfo.removedPackage != null; 11205 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 11206 boolean doRestore = !update 11207 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 11208 11209 // Set up the post-install work request bookkeeping. This will be used 11210 // and cleaned up by the post-install event handling regardless of whether 11211 // there's a restore pass performed. Token values are >= 1. 11212 int token; 11213 if (mNextInstallToken < 0) mNextInstallToken = 1; 11214 token = mNextInstallToken++; 11215 11216 PostInstallData data = new PostInstallData(args, res); 11217 mRunningInstalls.put(token, data); 11218 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 11219 11220 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 11221 // Pass responsibility to the Backup Manager. It will perform a 11222 // restore if appropriate, then pass responsibility back to the 11223 // Package Manager to run the post-install observer callbacks 11224 // and broadcasts. 11225 IBackupManager bm = IBackupManager.Stub.asInterface( 11226 ServiceManager.getService(Context.BACKUP_SERVICE)); 11227 if (bm != null) { 11228 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 11229 + " to BM for possible restore"); 11230 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11231 try { 11232 // TODO: http://b/22388012 11233 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 11234 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 11235 } else { 11236 doRestore = false; 11237 } 11238 } catch (RemoteException e) { 11239 // can't happen; the backup manager is local 11240 } catch (Exception e) { 11241 Slog.e(TAG, "Exception trying to enqueue restore", e); 11242 doRestore = false; 11243 } 11244 } else { 11245 Slog.e(TAG, "Backup Manager not found!"); 11246 doRestore = false; 11247 } 11248 } 11249 11250 if (!doRestore) { 11251 // No restore possible, or the Backup Manager was mysteriously not 11252 // available -- just fire the post-install work request directly. 11253 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 11254 11255 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 11256 11257 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11258 mHandler.sendMessage(msg); 11259 } 11260 } 11261 }); 11262 } 11263 11264 private abstract class HandlerParams { 11265 private static final int MAX_RETRIES = 4; 11266 11267 /** 11268 * Number of times startCopy() has been attempted and had a non-fatal 11269 * error. 11270 */ 11271 private int mRetries = 0; 11272 11273 /** User handle for the user requesting the information or installation. */ 11274 private final UserHandle mUser; 11275 String traceMethod; 11276 int traceCookie; 11277 11278 HandlerParams(UserHandle user) { 11279 mUser = user; 11280 } 11281 11282 UserHandle getUser() { 11283 return mUser; 11284 } 11285 11286 HandlerParams setTraceMethod(String traceMethod) { 11287 this.traceMethod = traceMethod; 11288 return this; 11289 } 11290 11291 HandlerParams setTraceCookie(int traceCookie) { 11292 this.traceCookie = traceCookie; 11293 return this; 11294 } 11295 11296 final boolean startCopy() { 11297 boolean res; 11298 try { 11299 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 11300 11301 if (++mRetries > MAX_RETRIES) { 11302 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 11303 mHandler.sendEmptyMessage(MCS_GIVE_UP); 11304 handleServiceError(); 11305 return false; 11306 } else { 11307 handleStartCopy(); 11308 res = true; 11309 } 11310 } catch (RemoteException e) { 11311 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 11312 mHandler.sendEmptyMessage(MCS_RECONNECT); 11313 res = false; 11314 } 11315 handleReturnCode(); 11316 return res; 11317 } 11318 11319 final void serviceError() { 11320 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 11321 handleServiceError(); 11322 handleReturnCode(); 11323 } 11324 11325 abstract void handleStartCopy() throws RemoteException; 11326 abstract void handleServiceError(); 11327 abstract void handleReturnCode(); 11328 } 11329 11330 class MeasureParams extends HandlerParams { 11331 private final PackageStats mStats; 11332 private boolean mSuccess; 11333 11334 private final IPackageStatsObserver mObserver; 11335 11336 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 11337 super(new UserHandle(stats.userHandle)); 11338 mObserver = observer; 11339 mStats = stats; 11340 } 11341 11342 @Override 11343 public String toString() { 11344 return "MeasureParams{" 11345 + Integer.toHexString(System.identityHashCode(this)) 11346 + " " + mStats.packageName + "}"; 11347 } 11348 11349 @Override 11350 void handleStartCopy() throws RemoteException { 11351 synchronized (mInstallLock) { 11352 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 11353 } 11354 11355 if (mSuccess) { 11356 final boolean mounted; 11357 if (Environment.isExternalStorageEmulated()) { 11358 mounted = true; 11359 } else { 11360 final String status = Environment.getExternalStorageState(); 11361 mounted = (Environment.MEDIA_MOUNTED.equals(status) 11362 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 11363 } 11364 11365 if (mounted) { 11366 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 11367 11368 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 11369 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 11370 11371 mStats.externalDataSize = calculateDirectorySize(mContainerService, 11372 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 11373 11374 // Always subtract cache size, since it's a subdirectory 11375 mStats.externalDataSize -= mStats.externalCacheSize; 11376 11377 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 11378 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 11379 11380 mStats.externalObbSize = calculateDirectorySize(mContainerService, 11381 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 11382 } 11383 } 11384 } 11385 11386 @Override 11387 void handleReturnCode() { 11388 if (mObserver != null) { 11389 try { 11390 mObserver.onGetStatsCompleted(mStats, mSuccess); 11391 } catch (RemoteException e) { 11392 Slog.i(TAG, "Observer no longer exists."); 11393 } 11394 } 11395 } 11396 11397 @Override 11398 void handleServiceError() { 11399 Slog.e(TAG, "Could not measure application " + mStats.packageName 11400 + " external storage"); 11401 } 11402 } 11403 11404 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 11405 throws RemoteException { 11406 long result = 0; 11407 for (File path : paths) { 11408 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 11409 } 11410 return result; 11411 } 11412 11413 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 11414 for (File path : paths) { 11415 try { 11416 mcs.clearDirectory(path.getAbsolutePath()); 11417 } catch (RemoteException e) { 11418 } 11419 } 11420 } 11421 11422 static class OriginInfo { 11423 /** 11424 * Location where install is coming from, before it has been 11425 * copied/renamed into place. This could be a single monolithic APK 11426 * file, or a cluster directory. This location may be untrusted. 11427 */ 11428 final File file; 11429 final String cid; 11430 11431 /** 11432 * Flag indicating that {@link #file} or {@link #cid} has already been 11433 * staged, meaning downstream users don't need to defensively copy the 11434 * contents. 11435 */ 11436 final boolean staged; 11437 11438 /** 11439 * Flag indicating that {@link #file} or {@link #cid} is an already 11440 * installed app that is being moved. 11441 */ 11442 final boolean existing; 11443 11444 final String resolvedPath; 11445 final File resolvedFile; 11446 11447 static OriginInfo fromNothing() { 11448 return new OriginInfo(null, null, false, false); 11449 } 11450 11451 static OriginInfo fromUntrustedFile(File file) { 11452 return new OriginInfo(file, null, false, false); 11453 } 11454 11455 static OriginInfo fromExistingFile(File file) { 11456 return new OriginInfo(file, null, false, true); 11457 } 11458 11459 static OriginInfo fromStagedFile(File file) { 11460 return new OriginInfo(file, null, true, false); 11461 } 11462 11463 static OriginInfo fromStagedContainer(String cid) { 11464 return new OriginInfo(null, cid, true, false); 11465 } 11466 11467 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 11468 this.file = file; 11469 this.cid = cid; 11470 this.staged = staged; 11471 this.existing = existing; 11472 11473 if (cid != null) { 11474 resolvedPath = PackageHelper.getSdDir(cid); 11475 resolvedFile = new File(resolvedPath); 11476 } else if (file != null) { 11477 resolvedPath = file.getAbsolutePath(); 11478 resolvedFile = file; 11479 } else { 11480 resolvedPath = null; 11481 resolvedFile = null; 11482 } 11483 } 11484 } 11485 11486 static class MoveInfo { 11487 final int moveId; 11488 final String fromUuid; 11489 final String toUuid; 11490 final String packageName; 11491 final String dataAppName; 11492 final int appId; 11493 final String seinfo; 11494 final int targetSdkVersion; 11495 11496 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 11497 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 11498 this.moveId = moveId; 11499 this.fromUuid = fromUuid; 11500 this.toUuid = toUuid; 11501 this.packageName = packageName; 11502 this.dataAppName = dataAppName; 11503 this.appId = appId; 11504 this.seinfo = seinfo; 11505 this.targetSdkVersion = targetSdkVersion; 11506 } 11507 } 11508 11509 class InstallParams extends HandlerParams { 11510 final OriginInfo origin; 11511 final MoveInfo move; 11512 final IPackageInstallObserver2 observer; 11513 int installFlags; 11514 final String installerPackageName; 11515 final String volumeUuid; 11516 final VerificationParams verificationParams; 11517 private InstallArgs mArgs; 11518 private int mRet; 11519 final String packageAbiOverride; 11520 final String[] grantedRuntimePermissions; 11521 11522 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11523 int installFlags, String installerPackageName, String volumeUuid, 11524 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 11525 String[] grantedPermissions) { 11526 super(user); 11527 this.origin = origin; 11528 this.move = move; 11529 this.observer = observer; 11530 this.installFlags = installFlags; 11531 this.installerPackageName = installerPackageName; 11532 this.volumeUuid = volumeUuid; 11533 this.verificationParams = verificationParams; 11534 this.packageAbiOverride = packageAbiOverride; 11535 this.grantedRuntimePermissions = grantedPermissions; 11536 } 11537 11538 @Override 11539 public String toString() { 11540 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 11541 + " file=" + origin.file + " cid=" + origin.cid + "}"; 11542 } 11543 11544 private int installLocationPolicy(PackageInfoLite pkgLite) { 11545 String packageName = pkgLite.packageName; 11546 int installLocation = pkgLite.installLocation; 11547 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11548 // reader 11549 synchronized (mPackages) { 11550 // Currently installed package which the new package is attempting to replace or 11551 // null if no such package is installed. 11552 PackageParser.Package installedPkg = mPackages.get(packageName); 11553 // Package which currently owns the data which the new package will own if installed. 11554 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 11555 // will be null whereas dataOwnerPkg will contain information about the package 11556 // which was uninstalled while keeping its data. 11557 PackageParser.Package dataOwnerPkg = installedPkg; 11558 if (dataOwnerPkg == null) { 11559 PackageSetting ps = mSettings.mPackages.get(packageName); 11560 if (ps != null) { 11561 dataOwnerPkg = ps.pkg; 11562 } 11563 } 11564 11565 if (dataOwnerPkg != null) { 11566 // If installed, the package will get access to data left on the device by its 11567 // predecessor. As a security measure, this is permited only if this is not a 11568 // version downgrade or if the predecessor package is marked as debuggable and 11569 // a downgrade is explicitly requested. 11570 if (((dataOwnerPkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) 11571 || ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0)) { 11572 try { 11573 checkDowngrade(dataOwnerPkg, pkgLite); 11574 } catch (PackageManagerException e) { 11575 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 11576 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 11577 } 11578 } 11579 } 11580 11581 if (installedPkg != null) { 11582 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11583 // Check for updated system application. 11584 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11585 if (onSd) { 11586 Slog.w(TAG, "Cannot install update to system app on sdcard"); 11587 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 11588 } 11589 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11590 } else { 11591 if (onSd) { 11592 // Install flag overrides everything. 11593 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11594 } 11595 // If current upgrade specifies particular preference 11596 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 11597 // Application explicitly specified internal. 11598 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11599 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 11600 // App explictly prefers external. Let policy decide 11601 } else { 11602 // Prefer previous location 11603 if (isExternal(installedPkg)) { 11604 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11605 } 11606 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11607 } 11608 } 11609 } else { 11610 // Invalid install. Return error code 11611 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 11612 } 11613 } 11614 } 11615 // All the special cases have been taken care of. 11616 // Return result based on recommended install location. 11617 if (onSd) { 11618 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11619 } 11620 return pkgLite.recommendedInstallLocation; 11621 } 11622 11623 /* 11624 * Invoke remote method to get package information and install 11625 * location values. Override install location based on default 11626 * policy if needed and then create install arguments based 11627 * on the install location. 11628 */ 11629 public void handleStartCopy() throws RemoteException { 11630 int ret = PackageManager.INSTALL_SUCCEEDED; 11631 11632 // If we're already staged, we've firmly committed to an install location 11633 if (origin.staged) { 11634 if (origin.file != null) { 11635 installFlags |= PackageManager.INSTALL_INTERNAL; 11636 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11637 } else if (origin.cid != null) { 11638 installFlags |= PackageManager.INSTALL_EXTERNAL; 11639 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11640 } else { 11641 throw new IllegalStateException("Invalid stage location"); 11642 } 11643 } 11644 11645 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11646 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 11647 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11648 PackageInfoLite pkgLite = null; 11649 11650 if (onInt && onSd) { 11651 // Check if both bits are set. 11652 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 11653 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11654 } else if (onSd && ephemeral) { 11655 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 11656 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11657 } else { 11658 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 11659 packageAbiOverride); 11660 11661 if (DEBUG_EPHEMERAL && ephemeral) { 11662 Slog.v(TAG, "pkgLite for install: " + pkgLite); 11663 } 11664 11665 /* 11666 * If we have too little free space, try to free cache 11667 * before giving up. 11668 */ 11669 if (!origin.staged && pkgLite.recommendedInstallLocation 11670 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11671 // TODO: focus freeing disk space on the target device 11672 final StorageManager storage = StorageManager.from(mContext); 11673 final long lowThreshold = storage.getStorageLowBytes( 11674 Environment.getDataDirectory()); 11675 11676 final long sizeBytes = mContainerService.calculateInstalledSize( 11677 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 11678 11679 try { 11680 mInstaller.freeCache(null, sizeBytes + lowThreshold); 11681 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 11682 installFlags, packageAbiOverride); 11683 } catch (InstallerException e) { 11684 Slog.w(TAG, "Failed to free cache", e); 11685 } 11686 11687 /* 11688 * The cache free must have deleted the file we 11689 * downloaded to install. 11690 * 11691 * TODO: fix the "freeCache" call to not delete 11692 * the file we care about. 11693 */ 11694 if (pkgLite.recommendedInstallLocation 11695 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11696 pkgLite.recommendedInstallLocation 11697 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 11698 } 11699 } 11700 } 11701 11702 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11703 int loc = pkgLite.recommendedInstallLocation; 11704 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 11705 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11706 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 11707 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 11708 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11709 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11710 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 11711 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 11712 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11713 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 11714 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 11715 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 11716 } else { 11717 // Override with defaults if needed. 11718 loc = installLocationPolicy(pkgLite); 11719 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 11720 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 11721 } else if (!onSd && !onInt) { 11722 // Override install location with flags 11723 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 11724 // Set the flag to install on external media. 11725 installFlags |= PackageManager.INSTALL_EXTERNAL; 11726 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11727 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 11728 if (DEBUG_EPHEMERAL) { 11729 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 11730 } 11731 installFlags |= PackageManager.INSTALL_EPHEMERAL; 11732 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 11733 |PackageManager.INSTALL_INTERNAL); 11734 } else { 11735 // Make sure the flag for installing on external 11736 // media is unset 11737 installFlags |= PackageManager.INSTALL_INTERNAL; 11738 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11739 } 11740 } 11741 } 11742 } 11743 11744 final InstallArgs args = createInstallArgs(this); 11745 mArgs = args; 11746 11747 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11748 // TODO: http://b/22976637 11749 // Apps installed for "all" users use the device owner to verify the app 11750 UserHandle verifierUser = getUser(); 11751 if (verifierUser == UserHandle.ALL) { 11752 verifierUser = UserHandle.SYSTEM; 11753 } 11754 11755 /* 11756 * Determine if we have any installed package verifiers. If we 11757 * do, then we'll defer to them to verify the packages. 11758 */ 11759 final int requiredUid = mRequiredVerifierPackage == null ? -1 11760 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 11761 verifierUser.getIdentifier()); 11762 if (!origin.existing && requiredUid != -1 11763 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 11764 final Intent verification = new Intent( 11765 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 11766 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 11767 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 11768 PACKAGE_MIME_TYPE); 11769 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11770 11771 // Query all live verifiers based on current user state 11772 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 11773 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 11774 11775 if (DEBUG_VERIFY) { 11776 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 11777 + verification.toString() + " with " + pkgLite.verifiers.length 11778 + " optional verifiers"); 11779 } 11780 11781 final int verificationId = mPendingVerificationToken++; 11782 11783 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11784 11785 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 11786 installerPackageName); 11787 11788 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 11789 installFlags); 11790 11791 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 11792 pkgLite.packageName); 11793 11794 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 11795 pkgLite.versionCode); 11796 11797 if (verificationParams != null) { 11798 if (verificationParams.getVerificationURI() != null) { 11799 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 11800 verificationParams.getVerificationURI()); 11801 } 11802 if (verificationParams.getOriginatingURI() != null) { 11803 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 11804 verificationParams.getOriginatingURI()); 11805 } 11806 if (verificationParams.getReferrer() != null) { 11807 verification.putExtra(Intent.EXTRA_REFERRER, 11808 verificationParams.getReferrer()); 11809 } 11810 if (verificationParams.getOriginatingUid() >= 0) { 11811 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 11812 verificationParams.getOriginatingUid()); 11813 } 11814 if (verificationParams.getInstallerUid() >= 0) { 11815 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 11816 verificationParams.getInstallerUid()); 11817 } 11818 } 11819 11820 final PackageVerificationState verificationState = new PackageVerificationState( 11821 requiredUid, args); 11822 11823 mPendingVerification.append(verificationId, verificationState); 11824 11825 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 11826 receivers, verificationState); 11827 11828 /* 11829 * If any sufficient verifiers were listed in the package 11830 * manifest, attempt to ask them. 11831 */ 11832 if (sufficientVerifiers != null) { 11833 final int N = sufficientVerifiers.size(); 11834 if (N == 0) { 11835 Slog.i(TAG, "Additional verifiers required, but none installed."); 11836 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 11837 } else { 11838 for (int i = 0; i < N; i++) { 11839 final ComponentName verifierComponent = sufficientVerifiers.get(i); 11840 11841 final Intent sufficientIntent = new Intent(verification); 11842 sufficientIntent.setComponent(verifierComponent); 11843 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 11844 } 11845 } 11846 } 11847 11848 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 11849 mRequiredVerifierPackage, receivers); 11850 if (ret == PackageManager.INSTALL_SUCCEEDED 11851 && mRequiredVerifierPackage != null) { 11852 Trace.asyncTraceBegin( 11853 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 11854 /* 11855 * Send the intent to the required verification agent, 11856 * but only start the verification timeout after the 11857 * target BroadcastReceivers have run. 11858 */ 11859 verification.setComponent(requiredVerifierComponent); 11860 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 11861 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11862 new BroadcastReceiver() { 11863 @Override 11864 public void onReceive(Context context, Intent intent) { 11865 final Message msg = mHandler 11866 .obtainMessage(CHECK_PENDING_VERIFICATION); 11867 msg.arg1 = verificationId; 11868 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 11869 } 11870 }, null, 0, null, null); 11871 11872 /* 11873 * We don't want the copy to proceed until verification 11874 * succeeds, so null out this field. 11875 */ 11876 mArgs = null; 11877 } 11878 } else { 11879 /* 11880 * No package verification is enabled, so immediately start 11881 * the remote call to initiate copy using temporary file. 11882 */ 11883 ret = args.copyApk(mContainerService, true); 11884 } 11885 } 11886 11887 mRet = ret; 11888 } 11889 11890 @Override 11891 void handleReturnCode() { 11892 // If mArgs is null, then MCS couldn't be reached. When it 11893 // reconnects, it will try again to install. At that point, this 11894 // will succeed. 11895 if (mArgs != null) { 11896 processPendingInstall(mArgs, mRet); 11897 } 11898 } 11899 11900 @Override 11901 void handleServiceError() { 11902 mArgs = createInstallArgs(this); 11903 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11904 } 11905 11906 public boolean isForwardLocked() { 11907 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11908 } 11909 } 11910 11911 /** 11912 * Used during creation of InstallArgs 11913 * 11914 * @param installFlags package installation flags 11915 * @return true if should be installed on external storage 11916 */ 11917 private static boolean installOnExternalAsec(int installFlags) { 11918 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 11919 return false; 11920 } 11921 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 11922 return true; 11923 } 11924 return false; 11925 } 11926 11927 /** 11928 * Used during creation of InstallArgs 11929 * 11930 * @param installFlags package installation flags 11931 * @return true if should be installed as forward locked 11932 */ 11933 private static boolean installForwardLocked(int installFlags) { 11934 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11935 } 11936 11937 private InstallArgs createInstallArgs(InstallParams params) { 11938 if (params.move != null) { 11939 return new MoveInstallArgs(params); 11940 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 11941 return new AsecInstallArgs(params); 11942 } else { 11943 return new FileInstallArgs(params); 11944 } 11945 } 11946 11947 /** 11948 * Create args that describe an existing installed package. Typically used 11949 * when cleaning up old installs, or used as a move source. 11950 */ 11951 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 11952 String resourcePath, String[] instructionSets) { 11953 final boolean isInAsec; 11954 if (installOnExternalAsec(installFlags)) { 11955 /* Apps on SD card are always in ASEC containers. */ 11956 isInAsec = true; 11957 } else if (installForwardLocked(installFlags) 11958 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 11959 /* 11960 * Forward-locked apps are only in ASEC containers if they're the 11961 * new style 11962 */ 11963 isInAsec = true; 11964 } else { 11965 isInAsec = false; 11966 } 11967 11968 if (isInAsec) { 11969 return new AsecInstallArgs(codePath, instructionSets, 11970 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 11971 } else { 11972 return new FileInstallArgs(codePath, resourcePath, instructionSets); 11973 } 11974 } 11975 11976 static abstract class InstallArgs { 11977 /** @see InstallParams#origin */ 11978 final OriginInfo origin; 11979 /** @see InstallParams#move */ 11980 final MoveInfo move; 11981 11982 final IPackageInstallObserver2 observer; 11983 // Always refers to PackageManager flags only 11984 final int installFlags; 11985 final String installerPackageName; 11986 final String volumeUuid; 11987 final UserHandle user; 11988 final String abiOverride; 11989 final String[] installGrantPermissions; 11990 /** If non-null, drop an async trace when the install completes */ 11991 final String traceMethod; 11992 final int traceCookie; 11993 11994 // The list of instruction sets supported by this app. This is currently 11995 // only used during the rmdex() phase to clean up resources. We can get rid of this 11996 // if we move dex files under the common app path. 11997 /* nullable */ String[] instructionSets; 11998 11999 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12000 int installFlags, String installerPackageName, String volumeUuid, 12001 UserHandle user, String[] instructionSets, 12002 String abiOverride, String[] installGrantPermissions, 12003 String traceMethod, int traceCookie) { 12004 this.origin = origin; 12005 this.move = move; 12006 this.installFlags = installFlags; 12007 this.observer = observer; 12008 this.installerPackageName = installerPackageName; 12009 this.volumeUuid = volumeUuid; 12010 this.user = user; 12011 this.instructionSets = instructionSets; 12012 this.abiOverride = abiOverride; 12013 this.installGrantPermissions = installGrantPermissions; 12014 this.traceMethod = traceMethod; 12015 this.traceCookie = traceCookie; 12016 } 12017 12018 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12019 abstract int doPreInstall(int status); 12020 12021 /** 12022 * Rename package into final resting place. All paths on the given 12023 * scanned package should be updated to reflect the rename. 12024 */ 12025 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12026 abstract int doPostInstall(int status, int uid); 12027 12028 /** @see PackageSettingBase#codePathString */ 12029 abstract String getCodePath(); 12030 /** @see PackageSettingBase#resourcePathString */ 12031 abstract String getResourcePath(); 12032 12033 // Need installer lock especially for dex file removal. 12034 abstract void cleanUpResourcesLI(); 12035 abstract boolean doPostDeleteLI(boolean delete); 12036 12037 /** 12038 * Called before the source arguments are copied. This is used mostly 12039 * for MoveParams when it needs to read the source file to put it in the 12040 * destination. 12041 */ 12042 int doPreCopy() { 12043 return PackageManager.INSTALL_SUCCEEDED; 12044 } 12045 12046 /** 12047 * Called after the source arguments are copied. This is used mostly for 12048 * MoveParams when it needs to read the source file to put it in the 12049 * destination. 12050 * 12051 * @return 12052 */ 12053 int doPostCopy(int uid) { 12054 return PackageManager.INSTALL_SUCCEEDED; 12055 } 12056 12057 protected boolean isFwdLocked() { 12058 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12059 } 12060 12061 protected boolean isExternalAsec() { 12062 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12063 } 12064 12065 protected boolean isEphemeral() { 12066 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12067 } 12068 12069 UserHandle getUser() { 12070 return user; 12071 } 12072 } 12073 12074 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 12075 if (!allCodePaths.isEmpty()) { 12076 if (instructionSets == null) { 12077 throw new IllegalStateException("instructionSet == null"); 12078 } 12079 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 12080 for (String codePath : allCodePaths) { 12081 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 12082 try { 12083 mInstaller.rmdex(codePath, dexCodeInstructionSet); 12084 } catch (InstallerException ignored) { 12085 } 12086 } 12087 } 12088 } 12089 } 12090 12091 /** 12092 * Logic to handle installation of non-ASEC applications, including copying 12093 * and renaming logic. 12094 */ 12095 class FileInstallArgs extends InstallArgs { 12096 private File codeFile; 12097 private File resourceFile; 12098 12099 // Example topology: 12100 // /data/app/com.example/base.apk 12101 // /data/app/com.example/split_foo.apk 12102 // /data/app/com.example/lib/arm/libfoo.so 12103 // /data/app/com.example/lib/arm64/libfoo.so 12104 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 12105 12106 /** New install */ 12107 FileInstallArgs(InstallParams params) { 12108 super(params.origin, params.move, params.observer, params.installFlags, 12109 params.installerPackageName, params.volumeUuid, 12110 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12111 params.grantedRuntimePermissions, 12112 params.traceMethod, params.traceCookie); 12113 if (isFwdLocked()) { 12114 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 12115 } 12116 } 12117 12118 /** Existing install */ 12119 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 12120 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 12121 null, null, null, 0); 12122 this.codeFile = (codePath != null) ? new File(codePath) : null; 12123 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 12124 } 12125 12126 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12127 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 12128 try { 12129 return doCopyApk(imcs, temp); 12130 } finally { 12131 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12132 } 12133 } 12134 12135 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12136 if (origin.staged) { 12137 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 12138 codeFile = origin.file; 12139 resourceFile = origin.file; 12140 return PackageManager.INSTALL_SUCCEEDED; 12141 } 12142 12143 try { 12144 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12145 final File tempDir = 12146 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 12147 codeFile = tempDir; 12148 resourceFile = tempDir; 12149 } catch (IOException e) { 12150 Slog.w(TAG, "Failed to create copy file: " + e); 12151 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12152 } 12153 12154 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 12155 @Override 12156 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 12157 if (!FileUtils.isValidExtFilename(name)) { 12158 throw new IllegalArgumentException("Invalid filename: " + name); 12159 } 12160 try { 12161 final File file = new File(codeFile, name); 12162 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 12163 O_RDWR | O_CREAT, 0644); 12164 Os.chmod(file.getAbsolutePath(), 0644); 12165 return new ParcelFileDescriptor(fd); 12166 } catch (ErrnoException e) { 12167 throw new RemoteException("Failed to open: " + e.getMessage()); 12168 } 12169 } 12170 }; 12171 12172 int ret = PackageManager.INSTALL_SUCCEEDED; 12173 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 12174 if (ret != PackageManager.INSTALL_SUCCEEDED) { 12175 Slog.e(TAG, "Failed to copy package"); 12176 return ret; 12177 } 12178 12179 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 12180 NativeLibraryHelper.Handle handle = null; 12181 try { 12182 handle = NativeLibraryHelper.Handle.create(codeFile); 12183 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 12184 abiOverride); 12185 } catch (IOException e) { 12186 Slog.e(TAG, "Copying native libraries failed", e); 12187 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12188 } finally { 12189 IoUtils.closeQuietly(handle); 12190 } 12191 12192 return ret; 12193 } 12194 12195 int doPreInstall(int status) { 12196 if (status != PackageManager.INSTALL_SUCCEEDED) { 12197 cleanUp(); 12198 } 12199 return status; 12200 } 12201 12202 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12203 if (status != PackageManager.INSTALL_SUCCEEDED) { 12204 cleanUp(); 12205 return false; 12206 } 12207 12208 final File targetDir = codeFile.getParentFile(); 12209 final File beforeCodeFile = codeFile; 12210 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 12211 12212 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 12213 try { 12214 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 12215 } catch (ErrnoException e) { 12216 Slog.w(TAG, "Failed to rename", e); 12217 return false; 12218 } 12219 12220 if (!SELinux.restoreconRecursive(afterCodeFile)) { 12221 Slog.w(TAG, "Failed to restorecon"); 12222 return false; 12223 } 12224 12225 // Reflect the rename internally 12226 codeFile = afterCodeFile; 12227 resourceFile = afterCodeFile; 12228 12229 // Reflect the rename in scanned details 12230 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12231 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12232 afterCodeFile, pkg.baseCodePath)); 12233 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12234 afterCodeFile, pkg.splitCodePaths)); 12235 12236 // Reflect the rename in app info 12237 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12238 pkg.setApplicationInfoCodePath(pkg.codePath); 12239 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12240 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12241 pkg.setApplicationInfoResourcePath(pkg.codePath); 12242 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12243 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12244 12245 return true; 12246 } 12247 12248 int doPostInstall(int status, int uid) { 12249 if (status != PackageManager.INSTALL_SUCCEEDED) { 12250 cleanUp(); 12251 } 12252 return status; 12253 } 12254 12255 @Override 12256 String getCodePath() { 12257 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12258 } 12259 12260 @Override 12261 String getResourcePath() { 12262 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12263 } 12264 12265 private boolean cleanUp() { 12266 if (codeFile == null || !codeFile.exists()) { 12267 return false; 12268 } 12269 12270 removeCodePathLI(codeFile); 12271 12272 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 12273 resourceFile.delete(); 12274 } 12275 12276 return true; 12277 } 12278 12279 void cleanUpResourcesLI() { 12280 // Try enumerating all code paths before deleting 12281 List<String> allCodePaths = Collections.EMPTY_LIST; 12282 if (codeFile != null && codeFile.exists()) { 12283 try { 12284 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12285 allCodePaths = pkg.getAllCodePaths(); 12286 } catch (PackageParserException e) { 12287 // Ignored; we tried our best 12288 } 12289 } 12290 12291 cleanUp(); 12292 removeDexFiles(allCodePaths, instructionSets); 12293 } 12294 12295 boolean doPostDeleteLI(boolean delete) { 12296 // XXX err, shouldn't we respect the delete flag? 12297 cleanUpResourcesLI(); 12298 return true; 12299 } 12300 } 12301 12302 private boolean isAsecExternal(String cid) { 12303 final String asecPath = PackageHelper.getSdFilesystem(cid); 12304 return !asecPath.startsWith(mAsecInternalPath); 12305 } 12306 12307 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 12308 PackageManagerException { 12309 if (copyRet < 0) { 12310 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 12311 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 12312 throw new PackageManagerException(copyRet, message); 12313 } 12314 } 12315 } 12316 12317 /** 12318 * Extract the MountService "container ID" from the full code path of an 12319 * .apk. 12320 */ 12321 static String cidFromCodePath(String fullCodePath) { 12322 int eidx = fullCodePath.lastIndexOf("/"); 12323 String subStr1 = fullCodePath.substring(0, eidx); 12324 int sidx = subStr1.lastIndexOf("/"); 12325 return subStr1.substring(sidx+1, eidx); 12326 } 12327 12328 /** 12329 * Logic to handle installation of ASEC applications, including copying and 12330 * renaming logic. 12331 */ 12332 class AsecInstallArgs extends InstallArgs { 12333 static final String RES_FILE_NAME = "pkg.apk"; 12334 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 12335 12336 String cid; 12337 String packagePath; 12338 String resourcePath; 12339 12340 /** New install */ 12341 AsecInstallArgs(InstallParams params) { 12342 super(params.origin, params.move, params.observer, params.installFlags, 12343 params.installerPackageName, params.volumeUuid, 12344 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12345 params.grantedRuntimePermissions, 12346 params.traceMethod, params.traceCookie); 12347 } 12348 12349 /** Existing install */ 12350 AsecInstallArgs(String fullCodePath, String[] instructionSets, 12351 boolean isExternal, boolean isForwardLocked) { 12352 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 12353 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12354 instructionSets, null, null, null, 0); 12355 // Hackily pretend we're still looking at a full code path 12356 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 12357 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 12358 } 12359 12360 // Extract cid from fullCodePath 12361 int eidx = fullCodePath.lastIndexOf("/"); 12362 String subStr1 = fullCodePath.substring(0, eidx); 12363 int sidx = subStr1.lastIndexOf("/"); 12364 cid = subStr1.substring(sidx+1, eidx); 12365 setMountPath(subStr1); 12366 } 12367 12368 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 12369 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 12370 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12371 instructionSets, null, null, null, 0); 12372 this.cid = cid; 12373 setMountPath(PackageHelper.getSdDir(cid)); 12374 } 12375 12376 void createCopyFile() { 12377 cid = mInstallerService.allocateExternalStageCidLegacy(); 12378 } 12379 12380 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12381 if (origin.staged && origin.cid != null) { 12382 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 12383 cid = origin.cid; 12384 setMountPath(PackageHelper.getSdDir(cid)); 12385 return PackageManager.INSTALL_SUCCEEDED; 12386 } 12387 12388 if (temp) { 12389 createCopyFile(); 12390 } else { 12391 /* 12392 * Pre-emptively destroy the container since it's destroyed if 12393 * copying fails due to it existing anyway. 12394 */ 12395 PackageHelper.destroySdDir(cid); 12396 } 12397 12398 final String newMountPath = imcs.copyPackageToContainer( 12399 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 12400 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 12401 12402 if (newMountPath != null) { 12403 setMountPath(newMountPath); 12404 return PackageManager.INSTALL_SUCCEEDED; 12405 } else { 12406 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12407 } 12408 } 12409 12410 @Override 12411 String getCodePath() { 12412 return packagePath; 12413 } 12414 12415 @Override 12416 String getResourcePath() { 12417 return resourcePath; 12418 } 12419 12420 int doPreInstall(int status) { 12421 if (status != PackageManager.INSTALL_SUCCEEDED) { 12422 // Destroy container 12423 PackageHelper.destroySdDir(cid); 12424 } else { 12425 boolean mounted = PackageHelper.isContainerMounted(cid); 12426 if (!mounted) { 12427 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 12428 Process.SYSTEM_UID); 12429 if (newMountPath != null) { 12430 setMountPath(newMountPath); 12431 } else { 12432 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12433 } 12434 } 12435 } 12436 return status; 12437 } 12438 12439 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12440 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 12441 String newMountPath = null; 12442 if (PackageHelper.isContainerMounted(cid)) { 12443 // Unmount the container 12444 if (!PackageHelper.unMountSdDir(cid)) { 12445 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 12446 return false; 12447 } 12448 } 12449 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 12450 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 12451 " which might be stale. Will try to clean up."); 12452 // Clean up the stale container and proceed to recreate. 12453 if (!PackageHelper.destroySdDir(newCacheId)) { 12454 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 12455 return false; 12456 } 12457 // Successfully cleaned up stale container. Try to rename again. 12458 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 12459 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 12460 + " inspite of cleaning it up."); 12461 return false; 12462 } 12463 } 12464 if (!PackageHelper.isContainerMounted(newCacheId)) { 12465 Slog.w(TAG, "Mounting container " + newCacheId); 12466 newMountPath = PackageHelper.mountSdDir(newCacheId, 12467 getEncryptKey(), Process.SYSTEM_UID); 12468 } else { 12469 newMountPath = PackageHelper.getSdDir(newCacheId); 12470 } 12471 if (newMountPath == null) { 12472 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 12473 return false; 12474 } 12475 Log.i(TAG, "Succesfully renamed " + cid + 12476 " to " + newCacheId + 12477 " at new path: " + newMountPath); 12478 cid = newCacheId; 12479 12480 final File beforeCodeFile = new File(packagePath); 12481 setMountPath(newMountPath); 12482 final File afterCodeFile = new File(packagePath); 12483 12484 // Reflect the rename in scanned details 12485 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12486 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12487 afterCodeFile, pkg.baseCodePath)); 12488 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12489 afterCodeFile, pkg.splitCodePaths)); 12490 12491 // Reflect the rename in app info 12492 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12493 pkg.setApplicationInfoCodePath(pkg.codePath); 12494 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12495 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12496 pkg.setApplicationInfoResourcePath(pkg.codePath); 12497 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12498 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12499 12500 return true; 12501 } 12502 12503 private void setMountPath(String mountPath) { 12504 final File mountFile = new File(mountPath); 12505 12506 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 12507 if (monolithicFile.exists()) { 12508 packagePath = monolithicFile.getAbsolutePath(); 12509 if (isFwdLocked()) { 12510 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 12511 } else { 12512 resourcePath = packagePath; 12513 } 12514 } else { 12515 packagePath = mountFile.getAbsolutePath(); 12516 resourcePath = packagePath; 12517 } 12518 } 12519 12520 int doPostInstall(int status, int uid) { 12521 if (status != PackageManager.INSTALL_SUCCEEDED) { 12522 cleanUp(); 12523 } else { 12524 final int groupOwner; 12525 final String protectedFile; 12526 if (isFwdLocked()) { 12527 groupOwner = UserHandle.getSharedAppGid(uid); 12528 protectedFile = RES_FILE_NAME; 12529 } else { 12530 groupOwner = -1; 12531 protectedFile = null; 12532 } 12533 12534 if (uid < Process.FIRST_APPLICATION_UID 12535 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 12536 Slog.e(TAG, "Failed to finalize " + cid); 12537 PackageHelper.destroySdDir(cid); 12538 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12539 } 12540 12541 boolean mounted = PackageHelper.isContainerMounted(cid); 12542 if (!mounted) { 12543 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 12544 } 12545 } 12546 return status; 12547 } 12548 12549 private void cleanUp() { 12550 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 12551 12552 // Destroy secure container 12553 PackageHelper.destroySdDir(cid); 12554 } 12555 12556 private List<String> getAllCodePaths() { 12557 final File codeFile = new File(getCodePath()); 12558 if (codeFile != null && codeFile.exists()) { 12559 try { 12560 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12561 return pkg.getAllCodePaths(); 12562 } catch (PackageParserException e) { 12563 // Ignored; we tried our best 12564 } 12565 } 12566 return Collections.EMPTY_LIST; 12567 } 12568 12569 void cleanUpResourcesLI() { 12570 // Enumerate all code paths before deleting 12571 cleanUpResourcesLI(getAllCodePaths()); 12572 } 12573 12574 private void cleanUpResourcesLI(List<String> allCodePaths) { 12575 cleanUp(); 12576 removeDexFiles(allCodePaths, instructionSets); 12577 } 12578 12579 String getPackageName() { 12580 return getAsecPackageName(cid); 12581 } 12582 12583 boolean doPostDeleteLI(boolean delete) { 12584 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 12585 final List<String> allCodePaths = getAllCodePaths(); 12586 boolean mounted = PackageHelper.isContainerMounted(cid); 12587 if (mounted) { 12588 // Unmount first 12589 if (PackageHelper.unMountSdDir(cid)) { 12590 mounted = false; 12591 } 12592 } 12593 if (!mounted && delete) { 12594 cleanUpResourcesLI(allCodePaths); 12595 } 12596 return !mounted; 12597 } 12598 12599 @Override 12600 int doPreCopy() { 12601 if (isFwdLocked()) { 12602 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 12603 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 12604 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12605 } 12606 } 12607 12608 return PackageManager.INSTALL_SUCCEEDED; 12609 } 12610 12611 @Override 12612 int doPostCopy(int uid) { 12613 if (isFwdLocked()) { 12614 if (uid < Process.FIRST_APPLICATION_UID 12615 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 12616 RES_FILE_NAME)) { 12617 Slog.e(TAG, "Failed to finalize " + cid); 12618 PackageHelper.destroySdDir(cid); 12619 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12620 } 12621 } 12622 12623 return PackageManager.INSTALL_SUCCEEDED; 12624 } 12625 } 12626 12627 /** 12628 * Logic to handle movement of existing installed applications. 12629 */ 12630 class MoveInstallArgs extends InstallArgs { 12631 private File codeFile; 12632 private File resourceFile; 12633 12634 /** New install */ 12635 MoveInstallArgs(InstallParams params) { 12636 super(params.origin, params.move, params.observer, params.installFlags, 12637 params.installerPackageName, params.volumeUuid, 12638 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12639 params.grantedRuntimePermissions, 12640 params.traceMethod, params.traceCookie); 12641 } 12642 12643 int copyApk(IMediaContainerService imcs, boolean temp) { 12644 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 12645 + move.fromUuid + " to " + move.toUuid); 12646 synchronized (mInstaller) { 12647 try { 12648 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 12649 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 12650 } catch (InstallerException e) { 12651 Slog.w(TAG, "Failed to move app", e); 12652 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12653 } 12654 } 12655 12656 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 12657 resourceFile = codeFile; 12658 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 12659 12660 return PackageManager.INSTALL_SUCCEEDED; 12661 } 12662 12663 int doPreInstall(int status) { 12664 if (status != PackageManager.INSTALL_SUCCEEDED) { 12665 cleanUp(move.toUuid); 12666 } 12667 return status; 12668 } 12669 12670 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12671 if (status != PackageManager.INSTALL_SUCCEEDED) { 12672 cleanUp(move.toUuid); 12673 return false; 12674 } 12675 12676 // Reflect the move in app info 12677 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12678 pkg.setApplicationInfoCodePath(pkg.codePath); 12679 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12680 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12681 pkg.setApplicationInfoResourcePath(pkg.codePath); 12682 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12683 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12684 12685 return true; 12686 } 12687 12688 int doPostInstall(int status, int uid) { 12689 if (status == PackageManager.INSTALL_SUCCEEDED) { 12690 cleanUp(move.fromUuid); 12691 } else { 12692 cleanUp(move.toUuid); 12693 } 12694 return status; 12695 } 12696 12697 @Override 12698 String getCodePath() { 12699 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12700 } 12701 12702 @Override 12703 String getResourcePath() { 12704 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12705 } 12706 12707 private boolean cleanUp(String volumeUuid) { 12708 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 12709 move.dataAppName); 12710 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 12711 synchronized (mInstallLock) { 12712 // Clean up both app data and code 12713 removeDataDirsLI(volumeUuid, move.packageName); 12714 removeCodePathLI(codeFile); 12715 } 12716 return true; 12717 } 12718 12719 void cleanUpResourcesLI() { 12720 throw new UnsupportedOperationException(); 12721 } 12722 12723 boolean doPostDeleteLI(boolean delete) { 12724 throw new UnsupportedOperationException(); 12725 } 12726 } 12727 12728 static String getAsecPackageName(String packageCid) { 12729 int idx = packageCid.lastIndexOf("-"); 12730 if (idx == -1) { 12731 return packageCid; 12732 } 12733 return packageCid.substring(0, idx); 12734 } 12735 12736 // Utility method used to create code paths based on package name and available index. 12737 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 12738 String idxStr = ""; 12739 int idx = 1; 12740 // Fall back to default value of idx=1 if prefix is not 12741 // part of oldCodePath 12742 if (oldCodePath != null) { 12743 String subStr = oldCodePath; 12744 // Drop the suffix right away 12745 if (suffix != null && subStr.endsWith(suffix)) { 12746 subStr = subStr.substring(0, subStr.length() - suffix.length()); 12747 } 12748 // If oldCodePath already contains prefix find out the 12749 // ending index to either increment or decrement. 12750 int sidx = subStr.lastIndexOf(prefix); 12751 if (sidx != -1) { 12752 subStr = subStr.substring(sidx + prefix.length()); 12753 if (subStr != null) { 12754 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 12755 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 12756 } 12757 try { 12758 idx = Integer.parseInt(subStr); 12759 if (idx <= 1) { 12760 idx++; 12761 } else { 12762 idx--; 12763 } 12764 } catch(NumberFormatException e) { 12765 } 12766 } 12767 } 12768 } 12769 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 12770 return prefix + idxStr; 12771 } 12772 12773 private File getNextCodePath(File targetDir, String packageName) { 12774 int suffix = 1; 12775 File result; 12776 do { 12777 result = new File(targetDir, packageName + "-" + suffix); 12778 suffix++; 12779 } while (result.exists()); 12780 return result; 12781 } 12782 12783 // Utility method that returns the relative package path with respect 12784 // to the installation directory. Like say for /data/data/com.test-1.apk 12785 // string com.test-1 is returned. 12786 static String deriveCodePathName(String codePath) { 12787 if (codePath == null) { 12788 return null; 12789 } 12790 final File codeFile = new File(codePath); 12791 final String name = codeFile.getName(); 12792 if (codeFile.isDirectory()) { 12793 return name; 12794 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 12795 final int lastDot = name.lastIndexOf('.'); 12796 return name.substring(0, lastDot); 12797 } else { 12798 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 12799 return null; 12800 } 12801 } 12802 12803 static class PackageInstalledInfo { 12804 String name; 12805 int uid; 12806 // The set of users that originally had this package installed. 12807 int[] origUsers; 12808 // The set of users that now have this package installed. 12809 int[] newUsers; 12810 PackageParser.Package pkg; 12811 int returnCode; 12812 String returnMsg; 12813 PackageRemovedInfo removedInfo; 12814 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 12815 12816 public void setError(int code, String msg) { 12817 setReturnCode(code); 12818 setReturnMessage(msg); 12819 Slog.w(TAG, msg); 12820 } 12821 12822 public void setError(String msg, PackageParserException e) { 12823 setReturnCode(e.error); 12824 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 12825 Slog.w(TAG, msg, e); 12826 } 12827 12828 public void setError(String msg, PackageManagerException e) { 12829 returnCode = e.error; 12830 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 12831 Slog.w(TAG, msg, e); 12832 } 12833 12834 public void setReturnCode(int returnCode) { 12835 this.returnCode = returnCode; 12836 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 12837 for (int i = 0; i < childCount; i++) { 12838 addedChildPackages.valueAt(i).returnCode = returnCode; 12839 } 12840 } 12841 12842 private void setReturnMessage(String returnMsg) { 12843 this.returnMsg = returnMsg; 12844 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 12845 for (int i = 0; i < childCount; i++) { 12846 addedChildPackages.valueAt(i).returnMsg = returnMsg; 12847 } 12848 } 12849 12850 // In some error cases we want to convey more info back to the observer 12851 String origPackage; 12852 String origPermission; 12853 } 12854 12855 /* 12856 * Install a non-existing package. 12857 */ 12858 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12859 UserHandle user, String installerPackageName, String volumeUuid, 12860 PackageInstalledInfo res) { 12861 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 12862 12863 // Remember this for later, in case we need to rollback this install 12864 String pkgName = pkg.packageName; 12865 12866 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 12867 12868 synchronized(mPackages) { 12869 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 12870 // A package with the same name is already installed, though 12871 // it has been renamed to an older name. The package we 12872 // are trying to install should be installed as an update to 12873 // the existing one, but that has not been requested, so bail. 12874 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12875 + " without first uninstalling package running as " 12876 + mSettings.mRenamedPackages.get(pkgName)); 12877 return; 12878 } 12879 if (mPackages.containsKey(pkgName)) { 12880 // Don't allow installation over an existing package with the same name. 12881 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12882 + " without first uninstalling."); 12883 return; 12884 } 12885 } 12886 12887 try { 12888 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 12889 System.currentTimeMillis(), user); 12890 12891 updateSettingsLI(newPackage, installerPackageName, null, res, user); 12892 12893 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12894 prepareAppDataAfterInstall(newPackage); 12895 12896 } else { 12897 // Remove package from internal structures, but keep around any 12898 // data that might have already existed 12899 deletePackageLI(pkgName, UserHandle.ALL, false, null, 12900 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 12901 } 12902 } catch (PackageManagerException e) { 12903 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12904 } 12905 12906 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12907 } 12908 12909 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 12910 // Can't rotate keys during boot or if sharedUser. 12911 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 12912 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 12913 return false; 12914 } 12915 // app is using upgradeKeySets; make sure all are valid 12916 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12917 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 12918 for (int i = 0; i < upgradeKeySets.length; i++) { 12919 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 12920 Slog.wtf(TAG, "Package " 12921 + (oldPs.name != null ? oldPs.name : "<null>") 12922 + " contains upgrade-key-set reference to unknown key-set: " 12923 + upgradeKeySets[i] 12924 + " reverting to signatures check."); 12925 return false; 12926 } 12927 } 12928 return true; 12929 } 12930 12931 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 12932 // Upgrade keysets are being used. Determine if new package has a superset of the 12933 // required keys. 12934 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 12935 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12936 for (int i = 0; i < upgradeKeySets.length; i++) { 12937 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 12938 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 12939 return true; 12940 } 12941 } 12942 return false; 12943 } 12944 12945 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12946 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 12947 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 12948 12949 final PackageParser.Package oldPackage; 12950 final String pkgName = pkg.packageName; 12951 final int[] allUsers; 12952 12953 // First find the old package info and check signatures 12954 synchronized(mPackages) { 12955 oldPackage = mPackages.get(pkgName); 12956 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 12957 if (isEphemeral && !oldIsEphemeral) { 12958 // can't downgrade from full to ephemeral 12959 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 12960 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 12961 return; 12962 } 12963 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 12964 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12965 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12966 if (!checkUpgradeKeySetLP(ps, pkg)) { 12967 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12968 "New package not signed by keys specified by upgrade-keysets: " 12969 + pkgName); 12970 return; 12971 } 12972 } else { 12973 // default to original signature matching 12974 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 12975 != PackageManager.SIGNATURE_MATCH) { 12976 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12977 "New package has a different signature: " + pkgName); 12978 return; 12979 } 12980 } 12981 12982 // In case of rollback, remember per-user/profile install state 12983 allUsers = sUserManager.getUserIds(); 12984 } 12985 12986 // Update what is removed 12987 res.removedInfo = new PackageRemovedInfo(); 12988 res.removedInfo.uid = oldPackage.applicationInfo.uid; 12989 res.removedInfo.removedPackage = oldPackage.packageName; 12990 res.removedInfo.isUpdate = true; 12991 final int childCount = (oldPackage.childPackages != null) 12992 ? oldPackage.childPackages.size() : 0; 12993 for (int i = 0; i < childCount; i++) { 12994 boolean childPackageUpdated = false; 12995 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 12996 if (res.addedChildPackages != null) { 12997 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 12998 if (childRes != null) { 12999 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 13000 childRes.removedInfo.removedPackage = childPkg.packageName; 13001 childRes.removedInfo.isUpdate = true; 13002 childPackageUpdated = true; 13003 } 13004 } 13005 if (!childPackageUpdated) { 13006 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 13007 childRemovedRes.removedPackage = childPkg.packageName; 13008 childRemovedRes.isUpdate = false; 13009 childRemovedRes.dataRemoved = true; 13010 synchronized (mPackages) { 13011 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13012 if (childPs != null) { 13013 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 13014 } 13015 } 13016 if (res.removedInfo.removedChildPackages == null) { 13017 res.removedInfo.removedChildPackages = new ArrayMap<>(); 13018 } 13019 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 13020 } 13021 } 13022 13023 boolean sysPkg = (isSystemApp(oldPackage)); 13024 if (sysPkg) { 13025 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 13026 user, allUsers, installerPackageName, res); 13027 } else { 13028 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 13029 user, allUsers, installerPackageName, res); 13030 } 13031 } 13032 13033 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 13034 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13035 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13036 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 13037 + deletedPackage); 13038 13039 String pkgName = deletedPackage.packageName; 13040 boolean deletedPkg = true; 13041 boolean addedPkg = false; 13042 13043 final long origUpdateTime = (pkg.mExtras != null) 13044 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 13045 13046 // First delete the existing package while retaining the data directory 13047 if (!deletePackageLI(pkgName, null, true, allUsers, PackageManager.DELETE_KEEP_DATA, 13048 res.removedInfo, true, pkg)) { 13049 // If the existing package wasn't successfully deleted 13050 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 13051 deletedPkg = false; 13052 } else { 13053 // Successfully deleted the old package; proceed with replace. 13054 13055 // If deleted package lived in a container, give users a chance to 13056 // relinquish resources before killing. 13057 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 13058 if (DEBUG_INSTALL) { 13059 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 13060 } 13061 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 13062 final ArrayList<String> pkgList = new ArrayList<String>(1); 13063 pkgList.add(deletedPackage.applicationInfo.packageName); 13064 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 13065 } 13066 13067 deleteCodeCacheDirsLI(pkg); 13068 13069 try { 13070 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 13071 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 13072 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13073 prepareAppDataAfterInstall(newPackage); 13074 addedPkg = true; 13075 } catch (PackageManagerException e) { 13076 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13077 } 13078 } 13079 13080 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13081 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 13082 13083 // Revert all internal state mutations and added folders for the failed install 13084 if (addedPkg) { 13085 deletePackageLI(pkgName, null, true, allUsers, PackageManager.DELETE_KEEP_DATA, 13086 res.removedInfo, true, null); 13087 } 13088 13089 // Restore the old package 13090 if (deletedPkg) { 13091 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 13092 File restoreFile = new File(deletedPackage.codePath); 13093 // Parse old package 13094 boolean oldExternal = isExternal(deletedPackage); 13095 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 13096 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 13097 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 13098 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 13099 try { 13100 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 13101 null); 13102 } catch (PackageManagerException e) { 13103 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 13104 + e.getMessage()); 13105 return; 13106 } 13107 13108 synchronized (mPackages) { 13109 // Ensure the installer package name up to date 13110 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13111 13112 // Update permissions for restored package 13113 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13114 13115 mSettings.writeLPr(); 13116 } 13117 13118 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 13119 } 13120 } else { 13121 synchronized (mPackages) { 13122 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 13123 if (ps != null) { 13124 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 13125 if (res.removedInfo.removedChildPackages != null) { 13126 final int childCount = res.removedInfo.removedChildPackages.size(); 13127 // Iterate in reverse as we may modify the collection 13128 for (int i = childCount - 1; i >= 0; i--) { 13129 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 13130 if (res.addedChildPackages.containsKey(childPackageName)) { 13131 res.removedInfo.removedChildPackages.removeAt(i); 13132 } else { 13133 PackageRemovedInfo childInfo = res.removedInfo 13134 .removedChildPackages.valueAt(i); 13135 childInfo.removedForAllUsers = mPackages.get( 13136 childInfo.removedPackage) == null; 13137 } 13138 } 13139 } 13140 } 13141 } 13142 } 13143 } 13144 13145 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 13146 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13147 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13148 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 13149 + ", old=" + deletedPackage); 13150 13151 final boolean disabledSystem; 13152 13153 // Set the system/privileged flags as needed 13154 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 13155 if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 13156 != 0) { 13157 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13158 } 13159 13160 // Kill package processes including services, providers, etc. 13161 killPackage(deletedPackage, "replace sys pkg"); 13162 13163 // Remove existing system package 13164 removePackageLI(deletedPackage, true); 13165 13166 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 13167 if (!disabledSystem) { 13168 // We didn't need to disable the .apk as a current system package, 13169 // which means we are replacing another update that is already 13170 // installed. We need to make sure to delete the older one's .apk. 13171 res.removedInfo.args = createInstallArgsForExisting(0, 13172 deletedPackage.applicationInfo.getCodePath(), 13173 deletedPackage.applicationInfo.getResourcePath(), 13174 getAppDexInstructionSets(deletedPackage.applicationInfo)); 13175 } else { 13176 res.removedInfo.args = null; 13177 } 13178 13179 // Successfully disabled the old package. Now proceed with re-installation 13180 deleteCodeCacheDirsLI(pkg); 13181 13182 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13183 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 13184 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 13185 13186 PackageParser.Package newPackage = null; 13187 try { 13188 // Add the package to the internal data structures 13189 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 13190 13191 // Set the update and install times 13192 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 13193 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 13194 System.currentTimeMillis()); 13195 13196 // Check for shared user id changes 13197 String invalidPackageName = getParentOrChildPackageChangedSharedUser( 13198 deletedPackage, newPackage); 13199 if (invalidPackageName != null) { 13200 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13201 "Forbidding shared user change from " + deletedPkgSetting.sharedUser 13202 + " to " + invalidPackageName); 13203 } 13204 13205 // Update the package dynamic state if succeeded 13206 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13207 // Now that the install succeeded make sure we remove data 13208 // directories for any child package the update removed. 13209 final int deletedChildCount = (deletedPackage.childPackages != null) 13210 ? deletedPackage.childPackages.size() : 0; 13211 final int newChildCount = (newPackage.childPackages != null) 13212 ? newPackage.childPackages.size() : 0; 13213 for (int i = 0; i < deletedChildCount; i++) { 13214 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 13215 boolean childPackageDeleted = true; 13216 for (int j = 0; j < newChildCount; j++) { 13217 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 13218 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 13219 childPackageDeleted = false; 13220 break; 13221 } 13222 } 13223 if (childPackageDeleted) { 13224 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 13225 deletedChildPkg.packageName); 13226 if (ps != null && res.removedInfo.removedChildPackages != null) { 13227 PackageRemovedInfo removedChildRes = res.removedInfo 13228 .removedChildPackages.get(deletedChildPkg.packageName); 13229 removePackageDataLI(ps, allUsers, removedChildRes, 0, false); 13230 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 13231 } 13232 } 13233 } 13234 13235 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13236 prepareAppDataAfterInstall(newPackage); 13237 } 13238 } catch (PackageManagerException e) { 13239 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 13240 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13241 } 13242 13243 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13244 // Re installation failed. Restore old information 13245 // Remove new pkg information 13246 if (newPackage != null) { 13247 removeInstalledPackageLI(newPackage, true); 13248 } 13249 // Add back the old system package 13250 try { 13251 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 13252 } catch (PackageManagerException e) { 13253 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 13254 } 13255 13256 synchronized (mPackages) { 13257 if (disabledSystem) { 13258 enableSystemPackageLPw(deletedPackage); 13259 } 13260 13261 // Ensure the installer package name up to date 13262 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13263 13264 // Update permissions for restored package 13265 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13266 13267 mSettings.writeLPr(); 13268 } 13269 13270 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 13271 + " after failed upgrade"); 13272 } 13273 } 13274 13275 /** 13276 * Checks whether the parent or any of the child packages have a change shared 13277 * user. For a package to be a valid update the shred users of the parent and 13278 * the children should match. We may later support changing child shared users. 13279 * @param oldPkg The updated package. 13280 * @param newPkg The update package. 13281 * @return The shared user that change between the versions. 13282 */ 13283 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 13284 PackageParser.Package newPkg) { 13285 // Check parent shared user 13286 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 13287 return newPkg.packageName; 13288 } 13289 // Check child shared users 13290 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13291 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 13292 for (int i = 0; i < newChildCount; i++) { 13293 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 13294 // If this child was present, did it have the same shared user? 13295 for (int j = 0; j < oldChildCount; j++) { 13296 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 13297 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 13298 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 13299 return newChildPkg.packageName; 13300 } 13301 } 13302 } 13303 return null; 13304 } 13305 13306 private void removeNativeBinariesLI(PackageParser.Package pkg) { 13307 // Remove the lib path for the parent package 13308 PackageSetting ps = (PackageSetting) pkg.mExtras; 13309 if (ps != null) { 13310 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 13311 } 13312 // Remove the lib path for the child packages 13313 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13314 for (int i = 0; i < childCount; i++) { 13315 ps = (PackageSetting) pkg.childPackages.get(i).mExtras; 13316 if (ps != null) { 13317 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 13318 } 13319 } 13320 } 13321 13322 private void enableSystemPackageLPw(PackageParser.Package pkg) { 13323 // Enable the parent package 13324 mSettings.enableSystemPackageLPw(pkg.packageName); 13325 // Enable the child packages 13326 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13327 for (int i = 0; i < childCount; i++) { 13328 PackageParser.Package childPkg = pkg.childPackages.get(i); 13329 mSettings.enableSystemPackageLPw(childPkg.packageName); 13330 } 13331 } 13332 13333 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 13334 PackageParser.Package newPkg) { 13335 // Disable the parent package (parent always replaced) 13336 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 13337 // Disable the child packages 13338 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13339 for (int i = 0; i < childCount; i++) { 13340 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 13341 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 13342 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 13343 } 13344 return disabled; 13345 } 13346 13347 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 13348 String installerPackageName) { 13349 // Enable the parent package 13350 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 13351 // Enable the child packages 13352 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13353 for (int i = 0; i < childCount; i++) { 13354 PackageParser.Package childPkg = pkg.childPackages.get(i); 13355 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 13356 } 13357 } 13358 13359 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 13360 // Collect all used permissions in the UID 13361 ArraySet<String> usedPermissions = new ArraySet<>(); 13362 final int packageCount = su.packages.size(); 13363 for (int i = 0; i < packageCount; i++) { 13364 PackageSetting ps = su.packages.valueAt(i); 13365 if (ps.pkg == null) { 13366 continue; 13367 } 13368 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 13369 for (int j = 0; j < requestedPermCount; j++) { 13370 String permission = ps.pkg.requestedPermissions.get(j); 13371 BasePermission bp = mSettings.mPermissions.get(permission); 13372 if (bp != null) { 13373 usedPermissions.add(permission); 13374 } 13375 } 13376 } 13377 13378 PermissionsState permissionsState = su.getPermissionsState(); 13379 // Prune install permissions 13380 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 13381 final int installPermCount = installPermStates.size(); 13382 for (int i = installPermCount - 1; i >= 0; i--) { 13383 PermissionState permissionState = installPermStates.get(i); 13384 if (!usedPermissions.contains(permissionState.getName())) { 13385 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 13386 if (bp != null) { 13387 permissionsState.revokeInstallPermission(bp); 13388 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 13389 PackageManager.MASK_PERMISSION_FLAGS, 0); 13390 } 13391 } 13392 } 13393 13394 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 13395 13396 // Prune runtime permissions 13397 for (int userId : allUserIds) { 13398 List<PermissionState> runtimePermStates = permissionsState 13399 .getRuntimePermissionStates(userId); 13400 final int runtimePermCount = runtimePermStates.size(); 13401 for (int i = runtimePermCount - 1; i >= 0; i--) { 13402 PermissionState permissionState = runtimePermStates.get(i); 13403 if (!usedPermissions.contains(permissionState.getName())) { 13404 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 13405 if (bp != null) { 13406 permissionsState.revokeRuntimePermission(bp, userId); 13407 permissionsState.updatePermissionFlags(bp, userId, 13408 PackageManager.MASK_PERMISSION_FLAGS, 0); 13409 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 13410 runtimePermissionChangedUserIds, userId); 13411 } 13412 } 13413 } 13414 } 13415 13416 return runtimePermissionChangedUserIds; 13417 } 13418 13419 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 13420 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 13421 // Update the parent package setting 13422 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 13423 res, user); 13424 // Update the child packages setting 13425 final int childCount = (newPackage.childPackages != null) 13426 ? newPackage.childPackages.size() : 0; 13427 for (int i = 0; i < childCount; i++) { 13428 PackageParser.Package childPackage = newPackage.childPackages.get(i); 13429 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 13430 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 13431 childRes.origUsers, childRes, user); 13432 } 13433 } 13434 13435 private void updateSettingsInternalLI(PackageParser.Package newPackage, 13436 String installerPackageName, int[] allUsers, int[] installedForUsers, 13437 PackageInstalledInfo res, UserHandle user) { 13438 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 13439 13440 String pkgName = newPackage.packageName; 13441 synchronized (mPackages) { 13442 //write settings. the installStatus will be incomplete at this stage. 13443 //note that the new package setting would have already been 13444 //added to mPackages. It hasn't been persisted yet. 13445 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 13446 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 13447 mSettings.writeLPr(); 13448 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13449 } 13450 13451 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 13452 synchronized (mPackages) { 13453 updatePermissionsLPw(newPackage.packageName, newPackage, 13454 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 13455 ? UPDATE_PERMISSIONS_ALL : 0)); 13456 // For system-bundled packages, we assume that installing an upgraded version 13457 // of the package implies that the user actually wants to run that new code, 13458 // so we enable the package. 13459 PackageSetting ps = mSettings.mPackages.get(pkgName); 13460 final int userId = user.getIdentifier(); 13461 if (ps != null) { 13462 if (isSystemApp(newPackage)) { 13463 if (DEBUG_INSTALL) { 13464 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 13465 } 13466 // Enable system package for requested users 13467 if (res.origUsers != null) { 13468 for (int origUserId : res.origUsers) { 13469 if (userId == UserHandle.USER_ALL || userId == origUserId) { 13470 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 13471 origUserId, installerPackageName); 13472 } 13473 } 13474 } 13475 // Also convey the prior install/uninstall state 13476 if (allUsers != null && installedForUsers != null) { 13477 for (int currentUserId : allUsers) { 13478 final boolean installed = ArrayUtils.contains( 13479 installedForUsers, currentUserId); 13480 if (DEBUG_INSTALL) { 13481 Slog.d(TAG, " user " + currentUserId + " => " + installed); 13482 } 13483 ps.setInstalled(installed, currentUserId); 13484 } 13485 // these install state changes will be persisted in the 13486 // upcoming call to mSettings.writeLPr(). 13487 } 13488 } 13489 // It's implied that when a user requests installation, they want the app to be 13490 // installed and enabled. 13491 if (userId != UserHandle.USER_ALL) { 13492 ps.setInstalled(true, userId); 13493 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 13494 } 13495 } 13496 res.name = pkgName; 13497 res.uid = newPackage.applicationInfo.uid; 13498 res.pkg = newPackage; 13499 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 13500 mSettings.setInstallerPackageName(pkgName, installerPackageName); 13501 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13502 //to update install status 13503 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 13504 mSettings.writeLPr(); 13505 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13506 } 13507 13508 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13509 } 13510 13511 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 13512 try { 13513 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 13514 installPackageLI(args, res); 13515 } finally { 13516 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13517 } 13518 } 13519 13520 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 13521 final int installFlags = args.installFlags; 13522 final String installerPackageName = args.installerPackageName; 13523 final String volumeUuid = args.volumeUuid; 13524 final File tmpPackageFile = new File(args.getCodePath()); 13525 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 13526 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 13527 || (args.volumeUuid != null)); 13528 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 13529 boolean replace = false; 13530 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 13531 if (args.move != null) { 13532 // moving a complete application; perform an initial scan on the new install location 13533 scanFlags |= SCAN_INITIAL; 13534 } 13535 13536 // Result object to be returned 13537 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13538 13539 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 13540 13541 // Sanity check 13542 if (ephemeral && (forwardLocked || onExternal)) { 13543 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 13544 + " external=" + onExternal); 13545 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13546 return; 13547 } 13548 13549 // Retrieve PackageSettings and parse package 13550 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 13551 | PackageParser.PARSE_ENFORCE_CODE 13552 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 13553 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 13554 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 13555 PackageParser pp = new PackageParser(); 13556 pp.setSeparateProcesses(mSeparateProcesses); 13557 pp.setDisplayMetrics(mMetrics); 13558 13559 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 13560 final PackageParser.Package pkg; 13561 try { 13562 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 13563 } catch (PackageParserException e) { 13564 res.setError("Failed parse during installPackageLI", e); 13565 return; 13566 } finally { 13567 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13568 } 13569 13570 // If we are installing a clustered package add results for the children 13571 if (pkg.childPackages != null) { 13572 synchronized (mPackages) { 13573 final int childCount = pkg.childPackages.size(); 13574 for (int i = 0; i < childCount; i++) { 13575 PackageParser.Package childPkg = pkg.childPackages.get(i); 13576 PackageInstalledInfo childRes = new PackageInstalledInfo(); 13577 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13578 childRes.pkg = childPkg; 13579 childRes.name = childPkg.packageName; 13580 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13581 if (childPs != null) { 13582 childRes.origUsers = childPs.queryInstalledUsers( 13583 sUserManager.getUserIds(), true); 13584 } 13585 if ((mPackages.containsKey(childPkg.packageName))) { 13586 childRes.removedInfo = new PackageRemovedInfo(); 13587 childRes.removedInfo.removedPackage = childPkg.packageName; 13588 } 13589 if (res.addedChildPackages == null) { 13590 res.addedChildPackages = new ArrayMap<>(); 13591 } 13592 res.addedChildPackages.put(childPkg.packageName, childRes); 13593 } 13594 } 13595 } 13596 13597 // If package doesn't declare API override, mark that we have an install 13598 // time CPU ABI override. 13599 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 13600 pkg.cpuAbiOverride = args.abiOverride; 13601 } 13602 13603 String pkgName = res.name = pkg.packageName; 13604 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 13605 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 13606 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 13607 return; 13608 } 13609 } 13610 13611 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 13612 try { 13613 PackageParser.collectCertificates(pkg, parseFlags); 13614 } catch (PackageParserException e) { 13615 res.setError("Failed collect during installPackageLI", e); 13616 return; 13617 } finally { 13618 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13619 } 13620 13621 // Get rid of all references to package scan path via parser. 13622 pp = null; 13623 String oldCodePath = null; 13624 boolean systemApp = false; 13625 synchronized (mPackages) { 13626 // Check if installing already existing package 13627 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 13628 String oldName = mSettings.mRenamedPackages.get(pkgName); 13629 if (pkg.mOriginalPackages != null 13630 && pkg.mOriginalPackages.contains(oldName) 13631 && mPackages.containsKey(oldName)) { 13632 // This package is derived from an original package, 13633 // and this device has been updating from that original 13634 // name. We must continue using the original name, so 13635 // rename the new package here. 13636 pkg.setPackageName(oldName); 13637 pkgName = pkg.packageName; 13638 replace = true; 13639 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 13640 + oldName + " pkgName=" + pkgName); 13641 } else if (mPackages.containsKey(pkgName)) { 13642 // This package, under its official name, already exists 13643 // on the device; we should replace it. 13644 replace = true; 13645 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 13646 } 13647 13648 // Child packages are installed through the parent package 13649 if (pkg.parentPackage != null) { 13650 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 13651 "Package " + pkg.packageName + " is child of package " 13652 + pkg.parentPackage.parentPackage + ". Child packages " 13653 + "can be updated only through the parent package."); 13654 return; 13655 } 13656 13657 if (replace) { 13658 // Prevent apps opting out from runtime permissions 13659 PackageParser.Package oldPackage = mPackages.get(pkgName); 13660 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 13661 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 13662 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 13663 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 13664 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 13665 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 13666 + " doesn't support runtime permissions but the old" 13667 + " target SDK " + oldTargetSdk + " does."); 13668 return; 13669 } 13670 13671 // Prevent installing of child packages 13672 if (oldPackage.parentPackage != null) { 13673 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 13674 "Package " + pkg.packageName + " is child of package " 13675 + oldPackage.parentPackage + ". Child packages " 13676 + "can be updated only through the parent package."); 13677 return; 13678 } 13679 } 13680 } 13681 13682 PackageSetting ps = mSettings.mPackages.get(pkgName); 13683 if (ps != null) { 13684 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 13685 13686 // Quick sanity check that we're signed correctly if updating; 13687 // we'll check this again later when scanning, but we want to 13688 // bail early here before tripping over redefined permissions. 13689 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13690 if (!checkUpgradeKeySetLP(ps, pkg)) { 13691 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 13692 + pkg.packageName + " upgrade keys do not match the " 13693 + "previously installed version"); 13694 return; 13695 } 13696 } else { 13697 try { 13698 verifySignaturesLP(ps, pkg); 13699 } catch (PackageManagerException e) { 13700 res.setError(e.error, e.getMessage()); 13701 return; 13702 } 13703 } 13704 13705 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 13706 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 13707 systemApp = (ps.pkg.applicationInfo.flags & 13708 ApplicationInfo.FLAG_SYSTEM) != 0; 13709 } 13710 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13711 } 13712 13713 // Check whether the newly-scanned package wants to define an already-defined perm 13714 int N = pkg.permissions.size(); 13715 for (int i = N-1; i >= 0; i--) { 13716 PackageParser.Permission perm = pkg.permissions.get(i); 13717 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 13718 if (bp != null) { 13719 // If the defining package is signed with our cert, it's okay. This 13720 // also includes the "updating the same package" case, of course. 13721 // "updating same package" could also involve key-rotation. 13722 final boolean sigsOk; 13723 if (bp.sourcePackage.equals(pkg.packageName) 13724 && (bp.packageSetting instanceof PackageSetting) 13725 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 13726 scanFlags))) { 13727 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 13728 } else { 13729 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 13730 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 13731 } 13732 if (!sigsOk) { 13733 // If the owning package is the system itself, we log but allow 13734 // install to proceed; we fail the install on all other permission 13735 // redefinitions. 13736 if (!bp.sourcePackage.equals("android")) { 13737 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 13738 + pkg.packageName + " attempting to redeclare permission " 13739 + perm.info.name + " already owned by " + bp.sourcePackage); 13740 res.origPermission = perm.info.name; 13741 res.origPackage = bp.sourcePackage; 13742 return; 13743 } else { 13744 Slog.w(TAG, "Package " + pkg.packageName 13745 + " attempting to redeclare system permission " 13746 + perm.info.name + "; ignoring new declaration"); 13747 pkg.permissions.remove(i); 13748 } 13749 } 13750 } 13751 } 13752 } 13753 13754 if (systemApp) { 13755 if (onExternal) { 13756 // Abort update; system app can't be replaced with app on sdcard 13757 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 13758 "Cannot install updates to system apps on sdcard"); 13759 return; 13760 } else if (ephemeral) { 13761 // Abort update; system app can't be replaced with an ephemeral app 13762 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 13763 "Cannot update a system app with an ephemeral app"); 13764 return; 13765 } 13766 } 13767 13768 if (args.move != null) { 13769 // We did an in-place move, so dex is ready to roll 13770 scanFlags |= SCAN_NO_DEX; 13771 scanFlags |= SCAN_MOVE; 13772 13773 synchronized (mPackages) { 13774 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13775 if (ps == null) { 13776 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 13777 "Missing settings for moved package " + pkgName); 13778 } 13779 13780 // We moved the entire application as-is, so bring over the 13781 // previously derived ABI information. 13782 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 13783 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 13784 } 13785 13786 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 13787 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 13788 scanFlags |= SCAN_NO_DEX; 13789 13790 try { 13791 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 13792 args.abiOverride : pkg.cpuAbiOverride); 13793 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 13794 true /* extract libs */); 13795 } catch (PackageManagerException pme) { 13796 Slog.e(TAG, "Error deriving application ABI", pme); 13797 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 13798 return; 13799 } 13800 13801 // Extract package to save the VM unzipping the APK in memory during 13802 // launch. Only do this if profile-guided compilation is enabled because 13803 // otherwise BackgroundDexOptService will not dexopt the package later. 13804 if (mUseJitProfiles) { 13805 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 13806 // Do not run PackageDexOptimizer through the local performDexOpt 13807 // method because `pkg` is not in `mPackages` yet. 13808 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 13809 false /* useProfiles */, true /* extractOnly */); 13810 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13811 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 13812 String msg = "Extracking package failed for " + pkgName; 13813 res.setError(INSTALL_FAILED_DEXOPT, msg); 13814 return; 13815 } 13816 } 13817 } 13818 13819 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 13820 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 13821 return; 13822 } 13823 13824 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 13825 13826 if (replace) { 13827 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 13828 installerPackageName, res); 13829 } else { 13830 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 13831 args.user, installerPackageName, volumeUuid, res); 13832 } 13833 synchronized (mPackages) { 13834 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13835 if (ps != null) { 13836 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13837 } 13838 13839 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13840 for (int i = 0; i < childCount; i++) { 13841 PackageParser.Package childPkg = pkg.childPackages.get(i); 13842 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13843 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13844 if (childPs != null) { 13845 childRes.newUsers = childPs.queryInstalledUsers( 13846 sUserManager.getUserIds(), true); 13847 } 13848 } 13849 } 13850 } 13851 13852 private void startIntentFilterVerifications(int userId, boolean replacing, 13853 PackageParser.Package pkg) { 13854 if (mIntentFilterVerifierComponent == null) { 13855 Slog.w(TAG, "No IntentFilter verification will not be done as " 13856 + "there is no IntentFilterVerifier available!"); 13857 return; 13858 } 13859 13860 final int verifierUid = getPackageUid( 13861 mIntentFilterVerifierComponent.getPackageName(), 13862 MATCH_DEBUG_TRIAGED_MISSING, 13863 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 13864 13865 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 13866 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 13867 mHandler.sendMessage(msg); 13868 13869 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13870 for (int i = 0; i < childCount; i++) { 13871 PackageParser.Package childPkg = pkg.childPackages.get(i); 13872 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 13873 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 13874 mHandler.sendMessage(msg); 13875 } 13876 } 13877 13878 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 13879 PackageParser.Package pkg) { 13880 int size = pkg.activities.size(); 13881 if (size == 0) { 13882 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13883 "No activity, so no need to verify any IntentFilter!"); 13884 return; 13885 } 13886 13887 final boolean hasDomainURLs = hasDomainURLs(pkg); 13888 if (!hasDomainURLs) { 13889 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13890 "No domain URLs, so no need to verify any IntentFilter!"); 13891 return; 13892 } 13893 13894 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 13895 + " if any IntentFilter from the " + size 13896 + " Activities needs verification ..."); 13897 13898 int count = 0; 13899 final String packageName = pkg.packageName; 13900 13901 synchronized (mPackages) { 13902 // If this is a new install and we see that we've already run verification for this 13903 // package, we have nothing to do: it means the state was restored from backup. 13904 if (!replacing) { 13905 IntentFilterVerificationInfo ivi = 13906 mSettings.getIntentFilterVerificationLPr(packageName); 13907 if (ivi != null) { 13908 if (DEBUG_DOMAIN_VERIFICATION) { 13909 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 13910 + ivi.getStatusString()); 13911 } 13912 return; 13913 } 13914 } 13915 13916 // If any filters need to be verified, then all need to be. 13917 boolean needToVerify = false; 13918 for (PackageParser.Activity a : pkg.activities) { 13919 for (ActivityIntentInfo filter : a.intents) { 13920 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 13921 if (DEBUG_DOMAIN_VERIFICATION) { 13922 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 13923 } 13924 needToVerify = true; 13925 break; 13926 } 13927 } 13928 } 13929 13930 if (needToVerify) { 13931 final int verificationId = mIntentFilterVerificationToken++; 13932 for (PackageParser.Activity a : pkg.activities) { 13933 for (ActivityIntentInfo filter : a.intents) { 13934 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 13935 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13936 "Verification needed for IntentFilter:" + filter.toString()); 13937 mIntentFilterVerifier.addOneIntentFilterVerification( 13938 verifierUid, userId, verificationId, filter, packageName); 13939 count++; 13940 } 13941 } 13942 } 13943 } 13944 } 13945 13946 if (count > 0) { 13947 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 13948 + " IntentFilter verification" + (count > 1 ? "s" : "") 13949 + " for userId:" + userId); 13950 mIntentFilterVerifier.startVerifications(userId); 13951 } else { 13952 if (DEBUG_DOMAIN_VERIFICATION) { 13953 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 13954 } 13955 } 13956 } 13957 13958 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 13959 final ComponentName cn = filter.activity.getComponentName(); 13960 final String packageName = cn.getPackageName(); 13961 13962 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 13963 packageName); 13964 if (ivi == null) { 13965 return true; 13966 } 13967 int status = ivi.getStatus(); 13968 switch (status) { 13969 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 13970 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 13971 return true; 13972 13973 default: 13974 // Nothing to do 13975 return false; 13976 } 13977 } 13978 13979 private static boolean isMultiArch(ApplicationInfo info) { 13980 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 13981 } 13982 13983 private static boolean isExternal(PackageParser.Package pkg) { 13984 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13985 } 13986 13987 private static boolean isExternal(PackageSetting ps) { 13988 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13989 } 13990 13991 private static boolean isEphemeral(PackageParser.Package pkg) { 13992 return pkg.applicationInfo.isEphemeralApp(); 13993 } 13994 13995 private static boolean isEphemeral(PackageSetting ps) { 13996 return ps.pkg != null && isEphemeral(ps.pkg); 13997 } 13998 13999 private static boolean isSystemApp(PackageParser.Package pkg) { 14000 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 14001 } 14002 14003 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 14004 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14005 } 14006 14007 private static boolean hasDomainURLs(PackageParser.Package pkg) { 14008 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 14009 } 14010 14011 private static boolean isSystemApp(PackageSetting ps) { 14012 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 14013 } 14014 14015 private static boolean isUpdatedSystemApp(PackageSetting ps) { 14016 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 14017 } 14018 14019 private int packageFlagsToInstallFlags(PackageSetting ps) { 14020 int installFlags = 0; 14021 if (isEphemeral(ps)) { 14022 installFlags |= PackageManager.INSTALL_EPHEMERAL; 14023 } 14024 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 14025 // This existing package was an external ASEC install when we have 14026 // the external flag without a UUID 14027 installFlags |= PackageManager.INSTALL_EXTERNAL; 14028 } 14029 if (ps.isForwardLocked()) { 14030 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 14031 } 14032 return installFlags; 14033 } 14034 14035 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 14036 if (isExternal(pkg)) { 14037 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14038 return StorageManager.UUID_PRIMARY_PHYSICAL; 14039 } else { 14040 return pkg.volumeUuid; 14041 } 14042 } else { 14043 return StorageManager.UUID_PRIVATE_INTERNAL; 14044 } 14045 } 14046 14047 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 14048 if (isExternal(pkg)) { 14049 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14050 return mSettings.getExternalVersion(); 14051 } else { 14052 return mSettings.findOrCreateVersion(pkg.volumeUuid); 14053 } 14054 } else { 14055 return mSettings.getInternalVersion(); 14056 } 14057 } 14058 14059 private void deleteTempPackageFiles() { 14060 final FilenameFilter filter = new FilenameFilter() { 14061 public boolean accept(File dir, String name) { 14062 return name.startsWith("vmdl") && name.endsWith(".tmp"); 14063 } 14064 }; 14065 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 14066 file.delete(); 14067 } 14068 } 14069 14070 @Override 14071 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 14072 int flags) { 14073 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 14074 flags); 14075 } 14076 14077 @Override 14078 public void deletePackage(final String packageName, 14079 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 14080 mContext.enforceCallingOrSelfPermission( 14081 android.Manifest.permission.DELETE_PACKAGES, null); 14082 Preconditions.checkNotNull(packageName); 14083 Preconditions.checkNotNull(observer); 14084 final int uid = Binder.getCallingUid(); 14085 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 14086 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 14087 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 14088 mContext.enforceCallingOrSelfPermission( 14089 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14090 "deletePackage for user " + userId); 14091 } 14092 14093 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 14094 try { 14095 observer.onPackageDeleted(packageName, 14096 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 14097 } catch (RemoteException re) { 14098 } 14099 return; 14100 } 14101 14102 for (int currentUserId : users) { 14103 if (getBlockUninstallForUser(packageName, currentUserId)) { 14104 try { 14105 observer.onPackageDeleted(packageName, 14106 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 14107 } catch (RemoteException re) { 14108 } 14109 return; 14110 } 14111 } 14112 14113 if (DEBUG_REMOVE) { 14114 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 14115 } 14116 // Queue up an async operation since the package deletion may take a little while. 14117 mHandler.post(new Runnable() { 14118 public void run() { 14119 mHandler.removeCallbacks(this); 14120 final int returnCode = deletePackageX(packageName, userId, flags); 14121 try { 14122 observer.onPackageDeleted(packageName, returnCode, null); 14123 } catch (RemoteException e) { 14124 Log.i(TAG, "Observer no longer exists."); 14125 } //end catch 14126 } //end run 14127 }); 14128 } 14129 14130 @Override 14131 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 14132 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 14133 } 14134 14135 private boolean isPackageDeviceAdmin(String packageName, int userId) { 14136 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 14137 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 14138 try { 14139 if (dpm != null) { 14140 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 14141 /* callingUserOnly =*/ false); 14142 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 14143 : deviceOwnerComponentName.getPackageName(); 14144 // Does the package contains the device owner? 14145 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 14146 // this check is probably not needed, since DO should be registered as a device 14147 // admin on some user too. (Original bug for this: b/17657954) 14148 if (packageName.equals(deviceOwnerPackageName)) { 14149 return true; 14150 } 14151 // Does it contain a device admin for any user? 14152 int[] users; 14153 if (userId == UserHandle.USER_ALL) { 14154 users = sUserManager.getUserIds(); 14155 } else { 14156 users = new int[]{userId}; 14157 } 14158 for (int i = 0; i < users.length; ++i) { 14159 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 14160 return true; 14161 } 14162 } 14163 } 14164 } catch (RemoteException e) { 14165 } 14166 return false; 14167 } 14168 14169 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 14170 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 14171 } 14172 14173 /** 14174 * This method is an internal method that could be get invoked either 14175 * to delete an installed package or to clean up a failed installation. 14176 * After deleting an installed package, a broadcast is sent to notify any 14177 * listeners that the package has been installed. For cleaning up a failed 14178 * installation, the broadcast is not necessary since the package's 14179 * installation wouldn't have sent the initial broadcast either 14180 * The key steps in deleting a package are 14181 * deleting the package information in internal structures like mPackages, 14182 * deleting the packages base directories through installd 14183 * updating mSettings to reflect current status 14184 * persisting settings for later use 14185 * sending a broadcast if necessary 14186 */ 14187 private int deletePackageX(String packageName, int userId, int flags) { 14188 final PackageRemovedInfo info = new PackageRemovedInfo(); 14189 final boolean res; 14190 14191 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 14192 ? UserHandle.ALL : new UserHandle(userId); 14193 14194 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 14195 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 14196 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 14197 } 14198 14199 PackageSetting uninstalledPs = null; 14200 14201 // for the uninstall-updates case and restricted profiles, remember the per- 14202 // user handle installed state 14203 int[] allUsers; 14204 synchronized (mPackages) { 14205 uninstalledPs = mSettings.mPackages.get(packageName); 14206 if (uninstalledPs == null) { 14207 Slog.w(TAG, "Not removing non-existent package " + packageName); 14208 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14209 } 14210 allUsers = sUserManager.getUserIds(); 14211 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 14212 } 14213 14214 synchronized (mInstallLock) { 14215 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 14216 res = deletePackageLI(packageName, removeForUser, true, allUsers, 14217 flags | REMOVE_CHATTY, info, true, null); 14218 synchronized (mPackages) { 14219 if (res) { 14220 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 14221 } 14222 } 14223 } 14224 14225 if (res) { 14226 info.sendPackageRemovedBroadcasts(); 14227 info.sendSystemPackageUpdatedBroadcasts(); 14228 info.sendSystemPackageAppearedBroadcasts(); 14229 } 14230 // Force a gc here. 14231 Runtime.getRuntime().gc(); 14232 // Delete the resources here after sending the broadcast to let 14233 // other processes clean up before deleting resources. 14234 if (info.args != null) { 14235 synchronized (mInstallLock) { 14236 info.args.doPostDeleteLI(true); 14237 } 14238 } 14239 14240 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14241 } 14242 14243 class PackageRemovedInfo { 14244 String removedPackage; 14245 int uid = -1; 14246 int removedAppId = -1; 14247 int[] origUsers; 14248 int[] removedUsers = null; 14249 boolean isRemovedPackageSystemUpdate = false; 14250 boolean isUpdate; 14251 boolean dataRemoved; 14252 boolean removedForAllUsers; 14253 // Clean up resources deleted packages. 14254 InstallArgs args = null; 14255 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 14256 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 14257 14258 void sendPackageRemovedBroadcasts() { 14259 sendPackageRemovedBroadcastInternal(); 14260 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 14261 for (int i = 0; i < childCount; i++) { 14262 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 14263 childInfo.sendPackageRemovedBroadcastInternal(); 14264 } 14265 } 14266 14267 void sendSystemPackageUpdatedBroadcasts() { 14268 if (isRemovedPackageSystemUpdate) { 14269 sendSystemPackageUpdatedBroadcastsInternal(); 14270 final int childCount = (removedChildPackages != null) 14271 ? removedChildPackages.size() : 0; 14272 for (int i = 0; i < childCount; i++) { 14273 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 14274 if (childInfo.isRemovedPackageSystemUpdate) { 14275 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 14276 } 14277 } 14278 } 14279 } 14280 14281 void sendSystemPackageAppearedBroadcasts() { 14282 final int packageCount = (appearedChildPackages != null) 14283 ? appearedChildPackages.size() : 0; 14284 for (int i = 0; i < packageCount; i++) { 14285 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 14286 for (int userId : installedInfo.newUsers) { 14287 sendPackageAddedForUser(installedInfo.name, true, 14288 UserHandle.getAppId(installedInfo.uid), userId); 14289 } 14290 } 14291 } 14292 14293 private void sendSystemPackageUpdatedBroadcastsInternal() { 14294 Bundle extras = new Bundle(2); 14295 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 14296 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14297 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 14298 extras, 0, null, null, null); 14299 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 14300 extras, 0, null, null, null); 14301 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 14302 null, 0, removedPackage, null, null); 14303 } 14304 14305 private void sendPackageRemovedBroadcastInternal() { 14306 Bundle extras = new Bundle(2); 14307 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 14308 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 14309 if (isUpdate || isRemovedPackageSystemUpdate) { 14310 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14311 } 14312 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 14313 if (removedPackage != null) { 14314 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 14315 extras, 0, null, null, removedUsers); 14316 if (dataRemoved && !isRemovedPackageSystemUpdate) { 14317 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 14318 removedPackage, extras, 0, null, null, removedUsers); 14319 } 14320 } 14321 if (removedAppId >= 0) { 14322 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 14323 removedUsers); 14324 } 14325 } 14326 } 14327 14328 /* 14329 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 14330 * flag is not set, the data directory is removed as well. 14331 * make sure this flag is set for partially installed apps. If not its meaningless to 14332 * delete a partially installed application. 14333 */ 14334 private void removePackageDataLI(PackageSetting ps, int[] allUserHandles, 14335 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 14336 String packageName = ps.name; 14337 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 14338 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 14339 // Retrieve object to delete permissions for shared user later on 14340 final PackageSetting deletedPs; 14341 // reader 14342 synchronized (mPackages) { 14343 deletedPs = mSettings.mPackages.get(packageName); 14344 if (outInfo != null) { 14345 outInfo.removedPackage = packageName; 14346 outInfo.removedUsers = deletedPs != null 14347 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 14348 : null; 14349 } 14350 } 14351 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 14352 removeDataDirsLI(ps.volumeUuid, packageName); 14353 if (outInfo != null) { 14354 outInfo.dataRemoved = true; 14355 } 14356 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 14357 } 14358 // writer 14359 synchronized (mPackages) { 14360 if (deletedPs != null) { 14361 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 14362 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 14363 clearDefaultBrowserIfNeeded(packageName); 14364 if (outInfo != null) { 14365 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 14366 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 14367 } 14368 updatePermissionsLPw(deletedPs.name, null, 0); 14369 if (deletedPs.sharedUser != null) { 14370 // Remove permissions associated with package. Since runtime 14371 // permissions are per user we have to kill the removed package 14372 // or packages running under the shared user of the removed 14373 // package if revoking the permissions requested only by the removed 14374 // package is successful and this causes a change in gids. 14375 for (int userId : UserManagerService.getInstance().getUserIds()) { 14376 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 14377 userId); 14378 if (userIdToKill == UserHandle.USER_ALL 14379 || userIdToKill >= UserHandle.USER_SYSTEM) { 14380 // If gids changed for this user, kill all affected packages. 14381 mHandler.post(new Runnable() { 14382 @Override 14383 public void run() { 14384 // This has to happen with no lock held. 14385 killApplication(deletedPs.name, deletedPs.appId, 14386 KILL_APP_REASON_GIDS_CHANGED); 14387 } 14388 }); 14389 break; 14390 } 14391 } 14392 } 14393 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 14394 } 14395 // make sure to preserve per-user disabled state if this removal was just 14396 // a downgrade of a system app to the factory package 14397 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 14398 if (DEBUG_REMOVE) { 14399 Slog.d(TAG, "Propagating install state across downgrade"); 14400 } 14401 for (int userId : allUserHandles) { 14402 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 14403 if (DEBUG_REMOVE) { 14404 Slog.d(TAG, " user " + userId + " => " + installed); 14405 } 14406 ps.setInstalled(installed, userId); 14407 } 14408 } 14409 } 14410 // can downgrade to reader 14411 if (writeSettings) { 14412 // Save settings now 14413 mSettings.writeLPr(); 14414 } 14415 } 14416 if (outInfo != null) { 14417 // A user ID was deleted here. Go through all users and remove it 14418 // from KeyStore. 14419 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 14420 } 14421 } 14422 14423 static boolean locationIsPrivileged(File path) { 14424 try { 14425 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 14426 .getCanonicalPath(); 14427 return path.getCanonicalPath().startsWith(privilegedAppDir); 14428 } catch (IOException e) { 14429 Slog.e(TAG, "Unable to access code path " + path); 14430 } 14431 return false; 14432 } 14433 14434 /* 14435 * Tries to delete system package. 14436 */ 14437 private boolean deleteSystemPackageLI(PackageParser.Package deletedPkg, 14438 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 14439 boolean writeSettings) { 14440 if (deletedPkg.parentPackage != null) { 14441 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 14442 return false; 14443 } 14444 14445 final boolean applyUserRestrictions 14446 = (allUserHandles != null) && (outInfo.origUsers != null); 14447 final PackageSetting disabledPs; 14448 // Confirm if the system package has been updated 14449 // An updated system app can be deleted. This will also have to restore 14450 // the system pkg from system partition 14451 // reader 14452 synchronized (mPackages) { 14453 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPkg.packageName); 14454 } 14455 14456 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 14457 + " disabledPs=" + disabledPs); 14458 14459 if (disabledPs == null) { 14460 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 14461 return false; 14462 } else if (DEBUG_REMOVE) { 14463 Slog.d(TAG, "Deleting system pkg from data partition"); 14464 } 14465 14466 if (DEBUG_REMOVE) { 14467 if (applyUserRestrictions) { 14468 Slog.d(TAG, "Remembering install states:"); 14469 for (int userId : allUserHandles) { 14470 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 14471 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 14472 } 14473 } 14474 } 14475 14476 // Delete the updated package 14477 outInfo.isRemovedPackageSystemUpdate = true; 14478 if (outInfo.removedChildPackages != null) { 14479 final int childCount = (deletedPkg.childPackages != null) 14480 ? deletedPkg.childPackages.size() : 0; 14481 for (int i = 0; i < childCount; i++) { 14482 String childPackageName = deletedPkg.childPackages.get(i).packageName; 14483 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 14484 .contains(childPackageName)) { 14485 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 14486 childPackageName); 14487 if (childInfo != null) { 14488 childInfo.isRemovedPackageSystemUpdate = true; 14489 } 14490 } 14491 } 14492 } 14493 14494 if (disabledPs.versionCode < deletedPs.versionCode) { 14495 // Delete data for downgrades 14496 flags &= ~PackageManager.DELETE_KEEP_DATA; 14497 } else { 14498 // Preserve data by setting flag 14499 flags |= PackageManager.DELETE_KEEP_DATA; 14500 } 14501 14502 boolean ret = deleteInstalledPackageLI(deletedPkg, true, flags, allUserHandles, 14503 outInfo, writeSettings, disabledPs.pkg); 14504 if (!ret) { 14505 return false; 14506 } 14507 14508 // writer 14509 synchronized (mPackages) { 14510 // Reinstate the old system package 14511 enableSystemPackageLPw(disabledPs.pkg); 14512 // Remove any native libraries from the upgraded package. 14513 removeNativeBinariesLI(deletedPkg); 14514 } 14515 14516 // Install the system package 14517 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 14518 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 14519 if (locationIsPrivileged(disabledPs.codePath)) { 14520 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 14521 } 14522 14523 final PackageParser.Package newPkg; 14524 try { 14525 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 14526 } catch (PackageManagerException e) { 14527 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 14528 + e.getMessage()); 14529 return false; 14530 } 14531 14532 prepareAppDataAfterInstall(newPkg); 14533 14534 // writer 14535 synchronized (mPackages) { 14536 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 14537 14538 // Propagate the permissions state as we do not want to drop on the floor 14539 // runtime permissions. The update permissions method below will take 14540 // care of removing obsolete permissions and grant install permissions. 14541 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 14542 updatePermissionsLPw(newPkg.packageName, newPkg, 14543 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 14544 14545 if (applyUserRestrictions) { 14546 if (DEBUG_REMOVE) { 14547 Slog.d(TAG, "Propagating install state across reinstall"); 14548 } 14549 for (int userId : allUserHandles) { 14550 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 14551 if (DEBUG_REMOVE) { 14552 Slog.d(TAG, " user " + userId + " => " + installed); 14553 } 14554 ps.setInstalled(installed, userId); 14555 14556 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 14557 } 14558 // Regardless of writeSettings we need to ensure that this restriction 14559 // state propagation is persisted 14560 mSettings.writeAllUsersPackageRestrictionsLPr(); 14561 } 14562 // can downgrade to reader here 14563 if (writeSettings) { 14564 mSettings.writeLPr(); 14565 } 14566 } 14567 return true; 14568 } 14569 14570 private boolean deleteInstalledPackageLI(PackageParser.Package pkg, 14571 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 14572 PackageRemovedInfo outInfo, boolean writeSettings, 14573 PackageParser.Package replacingPackage) { 14574 PackageSetting ps = null; 14575 14576 synchronized (mPackages) { 14577 pkg = mPackages.get(pkg.packageName); 14578 if (pkg == null) { 14579 return false; 14580 } 14581 14582 ps = mSettings.mPackages.get(pkg.packageName); 14583 if (ps == null) { 14584 return false; 14585 } 14586 14587 if (outInfo != null) { 14588 outInfo.uid = ps.appId; 14589 } 14590 14591 if (outInfo != null && outInfo.removedChildPackages != null) { 14592 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14593 for (int i = 0; i < childCount; i++) { 14594 String childPackageName = ps.childPackageNames.get(i); 14595 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 14596 if (childPs == null) { 14597 return false; 14598 } 14599 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 14600 childPackageName); 14601 if (childInfo != null) { 14602 childInfo.uid = childPs.appId; 14603 } 14604 } 14605 } 14606 } 14607 14608 // Delete package data from internal structures and also remove data if flag is set 14609 removePackageDataLI(ps, allUserHandles, outInfo, flags, writeSettings); 14610 14611 // Delete the child packages data 14612 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14613 for (int i = 0; i < childCount; i++) { 14614 PackageSetting childPs; 14615 synchronized (mPackages) { 14616 childPs = mSettings.peekPackageLPr(pkg.childPackages.get(i).packageName); 14617 } 14618 if (childPs != null) { 14619 PackageRemovedInfo childOutInfo = (outInfo != null 14620 && outInfo.removedChildPackages != null) 14621 ? outInfo.removedChildPackages.get(childPs.name) : null; 14622 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 14623 && (replacingPackage != null 14624 && !replacingPackage.hasChildPackage(childPs.name)) 14625 ? flags & ~DELETE_KEEP_DATA : flags; 14626 removePackageDataLI(childPs, allUserHandles, childOutInfo, 14627 deleteFlags, writeSettings); 14628 } 14629 } 14630 14631 // Delete application code and resources only for parent packages 14632 if (ps.pkg.parentPackage == null) { 14633 if (deleteCodeAndResources && (outInfo != null)) { 14634 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 14635 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 14636 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 14637 } 14638 } 14639 14640 return true; 14641 } 14642 14643 @Override 14644 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 14645 int userId) { 14646 mContext.enforceCallingOrSelfPermission( 14647 android.Manifest.permission.DELETE_PACKAGES, null); 14648 synchronized (mPackages) { 14649 PackageSetting ps = mSettings.mPackages.get(packageName); 14650 if (ps == null) { 14651 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 14652 return false; 14653 } 14654 if (!ps.getInstalled(userId)) { 14655 // Can't block uninstall for an app that is not installed or enabled. 14656 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 14657 return false; 14658 } 14659 ps.setBlockUninstall(blockUninstall, userId); 14660 mSettings.writePackageRestrictionsLPr(userId); 14661 } 14662 return true; 14663 } 14664 14665 @Override 14666 public boolean getBlockUninstallForUser(String packageName, int userId) { 14667 synchronized (mPackages) { 14668 PackageSetting ps = mSettings.mPackages.get(packageName); 14669 if (ps == null) { 14670 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 14671 return false; 14672 } 14673 return ps.getBlockUninstall(userId); 14674 } 14675 } 14676 14677 @Override 14678 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 14679 int callingUid = Binder.getCallingUid(); 14680 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 14681 throw new SecurityException( 14682 "setRequiredForSystemUser can only be run by the system or root"); 14683 } 14684 synchronized (mPackages) { 14685 PackageSetting ps = mSettings.mPackages.get(packageName); 14686 if (ps == null) { 14687 Log.w(TAG, "Package doesn't exist: " + packageName); 14688 return false; 14689 } 14690 if (systemUserApp) { 14691 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 14692 } else { 14693 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 14694 } 14695 mSettings.writeLPr(); 14696 } 14697 return true; 14698 } 14699 14700 /* 14701 * This method handles package deletion in general 14702 */ 14703 private boolean deletePackageLI(String packageName, UserHandle user, 14704 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 14705 PackageRemovedInfo outInfo, boolean writeSettings, 14706 PackageParser.Package replacingPackage) { 14707 if (packageName == null) { 14708 Slog.w(TAG, "Attempt to delete null packageName."); 14709 return false; 14710 } 14711 14712 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 14713 14714 PackageSetting ps; 14715 14716 synchronized (mPackages) { 14717 ps = mSettings.mPackages.get(packageName); 14718 if (ps == null) { 14719 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 14720 return false; 14721 } 14722 14723 if (ps.pkg != null && ps.pkg.parentPackage != null && (!isSystemApp(ps) 14724 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 14725 if (DEBUG_REMOVE) { 14726 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 14727 + ((user == null) ? UserHandle.USER_ALL : user)); 14728 } 14729 final int removedUserId = (user != null) ? user.getIdentifier() 14730 : UserHandle.USER_ALL; 14731 if (!clearPackageStateForUser(ps, removedUserId, outInfo)) { 14732 return false; 14733 } 14734 markPackageUninstalledForUserLPw(ps, user); 14735 scheduleWritePackageRestrictionsLocked(user); 14736 return true; 14737 } 14738 } 14739 14740 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 14741 && user.getIdentifier() != UserHandle.USER_ALL)) { 14742 // The caller is asking that the package only be deleted for a single 14743 // user. To do this, we just mark its uninstalled state and delete 14744 // its data. If this is a system app, we only allow this to happen if 14745 // they have set the special DELETE_SYSTEM_APP which requests different 14746 // semantics than normal for uninstalling system apps. 14747 markPackageUninstalledForUserLPw(ps, user); 14748 14749 if (!isSystemApp(ps)) { 14750 // Do not uninstall the APK if an app should be cached 14751 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 14752 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 14753 // Other user still have this package installed, so all 14754 // we need to do is clear this user's data and save that 14755 // it is uninstalled. 14756 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 14757 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 14758 return false; 14759 } 14760 scheduleWritePackageRestrictionsLocked(user); 14761 return true; 14762 } else { 14763 // We need to set it back to 'installed' so the uninstall 14764 // broadcasts will be sent correctly. 14765 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 14766 ps.setInstalled(true, user.getIdentifier()); 14767 } 14768 } else { 14769 // This is a system app, so we assume that the 14770 // other users still have this package installed, so all 14771 // we need to do is clear this user's data and save that 14772 // it is uninstalled. 14773 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 14774 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 14775 return false; 14776 } 14777 scheduleWritePackageRestrictionsLocked(user); 14778 return true; 14779 } 14780 } 14781 14782 // If we are deleting a composite package for all users, keep track 14783 // of result for each child. 14784 if (ps.childPackageNames != null && outInfo != null) { 14785 synchronized (mPackages) { 14786 final int childCount = ps.childPackageNames.size(); 14787 outInfo.removedChildPackages = new ArrayMap<>(childCount); 14788 for (int i = 0; i < childCount; i++) { 14789 String childPackageName = ps.childPackageNames.get(i); 14790 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 14791 childInfo.removedPackage = childPackageName; 14792 outInfo.removedChildPackages.put(childPackageName, childInfo); 14793 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 14794 if (childPs != null) { 14795 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 14796 } 14797 } 14798 } 14799 } 14800 14801 boolean ret = false; 14802 if (isSystemApp(ps)) { 14803 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 14804 // When an updated system application is deleted we delete the existing resources 14805 // as well and fall back to existing code in system partition 14806 ret = deleteSystemPackageLI(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 14807 } else { 14808 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 14809 // Kill application pre-emptively especially for apps on sd. 14810 killApplication(packageName, ps.appId, "uninstall pkg"); 14811 ret = deleteInstalledPackageLI(ps.pkg, deleteCodeAndResources, flags, allUserHandles, 14812 outInfo, writeSettings, replacingPackage); 14813 } 14814 14815 // Take a note whether we deleted the package for all users 14816 if (outInfo != null) { 14817 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14818 if (outInfo.removedChildPackages != null) { 14819 synchronized (mPackages) { 14820 final int childCount = outInfo.removedChildPackages.size(); 14821 for (int i = 0; i < childCount; i++) { 14822 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 14823 if (childInfo != null) { 14824 childInfo.removedForAllUsers = mPackages.get( 14825 childInfo.removedPackage) == null; 14826 } 14827 } 14828 } 14829 } 14830 // If we uninstalled an update to a system app there may be some 14831 // child packages that appeared as they are declared in the system 14832 // app but were not declared in the update. 14833 if (isSystemApp(ps)) { 14834 synchronized (mPackages) { 14835 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 14836 final int childCount = (updatedPs.childPackageNames != null) 14837 ? updatedPs.childPackageNames.size() : 0; 14838 for (int i = 0; i < childCount; i++) { 14839 String childPackageName = updatedPs.childPackageNames.get(i); 14840 if (outInfo.removedChildPackages == null 14841 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 14842 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 14843 if (childPs == null) { 14844 continue; 14845 } 14846 PackageInstalledInfo installRes = new PackageInstalledInfo(); 14847 installRes.name = childPackageName; 14848 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 14849 installRes.pkg = mPackages.get(childPackageName); 14850 installRes.uid = childPs.pkg.applicationInfo.uid; 14851 if (outInfo.appearedChildPackages == null) { 14852 outInfo.appearedChildPackages = new ArrayMap<>(); 14853 } 14854 outInfo.appearedChildPackages.put(childPackageName, installRes); 14855 } 14856 } 14857 } 14858 } 14859 } 14860 14861 return ret; 14862 } 14863 14864 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 14865 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 14866 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 14867 for (int nextUserId : userIds) { 14868 if (DEBUG_REMOVE) { 14869 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 14870 } 14871 ps.setUserState(nextUserId, COMPONENT_ENABLED_STATE_DEFAULT, 14872 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 14873 false /*hidden*/, false /*suspended*/, null, null, null, 14874 false /*blockUninstall*/, 14875 ps.readUserState(nextUserId).domainVerificationStatus, 0); 14876 } 14877 } 14878 14879 private boolean clearPackageStateForUser(PackageSetting ps, int userId, 14880 PackageRemovedInfo outInfo) { 14881 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 14882 : new int[] {userId}; 14883 for (int nextUserId : userIds) { 14884 if (DEBUG_REMOVE) { 14885 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 14886 + nextUserId); 14887 } 14888 final int flags = StorageManager.FLAG_STORAGE_CE| StorageManager.FLAG_STORAGE_DE; 14889 try { 14890 mInstaller.destroyAppData(ps.volumeUuid, ps.name, nextUserId, flags); 14891 } catch (InstallerException e) { 14892 Slog.w(TAG, "Couldn't remove cache files for package " + ps.name, e); 14893 return false; 14894 } 14895 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 14896 schedulePackageCleaning(ps.name, nextUserId, false); 14897 synchronized (mPackages) { 14898 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 14899 scheduleWritePackageRestrictionsLocked(nextUserId); 14900 } 14901 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 14902 } 14903 } 14904 14905 if (outInfo != null) { 14906 outInfo.removedPackage = ps.name; 14907 outInfo.removedAppId = ps.appId; 14908 outInfo.removedUsers = userIds; 14909 } 14910 14911 return true; 14912 } 14913 14914 private final class ClearStorageConnection implements ServiceConnection { 14915 IMediaContainerService mContainerService; 14916 14917 @Override 14918 public void onServiceConnected(ComponentName name, IBinder service) { 14919 synchronized (this) { 14920 mContainerService = IMediaContainerService.Stub.asInterface(service); 14921 notifyAll(); 14922 } 14923 } 14924 14925 @Override 14926 public void onServiceDisconnected(ComponentName name) { 14927 } 14928 } 14929 14930 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 14931 final boolean mounted; 14932 if (Environment.isExternalStorageEmulated()) { 14933 mounted = true; 14934 } else { 14935 final String status = Environment.getExternalStorageState(); 14936 14937 mounted = status.equals(Environment.MEDIA_MOUNTED) 14938 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 14939 } 14940 14941 if (!mounted) { 14942 return; 14943 } 14944 14945 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 14946 int[] users; 14947 if (userId == UserHandle.USER_ALL) { 14948 users = sUserManager.getUserIds(); 14949 } else { 14950 users = new int[] { userId }; 14951 } 14952 final ClearStorageConnection conn = new ClearStorageConnection(); 14953 if (mContext.bindServiceAsUser( 14954 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 14955 try { 14956 for (int curUser : users) { 14957 long timeout = SystemClock.uptimeMillis() + 5000; 14958 synchronized (conn) { 14959 long now = SystemClock.uptimeMillis(); 14960 while (conn.mContainerService == null && now < timeout) { 14961 try { 14962 conn.wait(timeout - now); 14963 } catch (InterruptedException e) { 14964 } 14965 } 14966 } 14967 if (conn.mContainerService == null) { 14968 return; 14969 } 14970 14971 final UserEnvironment userEnv = new UserEnvironment(curUser); 14972 clearDirectory(conn.mContainerService, 14973 userEnv.buildExternalStorageAppCacheDirs(packageName)); 14974 if (allData) { 14975 clearDirectory(conn.mContainerService, 14976 userEnv.buildExternalStorageAppDataDirs(packageName)); 14977 clearDirectory(conn.mContainerService, 14978 userEnv.buildExternalStorageAppMediaDirs(packageName)); 14979 } 14980 } 14981 } finally { 14982 mContext.unbindService(conn); 14983 } 14984 } 14985 } 14986 14987 @Override 14988 public void clearApplicationUserData(final String packageName, 14989 final IPackageDataObserver observer, final int userId) { 14990 mContext.enforceCallingOrSelfPermission( 14991 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 14992 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 14993 // Queue up an async operation since the package deletion may take a little while. 14994 mHandler.post(new Runnable() { 14995 public void run() { 14996 mHandler.removeCallbacks(this); 14997 final boolean succeeded; 14998 synchronized (mInstallLock) { 14999 succeeded = clearApplicationUserDataLI(packageName, userId); 15000 } 15001 clearExternalStorageDataSync(packageName, userId, true); 15002 if (succeeded) { 15003 // invoke DeviceStorageMonitor's update method to clear any notifications 15004 DeviceStorageMonitorInternal 15005 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 15006 if (dsm != null) { 15007 dsm.checkMemory(); 15008 } 15009 } 15010 if(observer != null) { 15011 try { 15012 observer.onRemoveCompleted(packageName, succeeded); 15013 } catch (RemoteException e) { 15014 Log.i(TAG, "Observer no longer exists."); 15015 } 15016 } //end if observer 15017 } //end run 15018 }); 15019 } 15020 15021 private boolean clearApplicationUserDataLI(String packageName, int userId) { 15022 if (packageName == null) { 15023 Slog.w(TAG, "Attempt to delete null packageName."); 15024 return false; 15025 } 15026 15027 // Try finding details about the requested package 15028 PackageParser.Package pkg; 15029 synchronized (mPackages) { 15030 pkg = mPackages.get(packageName); 15031 if (pkg == null) { 15032 final PackageSetting ps = mSettings.mPackages.get(packageName); 15033 if (ps != null) { 15034 pkg = ps.pkg; 15035 } 15036 } 15037 15038 if (pkg == null) { 15039 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15040 return false; 15041 } 15042 15043 PackageSetting ps = (PackageSetting) pkg.mExtras; 15044 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15045 } 15046 15047 // Always delete data directories for package, even if we found no other 15048 // record of app. This helps users recover from UID mismatches without 15049 // resorting to a full data wipe. 15050 // TODO: triage flags as part of 26466827 15051 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15052 try { 15053 mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags); 15054 } catch (InstallerException e) { 15055 Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e); 15056 return false; 15057 } 15058 15059 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15060 removeKeystoreDataIfNeeded(userId, appId); 15061 15062 // Create a native library symlink only if we have native libraries 15063 // and if the native libraries are 32 bit libraries. We do not provide 15064 // this symlink for 64 bit libraries. 15065 if (pkg.applicationInfo.primaryCpuAbi != null && 15066 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 15067 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 15068 try { 15069 mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 15070 nativeLibPath, userId); 15071 } catch (InstallerException e) { 15072 Slog.w(TAG, "Failed linking native library dir", e); 15073 return false; 15074 } 15075 } 15076 15077 return true; 15078 } 15079 15080 /** 15081 * Reverts user permission state changes (permissions and flags) in 15082 * all packages for a given user. 15083 * 15084 * @param userId The device user for which to do a reset. 15085 */ 15086 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 15087 final int packageCount = mPackages.size(); 15088 for (int i = 0; i < packageCount; i++) { 15089 PackageParser.Package pkg = mPackages.valueAt(i); 15090 PackageSetting ps = (PackageSetting) pkg.mExtras; 15091 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15092 } 15093 } 15094 15095 /** 15096 * Reverts user permission state changes (permissions and flags). 15097 * 15098 * @param ps The package for which to reset. 15099 * @param userId The device user for which to do a reset. 15100 */ 15101 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 15102 final PackageSetting ps, final int userId) { 15103 if (ps.pkg == null) { 15104 return; 15105 } 15106 15107 // These are flags that can change base on user actions. 15108 final int userSettableMask = FLAG_PERMISSION_USER_SET 15109 | FLAG_PERMISSION_USER_FIXED 15110 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 15111 | FLAG_PERMISSION_REVIEW_REQUIRED; 15112 15113 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 15114 | FLAG_PERMISSION_POLICY_FIXED; 15115 15116 boolean writeInstallPermissions = false; 15117 boolean writeRuntimePermissions = false; 15118 15119 final int permissionCount = ps.pkg.requestedPermissions.size(); 15120 for (int i = 0; i < permissionCount; i++) { 15121 String permission = ps.pkg.requestedPermissions.get(i); 15122 15123 BasePermission bp = mSettings.mPermissions.get(permission); 15124 if (bp == null) { 15125 continue; 15126 } 15127 15128 // If shared user we just reset the state to which only this app contributed. 15129 if (ps.sharedUser != null) { 15130 boolean used = false; 15131 final int packageCount = ps.sharedUser.packages.size(); 15132 for (int j = 0; j < packageCount; j++) { 15133 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 15134 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 15135 && pkg.pkg.requestedPermissions.contains(permission)) { 15136 used = true; 15137 break; 15138 } 15139 } 15140 if (used) { 15141 continue; 15142 } 15143 } 15144 15145 PermissionsState permissionsState = ps.getPermissionsState(); 15146 15147 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 15148 15149 // Always clear the user settable flags. 15150 final boolean hasInstallState = permissionsState.getInstallPermissionState( 15151 bp.name) != null; 15152 // If permission review is enabled and this is a legacy app, mark the 15153 // permission as requiring a review as this is the initial state. 15154 int flags = 0; 15155 if (Build.PERMISSIONS_REVIEW_REQUIRED 15156 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 15157 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 15158 } 15159 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 15160 if (hasInstallState) { 15161 writeInstallPermissions = true; 15162 } else { 15163 writeRuntimePermissions = true; 15164 } 15165 } 15166 15167 // Below is only runtime permission handling. 15168 if (!bp.isRuntime()) { 15169 continue; 15170 } 15171 15172 // Never clobber system or policy. 15173 if ((oldFlags & policyOrSystemFlags) != 0) { 15174 continue; 15175 } 15176 15177 // If this permission was granted by default, make sure it is. 15178 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 15179 if (permissionsState.grantRuntimePermission(bp, userId) 15180 != PERMISSION_OPERATION_FAILURE) { 15181 writeRuntimePermissions = true; 15182 } 15183 // If permission review is enabled the permissions for a legacy apps 15184 // are represented as constantly granted runtime ones, so don't revoke. 15185 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 15186 // Otherwise, reset the permission. 15187 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 15188 switch (revokeResult) { 15189 case PERMISSION_OPERATION_SUCCESS: { 15190 writeRuntimePermissions = true; 15191 } break; 15192 15193 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 15194 writeRuntimePermissions = true; 15195 final int appId = ps.appId; 15196 mHandler.post(new Runnable() { 15197 @Override 15198 public void run() { 15199 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 15200 } 15201 }); 15202 } break; 15203 } 15204 } 15205 } 15206 15207 // Synchronously write as we are taking permissions away. 15208 if (writeRuntimePermissions) { 15209 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 15210 } 15211 15212 // Synchronously write as we are taking permissions away. 15213 if (writeInstallPermissions) { 15214 mSettings.writeLPr(); 15215 } 15216 } 15217 15218 /** 15219 * Remove entries from the keystore daemon. Will only remove it if the 15220 * {@code appId} is valid. 15221 */ 15222 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 15223 if (appId < 0) { 15224 return; 15225 } 15226 15227 final KeyStore keyStore = KeyStore.getInstance(); 15228 if (keyStore != null) { 15229 if (userId == UserHandle.USER_ALL) { 15230 for (final int individual : sUserManager.getUserIds()) { 15231 keyStore.clearUid(UserHandle.getUid(individual, appId)); 15232 } 15233 } else { 15234 keyStore.clearUid(UserHandle.getUid(userId, appId)); 15235 } 15236 } else { 15237 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 15238 } 15239 } 15240 15241 @Override 15242 public void deleteApplicationCacheFiles(final String packageName, 15243 final IPackageDataObserver observer) { 15244 mContext.enforceCallingOrSelfPermission( 15245 android.Manifest.permission.DELETE_CACHE_FILES, null); 15246 // Queue up an async operation since the package deletion may take a little while. 15247 final int userId = UserHandle.getCallingUserId(); 15248 mHandler.post(new Runnable() { 15249 public void run() { 15250 mHandler.removeCallbacks(this); 15251 final boolean succeded; 15252 synchronized (mInstallLock) { 15253 succeded = deleteApplicationCacheFilesLI(packageName, userId); 15254 } 15255 clearExternalStorageDataSync(packageName, userId, false); 15256 if (observer != null) { 15257 try { 15258 observer.onRemoveCompleted(packageName, succeded); 15259 } catch (RemoteException e) { 15260 Log.i(TAG, "Observer no longer exists."); 15261 } 15262 } //end if observer 15263 } //end run 15264 }); 15265 } 15266 15267 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 15268 if (packageName == null) { 15269 Slog.w(TAG, "Attempt to delete null packageName."); 15270 return false; 15271 } 15272 PackageParser.Package p; 15273 synchronized (mPackages) { 15274 p = mPackages.get(packageName); 15275 } 15276 if (p == null) { 15277 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 15278 return false; 15279 } 15280 final ApplicationInfo applicationInfo = p.applicationInfo; 15281 if (applicationInfo == null) { 15282 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 15283 return false; 15284 } 15285 // TODO: triage flags as part of 26466827 15286 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15287 try { 15288 mInstaller.clearAppData(p.volumeUuid, packageName, userId, 15289 flags | Installer.FLAG_CLEAR_CACHE_ONLY); 15290 } catch (InstallerException e) { 15291 Slog.w(TAG, "Couldn't remove cache files for package " 15292 + packageName + " u" + userId, e); 15293 return false; 15294 } 15295 return true; 15296 } 15297 15298 @Override 15299 public void getPackageSizeInfo(final String packageName, int userHandle, 15300 final IPackageStatsObserver observer) { 15301 mContext.enforceCallingOrSelfPermission( 15302 android.Manifest.permission.GET_PACKAGE_SIZE, null); 15303 if (packageName == null) { 15304 throw new IllegalArgumentException("Attempt to get size of null packageName"); 15305 } 15306 15307 PackageStats stats = new PackageStats(packageName, userHandle); 15308 15309 /* 15310 * Queue up an async operation since the package measurement may take a 15311 * little while. 15312 */ 15313 Message msg = mHandler.obtainMessage(INIT_COPY); 15314 msg.obj = new MeasureParams(stats, observer); 15315 mHandler.sendMessage(msg); 15316 } 15317 15318 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 15319 PackageStats pStats) { 15320 if (packageName == null) { 15321 Slog.w(TAG, "Attempt to get size of null packageName."); 15322 return false; 15323 } 15324 PackageParser.Package p; 15325 boolean dataOnly = false; 15326 String libDirRoot = null; 15327 String asecPath = null; 15328 PackageSetting ps = null; 15329 synchronized (mPackages) { 15330 p = mPackages.get(packageName); 15331 ps = mSettings.mPackages.get(packageName); 15332 if(p == null) { 15333 dataOnly = true; 15334 if((ps == null) || (ps.pkg == null)) { 15335 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 15336 return false; 15337 } 15338 p = ps.pkg; 15339 } 15340 if (ps != null) { 15341 libDirRoot = ps.legacyNativeLibraryPathString; 15342 } 15343 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 15344 final long token = Binder.clearCallingIdentity(); 15345 try { 15346 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 15347 if (secureContainerId != null) { 15348 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 15349 } 15350 } finally { 15351 Binder.restoreCallingIdentity(token); 15352 } 15353 } 15354 } 15355 String publicSrcDir = null; 15356 if(!dataOnly) { 15357 final ApplicationInfo applicationInfo = p.applicationInfo; 15358 if (applicationInfo == null) { 15359 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 15360 return false; 15361 } 15362 if (p.isForwardLocked()) { 15363 publicSrcDir = applicationInfo.getBaseResourcePath(); 15364 } 15365 } 15366 // TODO: extend to measure size of split APKs 15367 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 15368 // not just the first level. 15369 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 15370 // just the primary. 15371 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 15372 15373 String apkPath; 15374 File packageDir = new File(p.codePath); 15375 15376 if (packageDir.isDirectory() && p.canHaveOatDir()) { 15377 apkPath = packageDir.getAbsolutePath(); 15378 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 15379 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 15380 libDirRoot = null; 15381 } 15382 } else { 15383 apkPath = p.baseCodePath; 15384 } 15385 15386 // TODO: triage flags as part of 26466827 15387 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15388 try { 15389 mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath, 15390 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 15391 } catch (InstallerException e) { 15392 return false; 15393 } 15394 15395 // Fix-up for forward-locked applications in ASEC containers. 15396 if (!isExternal(p)) { 15397 pStats.codeSize += pStats.externalCodeSize; 15398 pStats.externalCodeSize = 0L; 15399 } 15400 15401 return true; 15402 } 15403 15404 15405 @Override 15406 public void addPackageToPreferred(String packageName) { 15407 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 15408 } 15409 15410 @Override 15411 public void removePackageFromPreferred(String packageName) { 15412 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 15413 } 15414 15415 @Override 15416 public List<PackageInfo> getPreferredPackages(int flags) { 15417 return new ArrayList<PackageInfo>(); 15418 } 15419 15420 private int getUidTargetSdkVersionLockedLPr(int uid) { 15421 Object obj = mSettings.getUserIdLPr(uid); 15422 if (obj instanceof SharedUserSetting) { 15423 final SharedUserSetting sus = (SharedUserSetting) obj; 15424 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 15425 final Iterator<PackageSetting> it = sus.packages.iterator(); 15426 while (it.hasNext()) { 15427 final PackageSetting ps = it.next(); 15428 if (ps.pkg != null) { 15429 int v = ps.pkg.applicationInfo.targetSdkVersion; 15430 if (v < vers) vers = v; 15431 } 15432 } 15433 return vers; 15434 } else if (obj instanceof PackageSetting) { 15435 final PackageSetting ps = (PackageSetting) obj; 15436 if (ps.pkg != null) { 15437 return ps.pkg.applicationInfo.targetSdkVersion; 15438 } 15439 } 15440 return Build.VERSION_CODES.CUR_DEVELOPMENT; 15441 } 15442 15443 @Override 15444 public void addPreferredActivity(IntentFilter filter, int match, 15445 ComponentName[] set, ComponentName activity, int userId) { 15446 addPreferredActivityInternal(filter, match, set, activity, true, userId, 15447 "Adding preferred"); 15448 } 15449 15450 private void addPreferredActivityInternal(IntentFilter filter, int match, 15451 ComponentName[] set, ComponentName activity, boolean always, int userId, 15452 String opname) { 15453 // writer 15454 int callingUid = Binder.getCallingUid(); 15455 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 15456 if (filter.countActions() == 0) { 15457 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 15458 return; 15459 } 15460 synchronized (mPackages) { 15461 if (mContext.checkCallingOrSelfPermission( 15462 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15463 != PackageManager.PERMISSION_GRANTED) { 15464 if (getUidTargetSdkVersionLockedLPr(callingUid) 15465 < Build.VERSION_CODES.FROYO) { 15466 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 15467 + callingUid); 15468 return; 15469 } 15470 mContext.enforceCallingOrSelfPermission( 15471 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15472 } 15473 15474 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 15475 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 15476 + userId + ":"); 15477 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15478 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 15479 scheduleWritePackageRestrictionsLocked(userId); 15480 } 15481 } 15482 15483 @Override 15484 public void replacePreferredActivity(IntentFilter filter, int match, 15485 ComponentName[] set, ComponentName activity, int userId) { 15486 if (filter.countActions() != 1) { 15487 throw new IllegalArgumentException( 15488 "replacePreferredActivity expects filter to have only 1 action."); 15489 } 15490 if (filter.countDataAuthorities() != 0 15491 || filter.countDataPaths() != 0 15492 || filter.countDataSchemes() > 1 15493 || filter.countDataTypes() != 0) { 15494 throw new IllegalArgumentException( 15495 "replacePreferredActivity expects filter to have no data authorities, " + 15496 "paths, or types; and at most one scheme."); 15497 } 15498 15499 final int callingUid = Binder.getCallingUid(); 15500 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 15501 synchronized (mPackages) { 15502 if (mContext.checkCallingOrSelfPermission( 15503 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15504 != PackageManager.PERMISSION_GRANTED) { 15505 if (getUidTargetSdkVersionLockedLPr(callingUid) 15506 < Build.VERSION_CODES.FROYO) { 15507 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 15508 + Binder.getCallingUid()); 15509 return; 15510 } 15511 mContext.enforceCallingOrSelfPermission( 15512 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15513 } 15514 15515 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 15516 if (pir != null) { 15517 // Get all of the existing entries that exactly match this filter. 15518 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 15519 if (existing != null && existing.size() == 1) { 15520 PreferredActivity cur = existing.get(0); 15521 if (DEBUG_PREFERRED) { 15522 Slog.i(TAG, "Checking replace of preferred:"); 15523 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15524 if (!cur.mPref.mAlways) { 15525 Slog.i(TAG, " -- CUR; not mAlways!"); 15526 } else { 15527 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 15528 Slog.i(TAG, " -- CUR: mSet=" 15529 + Arrays.toString(cur.mPref.mSetComponents)); 15530 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 15531 Slog.i(TAG, " -- NEW: mMatch=" 15532 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 15533 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 15534 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 15535 } 15536 } 15537 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 15538 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 15539 && cur.mPref.sameSet(set)) { 15540 // Setting the preferred activity to what it happens to be already 15541 if (DEBUG_PREFERRED) { 15542 Slog.i(TAG, "Replacing with same preferred activity " 15543 + cur.mPref.mShortComponent + " for user " 15544 + userId + ":"); 15545 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15546 } 15547 return; 15548 } 15549 } 15550 15551 if (existing != null) { 15552 if (DEBUG_PREFERRED) { 15553 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 15554 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15555 } 15556 for (int i = 0; i < existing.size(); i++) { 15557 PreferredActivity pa = existing.get(i); 15558 if (DEBUG_PREFERRED) { 15559 Slog.i(TAG, "Removing existing preferred activity " 15560 + pa.mPref.mComponent + ":"); 15561 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 15562 } 15563 pir.removeFilter(pa); 15564 } 15565 } 15566 } 15567 addPreferredActivityInternal(filter, match, set, activity, true, userId, 15568 "Replacing preferred"); 15569 } 15570 } 15571 15572 @Override 15573 public void clearPackagePreferredActivities(String packageName) { 15574 final int uid = Binder.getCallingUid(); 15575 // writer 15576 synchronized (mPackages) { 15577 PackageParser.Package pkg = mPackages.get(packageName); 15578 if (pkg == null || pkg.applicationInfo.uid != uid) { 15579 if (mContext.checkCallingOrSelfPermission( 15580 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15581 != PackageManager.PERMISSION_GRANTED) { 15582 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 15583 < Build.VERSION_CODES.FROYO) { 15584 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 15585 + Binder.getCallingUid()); 15586 return; 15587 } 15588 mContext.enforceCallingOrSelfPermission( 15589 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15590 } 15591 } 15592 15593 int user = UserHandle.getCallingUserId(); 15594 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 15595 scheduleWritePackageRestrictionsLocked(user); 15596 } 15597 } 15598 } 15599 15600 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15601 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 15602 ArrayList<PreferredActivity> removed = null; 15603 boolean changed = false; 15604 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15605 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 15606 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15607 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 15608 continue; 15609 } 15610 Iterator<PreferredActivity> it = pir.filterIterator(); 15611 while (it.hasNext()) { 15612 PreferredActivity pa = it.next(); 15613 // Mark entry for removal only if it matches the package name 15614 // and the entry is of type "always". 15615 if (packageName == null || 15616 (pa.mPref.mComponent.getPackageName().equals(packageName) 15617 && pa.mPref.mAlways)) { 15618 if (removed == null) { 15619 removed = new ArrayList<PreferredActivity>(); 15620 } 15621 removed.add(pa); 15622 } 15623 } 15624 if (removed != null) { 15625 for (int j=0; j<removed.size(); j++) { 15626 PreferredActivity pa = removed.get(j); 15627 pir.removeFilter(pa); 15628 } 15629 changed = true; 15630 } 15631 } 15632 return changed; 15633 } 15634 15635 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15636 private void clearIntentFilterVerificationsLPw(int userId) { 15637 final int packageCount = mPackages.size(); 15638 for (int i = 0; i < packageCount; i++) { 15639 PackageParser.Package pkg = mPackages.valueAt(i); 15640 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 15641 } 15642 } 15643 15644 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15645 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 15646 if (userId == UserHandle.USER_ALL) { 15647 if (mSettings.removeIntentFilterVerificationLPw(packageName, 15648 sUserManager.getUserIds())) { 15649 for (int oneUserId : sUserManager.getUserIds()) { 15650 scheduleWritePackageRestrictionsLocked(oneUserId); 15651 } 15652 } 15653 } else { 15654 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 15655 scheduleWritePackageRestrictionsLocked(userId); 15656 } 15657 } 15658 } 15659 15660 void clearDefaultBrowserIfNeeded(String packageName) { 15661 for (int oneUserId : sUserManager.getUserIds()) { 15662 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 15663 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 15664 if (packageName.equals(defaultBrowserPackageName)) { 15665 setDefaultBrowserPackageName(null, oneUserId); 15666 } 15667 } 15668 } 15669 15670 @Override 15671 public void resetApplicationPreferences(int userId) { 15672 mContext.enforceCallingOrSelfPermission( 15673 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15674 // writer 15675 synchronized (mPackages) { 15676 final long identity = Binder.clearCallingIdentity(); 15677 try { 15678 clearPackagePreferredActivitiesLPw(null, userId); 15679 mSettings.applyDefaultPreferredAppsLPw(this, userId); 15680 // TODO: We have to reset the default SMS and Phone. This requires 15681 // significant refactoring to keep all default apps in the package 15682 // manager (cleaner but more work) or have the services provide 15683 // callbacks to the package manager to request a default app reset. 15684 applyFactoryDefaultBrowserLPw(userId); 15685 clearIntentFilterVerificationsLPw(userId); 15686 primeDomainVerificationsLPw(userId); 15687 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 15688 scheduleWritePackageRestrictionsLocked(userId); 15689 } finally { 15690 Binder.restoreCallingIdentity(identity); 15691 } 15692 } 15693 } 15694 15695 @Override 15696 public int getPreferredActivities(List<IntentFilter> outFilters, 15697 List<ComponentName> outActivities, String packageName) { 15698 15699 int num = 0; 15700 final int userId = UserHandle.getCallingUserId(); 15701 // reader 15702 synchronized (mPackages) { 15703 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 15704 if (pir != null) { 15705 final Iterator<PreferredActivity> it = pir.filterIterator(); 15706 while (it.hasNext()) { 15707 final PreferredActivity pa = it.next(); 15708 if (packageName == null 15709 || (pa.mPref.mComponent.getPackageName().equals(packageName) 15710 && pa.mPref.mAlways)) { 15711 if (outFilters != null) { 15712 outFilters.add(new IntentFilter(pa)); 15713 } 15714 if (outActivities != null) { 15715 outActivities.add(pa.mPref.mComponent); 15716 } 15717 } 15718 } 15719 } 15720 } 15721 15722 return num; 15723 } 15724 15725 @Override 15726 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 15727 int userId) { 15728 int callingUid = Binder.getCallingUid(); 15729 if (callingUid != Process.SYSTEM_UID) { 15730 throw new SecurityException( 15731 "addPersistentPreferredActivity can only be run by the system"); 15732 } 15733 if (filter.countActions() == 0) { 15734 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 15735 return; 15736 } 15737 synchronized (mPackages) { 15738 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 15739 ":"); 15740 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15741 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 15742 new PersistentPreferredActivity(filter, activity)); 15743 scheduleWritePackageRestrictionsLocked(userId); 15744 } 15745 } 15746 15747 @Override 15748 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 15749 int callingUid = Binder.getCallingUid(); 15750 if (callingUid != Process.SYSTEM_UID) { 15751 throw new SecurityException( 15752 "clearPackagePersistentPreferredActivities can only be run by the system"); 15753 } 15754 ArrayList<PersistentPreferredActivity> removed = null; 15755 boolean changed = false; 15756 synchronized (mPackages) { 15757 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 15758 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 15759 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 15760 .valueAt(i); 15761 if (userId != thisUserId) { 15762 continue; 15763 } 15764 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 15765 while (it.hasNext()) { 15766 PersistentPreferredActivity ppa = it.next(); 15767 // Mark entry for removal only if it matches the package name. 15768 if (ppa.mComponent.getPackageName().equals(packageName)) { 15769 if (removed == null) { 15770 removed = new ArrayList<PersistentPreferredActivity>(); 15771 } 15772 removed.add(ppa); 15773 } 15774 } 15775 if (removed != null) { 15776 for (int j=0; j<removed.size(); j++) { 15777 PersistentPreferredActivity ppa = removed.get(j); 15778 ppir.removeFilter(ppa); 15779 } 15780 changed = true; 15781 } 15782 } 15783 15784 if (changed) { 15785 scheduleWritePackageRestrictionsLocked(userId); 15786 } 15787 } 15788 } 15789 15790 /** 15791 * Common machinery for picking apart a restored XML blob and passing 15792 * it to a caller-supplied functor to be applied to the running system. 15793 */ 15794 private void restoreFromXml(XmlPullParser parser, int userId, 15795 String expectedStartTag, BlobXmlRestorer functor) 15796 throws IOException, XmlPullParserException { 15797 int type; 15798 while ((type = parser.next()) != XmlPullParser.START_TAG 15799 && type != XmlPullParser.END_DOCUMENT) { 15800 } 15801 if (type != XmlPullParser.START_TAG) { 15802 // oops didn't find a start tag?! 15803 if (DEBUG_BACKUP) { 15804 Slog.e(TAG, "Didn't find start tag during restore"); 15805 } 15806 return; 15807 } 15808Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 15809 // this is supposed to be TAG_PREFERRED_BACKUP 15810 if (!expectedStartTag.equals(parser.getName())) { 15811 if (DEBUG_BACKUP) { 15812 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 15813 } 15814 return; 15815 } 15816 15817 // skip interfering stuff, then we're aligned with the backing implementation 15818 while ((type = parser.next()) == XmlPullParser.TEXT) { } 15819Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 15820 functor.apply(parser, userId); 15821 } 15822 15823 private interface BlobXmlRestorer { 15824 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 15825 } 15826 15827 /** 15828 * Non-Binder method, support for the backup/restore mechanism: write the 15829 * full set of preferred activities in its canonical XML format. Returns the 15830 * XML output as a byte array, or null if there is none. 15831 */ 15832 @Override 15833 public byte[] getPreferredActivityBackup(int userId) { 15834 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15835 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 15836 } 15837 15838 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 15839 try { 15840 final XmlSerializer serializer = new FastXmlSerializer(); 15841 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 15842 serializer.startDocument(null, true); 15843 serializer.startTag(null, TAG_PREFERRED_BACKUP); 15844 15845 synchronized (mPackages) { 15846 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 15847 } 15848 15849 serializer.endTag(null, TAG_PREFERRED_BACKUP); 15850 serializer.endDocument(); 15851 serializer.flush(); 15852 } catch (Exception e) { 15853 if (DEBUG_BACKUP) { 15854 Slog.e(TAG, "Unable to write preferred activities for backup", e); 15855 } 15856 return null; 15857 } 15858 15859 return dataStream.toByteArray(); 15860 } 15861 15862 @Override 15863 public void restorePreferredActivities(byte[] backup, int userId) { 15864 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15865 throw new SecurityException("Only the system may call restorePreferredActivities()"); 15866 } 15867 15868 try { 15869 final XmlPullParser parser = Xml.newPullParser(); 15870 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 15871 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 15872 new BlobXmlRestorer() { 15873 @Override 15874 public void apply(XmlPullParser parser, int userId) 15875 throws XmlPullParserException, IOException { 15876 synchronized (mPackages) { 15877 mSettings.readPreferredActivitiesLPw(parser, userId); 15878 } 15879 } 15880 } ); 15881 } catch (Exception e) { 15882 if (DEBUG_BACKUP) { 15883 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 15884 } 15885 } 15886 } 15887 15888 /** 15889 * Non-Binder method, support for the backup/restore mechanism: write the 15890 * default browser (etc) settings in its canonical XML format. Returns the default 15891 * browser XML representation as a byte array, or null if there is none. 15892 */ 15893 @Override 15894 public byte[] getDefaultAppsBackup(int userId) { 15895 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15896 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 15897 } 15898 15899 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 15900 try { 15901 final XmlSerializer serializer = new FastXmlSerializer(); 15902 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 15903 serializer.startDocument(null, true); 15904 serializer.startTag(null, TAG_DEFAULT_APPS); 15905 15906 synchronized (mPackages) { 15907 mSettings.writeDefaultAppsLPr(serializer, userId); 15908 } 15909 15910 serializer.endTag(null, TAG_DEFAULT_APPS); 15911 serializer.endDocument(); 15912 serializer.flush(); 15913 } catch (Exception e) { 15914 if (DEBUG_BACKUP) { 15915 Slog.e(TAG, "Unable to write default apps for backup", e); 15916 } 15917 return null; 15918 } 15919 15920 return dataStream.toByteArray(); 15921 } 15922 15923 @Override 15924 public void restoreDefaultApps(byte[] backup, int userId) { 15925 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15926 throw new SecurityException("Only the system may call restoreDefaultApps()"); 15927 } 15928 15929 try { 15930 final XmlPullParser parser = Xml.newPullParser(); 15931 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 15932 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 15933 new BlobXmlRestorer() { 15934 @Override 15935 public void apply(XmlPullParser parser, int userId) 15936 throws XmlPullParserException, IOException { 15937 synchronized (mPackages) { 15938 mSettings.readDefaultAppsLPw(parser, userId); 15939 } 15940 } 15941 } ); 15942 } catch (Exception e) { 15943 if (DEBUG_BACKUP) { 15944 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 15945 } 15946 } 15947 } 15948 15949 @Override 15950 public byte[] getIntentFilterVerificationBackup(int userId) { 15951 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15952 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 15953 } 15954 15955 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 15956 try { 15957 final XmlSerializer serializer = new FastXmlSerializer(); 15958 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 15959 serializer.startDocument(null, true); 15960 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 15961 15962 synchronized (mPackages) { 15963 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 15964 } 15965 15966 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 15967 serializer.endDocument(); 15968 serializer.flush(); 15969 } catch (Exception e) { 15970 if (DEBUG_BACKUP) { 15971 Slog.e(TAG, "Unable to write default apps for backup", e); 15972 } 15973 return null; 15974 } 15975 15976 return dataStream.toByteArray(); 15977 } 15978 15979 @Override 15980 public void restoreIntentFilterVerification(byte[] backup, int userId) { 15981 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15982 throw new SecurityException("Only the system may call restorePreferredActivities()"); 15983 } 15984 15985 try { 15986 final XmlPullParser parser = Xml.newPullParser(); 15987 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 15988 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 15989 new BlobXmlRestorer() { 15990 @Override 15991 public void apply(XmlPullParser parser, int userId) 15992 throws XmlPullParserException, IOException { 15993 synchronized (mPackages) { 15994 mSettings.readAllDomainVerificationsLPr(parser, userId); 15995 mSettings.writeLPr(); 15996 } 15997 } 15998 } ); 15999 } catch (Exception e) { 16000 if (DEBUG_BACKUP) { 16001 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16002 } 16003 } 16004 } 16005 16006 @Override 16007 public byte[] getPermissionGrantBackup(int userId) { 16008 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16009 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 16010 } 16011 16012 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16013 try { 16014 final XmlSerializer serializer = new FastXmlSerializer(); 16015 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16016 serializer.startDocument(null, true); 16017 serializer.startTag(null, TAG_PERMISSION_BACKUP); 16018 16019 synchronized (mPackages) { 16020 serializeRuntimePermissionGrantsLPr(serializer, userId); 16021 } 16022 16023 serializer.endTag(null, TAG_PERMISSION_BACKUP); 16024 serializer.endDocument(); 16025 serializer.flush(); 16026 } catch (Exception e) { 16027 if (DEBUG_BACKUP) { 16028 Slog.e(TAG, "Unable to write default apps for backup", e); 16029 } 16030 return null; 16031 } 16032 16033 return dataStream.toByteArray(); 16034 } 16035 16036 @Override 16037 public void restorePermissionGrants(byte[] backup, int userId) { 16038 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16039 throw new SecurityException("Only the system may call restorePermissionGrants()"); 16040 } 16041 16042 try { 16043 final XmlPullParser parser = Xml.newPullParser(); 16044 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16045 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 16046 new BlobXmlRestorer() { 16047 @Override 16048 public void apply(XmlPullParser parser, int userId) 16049 throws XmlPullParserException, IOException { 16050 synchronized (mPackages) { 16051 processRestoredPermissionGrantsLPr(parser, userId); 16052 } 16053 } 16054 } ); 16055 } catch (Exception e) { 16056 if (DEBUG_BACKUP) { 16057 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16058 } 16059 } 16060 } 16061 16062 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 16063 throws IOException { 16064 serializer.startTag(null, TAG_ALL_GRANTS); 16065 16066 final int N = mSettings.mPackages.size(); 16067 for (int i = 0; i < N; i++) { 16068 final PackageSetting ps = mSettings.mPackages.valueAt(i); 16069 boolean pkgGrantsKnown = false; 16070 16071 PermissionsState packagePerms = ps.getPermissionsState(); 16072 16073 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 16074 final int grantFlags = state.getFlags(); 16075 // only look at grants that are not system/policy fixed 16076 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 16077 final boolean isGranted = state.isGranted(); 16078 // And only back up the user-twiddled state bits 16079 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 16080 final String packageName = mSettings.mPackages.keyAt(i); 16081 if (!pkgGrantsKnown) { 16082 serializer.startTag(null, TAG_GRANT); 16083 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 16084 pkgGrantsKnown = true; 16085 } 16086 16087 final boolean userSet = 16088 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 16089 final boolean userFixed = 16090 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 16091 final boolean revoke = 16092 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 16093 16094 serializer.startTag(null, TAG_PERMISSION); 16095 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 16096 if (isGranted) { 16097 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 16098 } 16099 if (userSet) { 16100 serializer.attribute(null, ATTR_USER_SET, "true"); 16101 } 16102 if (userFixed) { 16103 serializer.attribute(null, ATTR_USER_FIXED, "true"); 16104 } 16105 if (revoke) { 16106 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 16107 } 16108 serializer.endTag(null, TAG_PERMISSION); 16109 } 16110 } 16111 } 16112 16113 if (pkgGrantsKnown) { 16114 serializer.endTag(null, TAG_GRANT); 16115 } 16116 } 16117 16118 serializer.endTag(null, TAG_ALL_GRANTS); 16119 } 16120 16121 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 16122 throws XmlPullParserException, IOException { 16123 String pkgName = null; 16124 int outerDepth = parser.getDepth(); 16125 int type; 16126 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 16127 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 16128 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 16129 continue; 16130 } 16131 16132 final String tagName = parser.getName(); 16133 if (tagName.equals(TAG_GRANT)) { 16134 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 16135 if (DEBUG_BACKUP) { 16136 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 16137 } 16138 } else if (tagName.equals(TAG_PERMISSION)) { 16139 16140 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 16141 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 16142 16143 int newFlagSet = 0; 16144 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 16145 newFlagSet |= FLAG_PERMISSION_USER_SET; 16146 } 16147 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 16148 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 16149 } 16150 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 16151 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 16152 } 16153 if (DEBUG_BACKUP) { 16154 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 16155 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 16156 } 16157 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16158 if (ps != null) { 16159 // Already installed so we apply the grant immediately 16160 if (DEBUG_BACKUP) { 16161 Slog.v(TAG, " + already installed; applying"); 16162 } 16163 PermissionsState perms = ps.getPermissionsState(); 16164 BasePermission bp = mSettings.mPermissions.get(permName); 16165 if (bp != null) { 16166 if (isGranted) { 16167 perms.grantRuntimePermission(bp, userId); 16168 } 16169 if (newFlagSet != 0) { 16170 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 16171 } 16172 } 16173 } else { 16174 // Need to wait for post-restore install to apply the grant 16175 if (DEBUG_BACKUP) { 16176 Slog.v(TAG, " - not yet installed; saving for later"); 16177 } 16178 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 16179 isGranted, newFlagSet, userId); 16180 } 16181 } else { 16182 PackageManagerService.reportSettingsProblem(Log.WARN, 16183 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 16184 XmlUtils.skipCurrentTag(parser); 16185 } 16186 } 16187 16188 scheduleWriteSettingsLocked(); 16189 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16190 } 16191 16192 @Override 16193 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 16194 int sourceUserId, int targetUserId, int flags) { 16195 mContext.enforceCallingOrSelfPermission( 16196 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16197 int callingUid = Binder.getCallingUid(); 16198 enforceOwnerRights(ownerPackage, callingUid); 16199 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16200 if (intentFilter.countActions() == 0) { 16201 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 16202 return; 16203 } 16204 synchronized (mPackages) { 16205 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 16206 ownerPackage, targetUserId, flags); 16207 CrossProfileIntentResolver resolver = 16208 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16209 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 16210 // We have all those whose filter is equal. Now checking if the rest is equal as well. 16211 if (existing != null) { 16212 int size = existing.size(); 16213 for (int i = 0; i < size; i++) { 16214 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 16215 return; 16216 } 16217 } 16218 } 16219 resolver.addFilter(newFilter); 16220 scheduleWritePackageRestrictionsLocked(sourceUserId); 16221 } 16222 } 16223 16224 @Override 16225 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 16226 mContext.enforceCallingOrSelfPermission( 16227 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16228 int callingUid = Binder.getCallingUid(); 16229 enforceOwnerRights(ownerPackage, callingUid); 16230 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16231 synchronized (mPackages) { 16232 CrossProfileIntentResolver resolver = 16233 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16234 ArraySet<CrossProfileIntentFilter> set = 16235 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 16236 for (CrossProfileIntentFilter filter : set) { 16237 if (filter.getOwnerPackage().equals(ownerPackage)) { 16238 resolver.removeFilter(filter); 16239 } 16240 } 16241 scheduleWritePackageRestrictionsLocked(sourceUserId); 16242 } 16243 } 16244 16245 // Enforcing that callingUid is owning pkg on userId 16246 private void enforceOwnerRights(String pkg, int callingUid) { 16247 // The system owns everything. 16248 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 16249 return; 16250 } 16251 int callingUserId = UserHandle.getUserId(callingUid); 16252 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 16253 if (pi == null) { 16254 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 16255 + callingUserId); 16256 } 16257 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 16258 throw new SecurityException("Calling uid " + callingUid 16259 + " does not own package " + pkg); 16260 } 16261 } 16262 16263 @Override 16264 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 16265 Intent intent = new Intent(Intent.ACTION_MAIN); 16266 intent.addCategory(Intent.CATEGORY_HOME); 16267 16268 final int callingUserId = UserHandle.getCallingUserId(); 16269 List<ResolveInfo> list = queryIntentActivities(intent, null, 16270 PackageManager.GET_META_DATA, callingUserId); 16271 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 16272 true, false, false, callingUserId); 16273 16274 allHomeCandidates.clear(); 16275 if (list != null) { 16276 for (ResolveInfo ri : list) { 16277 allHomeCandidates.add(ri); 16278 } 16279 } 16280 return (preferred == null || preferred.activityInfo == null) 16281 ? null 16282 : new ComponentName(preferred.activityInfo.packageName, 16283 preferred.activityInfo.name); 16284 } 16285 16286 @Override 16287 public void setApplicationEnabledSetting(String appPackageName, 16288 int newState, int flags, int userId, String callingPackage) { 16289 if (!sUserManager.exists(userId)) return; 16290 if (callingPackage == null) { 16291 callingPackage = Integer.toString(Binder.getCallingUid()); 16292 } 16293 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 16294 } 16295 16296 @Override 16297 public void setComponentEnabledSetting(ComponentName componentName, 16298 int newState, int flags, int userId) { 16299 if (!sUserManager.exists(userId)) return; 16300 setEnabledSetting(componentName.getPackageName(), 16301 componentName.getClassName(), newState, flags, userId, null); 16302 } 16303 16304 private void setEnabledSetting(final String packageName, String className, int newState, 16305 final int flags, int userId, String callingPackage) { 16306 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 16307 || newState == COMPONENT_ENABLED_STATE_ENABLED 16308 || newState == COMPONENT_ENABLED_STATE_DISABLED 16309 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 16310 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 16311 throw new IllegalArgumentException("Invalid new component state: " 16312 + newState); 16313 } 16314 PackageSetting pkgSetting; 16315 final int uid = Binder.getCallingUid(); 16316 final int permission = mContext.checkCallingOrSelfPermission( 16317 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 16318 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 16319 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 16320 boolean sendNow = false; 16321 boolean isApp = (className == null); 16322 String componentName = isApp ? packageName : className; 16323 int packageUid = -1; 16324 ArrayList<String> components; 16325 16326 // writer 16327 synchronized (mPackages) { 16328 pkgSetting = mSettings.mPackages.get(packageName); 16329 if (pkgSetting == null) { 16330 if (className == null) { 16331 throw new IllegalArgumentException("Unknown package: " + packageName); 16332 } 16333 throw new IllegalArgumentException( 16334 "Unknown component: " + packageName + "/" + className); 16335 } 16336 // Allow root and verify that userId is not being specified by a different user 16337 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 16338 throw new SecurityException( 16339 "Permission Denial: attempt to change component state from pid=" 16340 + Binder.getCallingPid() 16341 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 16342 } 16343 if (className == null) { 16344 // We're dealing with an application/package level state change 16345 if (pkgSetting.getEnabled(userId) == newState) { 16346 // Nothing to do 16347 return; 16348 } 16349 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 16350 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 16351 // Don't care about who enables an app. 16352 callingPackage = null; 16353 } 16354 pkgSetting.setEnabled(newState, userId, callingPackage); 16355 // pkgSetting.pkg.mSetEnabled = newState; 16356 } else { 16357 // We're dealing with a component level state change 16358 // First, verify that this is a valid class name. 16359 PackageParser.Package pkg = pkgSetting.pkg; 16360 if (pkg == null || !pkg.hasComponentClassName(className)) { 16361 if (pkg != null && 16362 pkg.applicationInfo.targetSdkVersion >= 16363 Build.VERSION_CODES.JELLY_BEAN) { 16364 throw new IllegalArgumentException("Component class " + className 16365 + " does not exist in " + packageName); 16366 } else { 16367 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 16368 + className + " does not exist in " + packageName); 16369 } 16370 } 16371 switch (newState) { 16372 case COMPONENT_ENABLED_STATE_ENABLED: 16373 if (!pkgSetting.enableComponentLPw(className, userId)) { 16374 return; 16375 } 16376 break; 16377 case COMPONENT_ENABLED_STATE_DISABLED: 16378 if (!pkgSetting.disableComponentLPw(className, userId)) { 16379 return; 16380 } 16381 break; 16382 case COMPONENT_ENABLED_STATE_DEFAULT: 16383 if (!pkgSetting.restoreComponentLPw(className, userId)) { 16384 return; 16385 } 16386 break; 16387 default: 16388 Slog.e(TAG, "Invalid new component state: " + newState); 16389 return; 16390 } 16391 } 16392 scheduleWritePackageRestrictionsLocked(userId); 16393 components = mPendingBroadcasts.get(userId, packageName); 16394 final boolean newPackage = components == null; 16395 if (newPackage) { 16396 components = new ArrayList<String>(); 16397 } 16398 if (!components.contains(componentName)) { 16399 components.add(componentName); 16400 } 16401 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 16402 sendNow = true; 16403 // Purge entry from pending broadcast list if another one exists already 16404 // since we are sending one right away. 16405 mPendingBroadcasts.remove(userId, packageName); 16406 } else { 16407 if (newPackage) { 16408 mPendingBroadcasts.put(userId, packageName, components); 16409 } 16410 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 16411 // Schedule a message 16412 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 16413 } 16414 } 16415 } 16416 16417 long callingId = Binder.clearCallingIdentity(); 16418 try { 16419 if (sendNow) { 16420 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 16421 sendPackageChangedBroadcast(packageName, 16422 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 16423 } 16424 } finally { 16425 Binder.restoreCallingIdentity(callingId); 16426 } 16427 } 16428 16429 private void sendPackageChangedBroadcast(String packageName, 16430 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 16431 if (DEBUG_INSTALL) 16432 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 16433 + componentNames); 16434 Bundle extras = new Bundle(4); 16435 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 16436 String nameList[] = new String[componentNames.size()]; 16437 componentNames.toArray(nameList); 16438 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 16439 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 16440 extras.putInt(Intent.EXTRA_UID, packageUid); 16441 // If this is not reporting a change of the overall package, then only send it 16442 // to registered receivers. We don't want to launch a swath of apps for every 16443 // little component state change. 16444 final int flags = !componentNames.contains(packageName) 16445 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 16446 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 16447 new int[] {UserHandle.getUserId(packageUid)}); 16448 } 16449 16450 @Override 16451 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 16452 if (!sUserManager.exists(userId)) return; 16453 final int uid = Binder.getCallingUid(); 16454 final int permission = mContext.checkCallingOrSelfPermission( 16455 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 16456 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 16457 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 16458 // writer 16459 synchronized (mPackages) { 16460 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 16461 allowedByPermission, uid, userId)) { 16462 scheduleWritePackageRestrictionsLocked(userId); 16463 } 16464 } 16465 } 16466 16467 @Override 16468 public String getInstallerPackageName(String packageName) { 16469 // reader 16470 synchronized (mPackages) { 16471 return mSettings.getInstallerPackageNameLPr(packageName); 16472 } 16473 } 16474 16475 @Override 16476 public int getApplicationEnabledSetting(String packageName, int userId) { 16477 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 16478 int uid = Binder.getCallingUid(); 16479 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 16480 // reader 16481 synchronized (mPackages) { 16482 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 16483 } 16484 } 16485 16486 @Override 16487 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 16488 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 16489 int uid = Binder.getCallingUid(); 16490 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 16491 // reader 16492 synchronized (mPackages) { 16493 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 16494 } 16495 } 16496 16497 @Override 16498 public void enterSafeMode() { 16499 enforceSystemOrRoot("Only the system can request entering safe mode"); 16500 16501 if (!mSystemReady) { 16502 mSafeMode = true; 16503 } 16504 } 16505 16506 @Override 16507 public void systemReady() { 16508 mSystemReady = true; 16509 16510 // Read the compatibilty setting when the system is ready. 16511 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 16512 mContext.getContentResolver(), 16513 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 16514 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 16515 if (DEBUG_SETTINGS) { 16516 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 16517 } 16518 16519 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 16520 16521 synchronized (mPackages) { 16522 // Verify that all of the preferred activity components actually 16523 // exist. It is possible for applications to be updated and at 16524 // that point remove a previously declared activity component that 16525 // had been set as a preferred activity. We try to clean this up 16526 // the next time we encounter that preferred activity, but it is 16527 // possible for the user flow to never be able to return to that 16528 // situation so here we do a sanity check to make sure we haven't 16529 // left any junk around. 16530 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 16531 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16532 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16533 removed.clear(); 16534 for (PreferredActivity pa : pir.filterSet()) { 16535 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 16536 removed.add(pa); 16537 } 16538 } 16539 if (removed.size() > 0) { 16540 for (int r=0; r<removed.size(); r++) { 16541 PreferredActivity pa = removed.get(r); 16542 Slog.w(TAG, "Removing dangling preferred activity: " 16543 + pa.mPref.mComponent); 16544 pir.removeFilter(pa); 16545 } 16546 mSettings.writePackageRestrictionsLPr( 16547 mSettings.mPreferredActivities.keyAt(i)); 16548 } 16549 } 16550 16551 for (int userId : UserManagerService.getInstance().getUserIds()) { 16552 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 16553 grantPermissionsUserIds = ArrayUtils.appendInt( 16554 grantPermissionsUserIds, userId); 16555 } 16556 } 16557 } 16558 sUserManager.systemReady(); 16559 16560 // If we upgraded grant all default permissions before kicking off. 16561 for (int userId : grantPermissionsUserIds) { 16562 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 16563 } 16564 16565 // Kick off any messages waiting for system ready 16566 if (mPostSystemReadyMessages != null) { 16567 for (Message msg : mPostSystemReadyMessages) { 16568 msg.sendToTarget(); 16569 } 16570 mPostSystemReadyMessages = null; 16571 } 16572 16573 // Watch for external volumes that come and go over time 16574 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16575 storage.registerListener(mStorageListener); 16576 16577 mInstallerService.systemReady(); 16578 mPackageDexOptimizer.systemReady(); 16579 16580 MountServiceInternal mountServiceInternal = LocalServices.getService( 16581 MountServiceInternal.class); 16582 mountServiceInternal.addExternalStoragePolicy( 16583 new MountServiceInternal.ExternalStorageMountPolicy() { 16584 @Override 16585 public int getMountMode(int uid, String packageName) { 16586 if (Process.isIsolated(uid)) { 16587 return Zygote.MOUNT_EXTERNAL_NONE; 16588 } 16589 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 16590 return Zygote.MOUNT_EXTERNAL_DEFAULT; 16591 } 16592 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 16593 return Zygote.MOUNT_EXTERNAL_DEFAULT; 16594 } 16595 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 16596 return Zygote.MOUNT_EXTERNAL_READ; 16597 } 16598 return Zygote.MOUNT_EXTERNAL_WRITE; 16599 } 16600 16601 @Override 16602 public boolean hasExternalStorage(int uid, String packageName) { 16603 return true; 16604 } 16605 }); 16606 } 16607 16608 @Override 16609 public boolean isSafeMode() { 16610 return mSafeMode; 16611 } 16612 16613 @Override 16614 public boolean hasSystemUidErrors() { 16615 return mHasSystemUidErrors; 16616 } 16617 16618 static String arrayToString(int[] array) { 16619 StringBuffer buf = new StringBuffer(128); 16620 buf.append('['); 16621 if (array != null) { 16622 for (int i=0; i<array.length; i++) { 16623 if (i > 0) buf.append(", "); 16624 buf.append(array[i]); 16625 } 16626 } 16627 buf.append(']'); 16628 return buf.toString(); 16629 } 16630 16631 static class DumpState { 16632 public static final int DUMP_LIBS = 1 << 0; 16633 public static final int DUMP_FEATURES = 1 << 1; 16634 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 16635 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 16636 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 16637 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 16638 public static final int DUMP_PERMISSIONS = 1 << 6; 16639 public static final int DUMP_PACKAGES = 1 << 7; 16640 public static final int DUMP_SHARED_USERS = 1 << 8; 16641 public static final int DUMP_MESSAGES = 1 << 9; 16642 public static final int DUMP_PROVIDERS = 1 << 10; 16643 public static final int DUMP_VERIFIERS = 1 << 11; 16644 public static final int DUMP_PREFERRED = 1 << 12; 16645 public static final int DUMP_PREFERRED_XML = 1 << 13; 16646 public static final int DUMP_KEYSETS = 1 << 14; 16647 public static final int DUMP_VERSION = 1 << 15; 16648 public static final int DUMP_INSTALLS = 1 << 16; 16649 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 16650 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 16651 16652 public static final int OPTION_SHOW_FILTERS = 1 << 0; 16653 16654 private int mTypes; 16655 16656 private int mOptions; 16657 16658 private boolean mTitlePrinted; 16659 16660 private SharedUserSetting mSharedUser; 16661 16662 public boolean isDumping(int type) { 16663 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 16664 return true; 16665 } 16666 16667 return (mTypes & type) != 0; 16668 } 16669 16670 public void setDump(int type) { 16671 mTypes |= type; 16672 } 16673 16674 public boolean isOptionEnabled(int option) { 16675 return (mOptions & option) != 0; 16676 } 16677 16678 public void setOptionEnabled(int option) { 16679 mOptions |= option; 16680 } 16681 16682 public boolean onTitlePrinted() { 16683 final boolean printed = mTitlePrinted; 16684 mTitlePrinted = true; 16685 return printed; 16686 } 16687 16688 public boolean getTitlePrinted() { 16689 return mTitlePrinted; 16690 } 16691 16692 public void setTitlePrinted(boolean enabled) { 16693 mTitlePrinted = enabled; 16694 } 16695 16696 public SharedUserSetting getSharedUser() { 16697 return mSharedUser; 16698 } 16699 16700 public void setSharedUser(SharedUserSetting user) { 16701 mSharedUser = user; 16702 } 16703 } 16704 16705 @Override 16706 public void onShellCommand(FileDescriptor in, FileDescriptor out, 16707 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 16708 (new PackageManagerShellCommand(this)).exec( 16709 this, in, out, err, args, resultReceiver); 16710 } 16711 16712 @Override 16713 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 16714 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 16715 != PackageManager.PERMISSION_GRANTED) { 16716 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 16717 + Binder.getCallingPid() 16718 + ", uid=" + Binder.getCallingUid() 16719 + " without permission " 16720 + android.Manifest.permission.DUMP); 16721 return; 16722 } 16723 16724 DumpState dumpState = new DumpState(); 16725 boolean fullPreferred = false; 16726 boolean checkin = false; 16727 16728 String packageName = null; 16729 ArraySet<String> permissionNames = null; 16730 16731 int opti = 0; 16732 while (opti < args.length) { 16733 String opt = args[opti]; 16734 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 16735 break; 16736 } 16737 opti++; 16738 16739 if ("-a".equals(opt)) { 16740 // Right now we only know how to print all. 16741 } else if ("-h".equals(opt)) { 16742 pw.println("Package manager dump options:"); 16743 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 16744 pw.println(" --checkin: dump for a checkin"); 16745 pw.println(" -f: print details of intent filters"); 16746 pw.println(" -h: print this help"); 16747 pw.println(" cmd may be one of:"); 16748 pw.println(" l[ibraries]: list known shared libraries"); 16749 pw.println(" f[eatures]: list device features"); 16750 pw.println(" k[eysets]: print known keysets"); 16751 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 16752 pw.println(" perm[issions]: dump permissions"); 16753 pw.println(" permission [name ...]: dump declaration and use of given permission"); 16754 pw.println(" pref[erred]: print preferred package settings"); 16755 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 16756 pw.println(" prov[iders]: dump content providers"); 16757 pw.println(" p[ackages]: dump installed packages"); 16758 pw.println(" s[hared-users]: dump shared user IDs"); 16759 pw.println(" m[essages]: print collected runtime messages"); 16760 pw.println(" v[erifiers]: print package verifier info"); 16761 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 16762 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 16763 pw.println(" version: print database version info"); 16764 pw.println(" write: write current settings now"); 16765 pw.println(" installs: details about install sessions"); 16766 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 16767 pw.println(" <package.name>: info about given package"); 16768 return; 16769 } else if ("--checkin".equals(opt)) { 16770 checkin = true; 16771 } else if ("-f".equals(opt)) { 16772 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 16773 } else { 16774 pw.println("Unknown argument: " + opt + "; use -h for help"); 16775 } 16776 } 16777 16778 // Is the caller requesting to dump a particular piece of data? 16779 if (opti < args.length) { 16780 String cmd = args[opti]; 16781 opti++; 16782 // Is this a package name? 16783 if ("android".equals(cmd) || cmd.contains(".")) { 16784 packageName = cmd; 16785 // When dumping a single package, we always dump all of its 16786 // filter information since the amount of data will be reasonable. 16787 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 16788 } else if ("check-permission".equals(cmd)) { 16789 if (opti >= args.length) { 16790 pw.println("Error: check-permission missing permission argument"); 16791 return; 16792 } 16793 String perm = args[opti]; 16794 opti++; 16795 if (opti >= args.length) { 16796 pw.println("Error: check-permission missing package argument"); 16797 return; 16798 } 16799 String pkg = args[opti]; 16800 opti++; 16801 int user = UserHandle.getUserId(Binder.getCallingUid()); 16802 if (opti < args.length) { 16803 try { 16804 user = Integer.parseInt(args[opti]); 16805 } catch (NumberFormatException e) { 16806 pw.println("Error: check-permission user argument is not a number: " 16807 + args[opti]); 16808 return; 16809 } 16810 } 16811 pw.println(checkPermission(perm, pkg, user)); 16812 return; 16813 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 16814 dumpState.setDump(DumpState.DUMP_LIBS); 16815 } else if ("f".equals(cmd) || "features".equals(cmd)) { 16816 dumpState.setDump(DumpState.DUMP_FEATURES); 16817 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 16818 if (opti >= args.length) { 16819 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 16820 | DumpState.DUMP_SERVICE_RESOLVERS 16821 | DumpState.DUMP_RECEIVER_RESOLVERS 16822 | DumpState.DUMP_CONTENT_RESOLVERS); 16823 } else { 16824 while (opti < args.length) { 16825 String name = args[opti]; 16826 if ("a".equals(name) || "activity".equals(name)) { 16827 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 16828 } else if ("s".equals(name) || "service".equals(name)) { 16829 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 16830 } else if ("r".equals(name) || "receiver".equals(name)) { 16831 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 16832 } else if ("c".equals(name) || "content".equals(name)) { 16833 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 16834 } else { 16835 pw.println("Error: unknown resolver table type: " + name); 16836 return; 16837 } 16838 opti++; 16839 } 16840 } 16841 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 16842 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 16843 } else if ("permission".equals(cmd)) { 16844 if (opti >= args.length) { 16845 pw.println("Error: permission requires permission name"); 16846 return; 16847 } 16848 permissionNames = new ArraySet<>(); 16849 while (opti < args.length) { 16850 permissionNames.add(args[opti]); 16851 opti++; 16852 } 16853 dumpState.setDump(DumpState.DUMP_PERMISSIONS 16854 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 16855 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 16856 dumpState.setDump(DumpState.DUMP_PREFERRED); 16857 } else if ("preferred-xml".equals(cmd)) { 16858 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 16859 if (opti < args.length && "--full".equals(args[opti])) { 16860 fullPreferred = true; 16861 opti++; 16862 } 16863 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 16864 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 16865 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 16866 dumpState.setDump(DumpState.DUMP_PACKAGES); 16867 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 16868 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 16869 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 16870 dumpState.setDump(DumpState.DUMP_PROVIDERS); 16871 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 16872 dumpState.setDump(DumpState.DUMP_MESSAGES); 16873 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 16874 dumpState.setDump(DumpState.DUMP_VERIFIERS); 16875 } else if ("i".equals(cmd) || "ifv".equals(cmd) 16876 || "intent-filter-verifiers".equals(cmd)) { 16877 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 16878 } else if ("version".equals(cmd)) { 16879 dumpState.setDump(DumpState.DUMP_VERSION); 16880 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 16881 dumpState.setDump(DumpState.DUMP_KEYSETS); 16882 } else if ("installs".equals(cmd)) { 16883 dumpState.setDump(DumpState.DUMP_INSTALLS); 16884 } else if ("write".equals(cmd)) { 16885 synchronized (mPackages) { 16886 mSettings.writeLPr(); 16887 pw.println("Settings written."); 16888 return; 16889 } 16890 } 16891 } 16892 16893 if (checkin) { 16894 pw.println("vers,1"); 16895 } 16896 16897 // reader 16898 synchronized (mPackages) { 16899 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 16900 if (!checkin) { 16901 if (dumpState.onTitlePrinted()) 16902 pw.println(); 16903 pw.println("Database versions:"); 16904 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 16905 } 16906 } 16907 16908 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 16909 if (!checkin) { 16910 if (dumpState.onTitlePrinted()) 16911 pw.println(); 16912 pw.println("Verifiers:"); 16913 pw.print(" Required: "); 16914 pw.print(mRequiredVerifierPackage); 16915 pw.print(" (uid="); 16916 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 16917 UserHandle.USER_SYSTEM)); 16918 pw.println(")"); 16919 } else if (mRequiredVerifierPackage != null) { 16920 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 16921 pw.print(","); 16922 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 16923 UserHandle.USER_SYSTEM)); 16924 } 16925 } 16926 16927 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 16928 packageName == null) { 16929 if (mIntentFilterVerifierComponent != null) { 16930 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 16931 if (!checkin) { 16932 if (dumpState.onTitlePrinted()) 16933 pw.println(); 16934 pw.println("Intent Filter Verifier:"); 16935 pw.print(" Using: "); 16936 pw.print(verifierPackageName); 16937 pw.print(" (uid="); 16938 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 16939 UserHandle.USER_SYSTEM)); 16940 pw.println(")"); 16941 } else if (verifierPackageName != null) { 16942 pw.print("ifv,"); pw.print(verifierPackageName); 16943 pw.print(","); 16944 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 16945 UserHandle.USER_SYSTEM)); 16946 } 16947 } else { 16948 pw.println(); 16949 pw.println("No Intent Filter Verifier available!"); 16950 } 16951 } 16952 16953 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 16954 boolean printedHeader = false; 16955 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 16956 while (it.hasNext()) { 16957 String name = it.next(); 16958 SharedLibraryEntry ent = mSharedLibraries.get(name); 16959 if (!checkin) { 16960 if (!printedHeader) { 16961 if (dumpState.onTitlePrinted()) 16962 pw.println(); 16963 pw.println("Libraries:"); 16964 printedHeader = true; 16965 } 16966 pw.print(" "); 16967 } else { 16968 pw.print("lib,"); 16969 } 16970 pw.print(name); 16971 if (!checkin) { 16972 pw.print(" -> "); 16973 } 16974 if (ent.path != null) { 16975 if (!checkin) { 16976 pw.print("(jar) "); 16977 pw.print(ent.path); 16978 } else { 16979 pw.print(",jar,"); 16980 pw.print(ent.path); 16981 } 16982 } else { 16983 if (!checkin) { 16984 pw.print("(apk) "); 16985 pw.print(ent.apk); 16986 } else { 16987 pw.print(",apk,"); 16988 pw.print(ent.apk); 16989 } 16990 } 16991 pw.println(); 16992 } 16993 } 16994 16995 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 16996 if (dumpState.onTitlePrinted()) 16997 pw.println(); 16998 if (!checkin) { 16999 pw.println("Features:"); 17000 } 17001 17002 for (FeatureInfo feat : mAvailableFeatures.values()) { 17003 if (checkin) { 17004 pw.print("feat,"); 17005 pw.print(feat.name); 17006 pw.print(","); 17007 pw.println(feat.version); 17008 } else { 17009 pw.print(" "); 17010 pw.print(feat.name); 17011 if (feat.version > 0) { 17012 pw.print(" version="); 17013 pw.print(feat.version); 17014 } 17015 pw.println(); 17016 } 17017 } 17018 } 17019 17020 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 17021 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 17022 : "Activity Resolver Table:", " ", packageName, 17023 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17024 dumpState.setTitlePrinted(true); 17025 } 17026 } 17027 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 17028 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 17029 : "Receiver Resolver Table:", " ", packageName, 17030 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17031 dumpState.setTitlePrinted(true); 17032 } 17033 } 17034 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 17035 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 17036 : "Service Resolver Table:", " ", packageName, 17037 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17038 dumpState.setTitlePrinted(true); 17039 } 17040 } 17041 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 17042 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 17043 : "Provider Resolver Table:", " ", packageName, 17044 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17045 dumpState.setTitlePrinted(true); 17046 } 17047 } 17048 17049 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 17050 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17051 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17052 int user = mSettings.mPreferredActivities.keyAt(i); 17053 if (pir.dump(pw, 17054 dumpState.getTitlePrinted() 17055 ? "\nPreferred Activities User " + user + ":" 17056 : "Preferred Activities User " + user + ":", " ", 17057 packageName, true, false)) { 17058 dumpState.setTitlePrinted(true); 17059 } 17060 } 17061 } 17062 17063 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 17064 pw.flush(); 17065 FileOutputStream fout = new FileOutputStream(fd); 17066 BufferedOutputStream str = new BufferedOutputStream(fout); 17067 XmlSerializer serializer = new FastXmlSerializer(); 17068 try { 17069 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 17070 serializer.startDocument(null, true); 17071 serializer.setFeature( 17072 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 17073 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 17074 serializer.endDocument(); 17075 serializer.flush(); 17076 } catch (IllegalArgumentException e) { 17077 pw.println("Failed writing: " + e); 17078 } catch (IllegalStateException e) { 17079 pw.println("Failed writing: " + e); 17080 } catch (IOException e) { 17081 pw.println("Failed writing: " + e); 17082 } 17083 } 17084 17085 if (!checkin 17086 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 17087 && packageName == null) { 17088 pw.println(); 17089 int count = mSettings.mPackages.size(); 17090 if (count == 0) { 17091 pw.println("No applications!"); 17092 pw.println(); 17093 } else { 17094 final String prefix = " "; 17095 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 17096 if (allPackageSettings.size() == 0) { 17097 pw.println("No domain preferred apps!"); 17098 pw.println(); 17099 } else { 17100 pw.println("App verification status:"); 17101 pw.println(); 17102 count = 0; 17103 for (PackageSetting ps : allPackageSettings) { 17104 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 17105 if (ivi == null || ivi.getPackageName() == null) continue; 17106 pw.println(prefix + "Package: " + ivi.getPackageName()); 17107 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 17108 pw.println(prefix + "Status: " + ivi.getStatusString()); 17109 pw.println(); 17110 count++; 17111 } 17112 if (count == 0) { 17113 pw.println(prefix + "No app verification established."); 17114 pw.println(); 17115 } 17116 for (int userId : sUserManager.getUserIds()) { 17117 pw.println("App linkages for user " + userId + ":"); 17118 pw.println(); 17119 count = 0; 17120 for (PackageSetting ps : allPackageSettings) { 17121 final long status = ps.getDomainVerificationStatusForUser(userId); 17122 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 17123 continue; 17124 } 17125 pw.println(prefix + "Package: " + ps.name); 17126 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 17127 String statusStr = IntentFilterVerificationInfo. 17128 getStatusStringFromValue(status); 17129 pw.println(prefix + "Status: " + statusStr); 17130 pw.println(); 17131 count++; 17132 } 17133 if (count == 0) { 17134 pw.println(prefix + "No configured app linkages."); 17135 pw.println(); 17136 } 17137 } 17138 } 17139 } 17140 } 17141 17142 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 17143 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 17144 if (packageName == null && permissionNames == null) { 17145 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 17146 if (iperm == 0) { 17147 if (dumpState.onTitlePrinted()) 17148 pw.println(); 17149 pw.println("AppOp Permissions:"); 17150 } 17151 pw.print(" AppOp Permission "); 17152 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 17153 pw.println(":"); 17154 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 17155 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 17156 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 17157 } 17158 } 17159 } 17160 } 17161 17162 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 17163 boolean printedSomething = false; 17164 for (PackageParser.Provider p : mProviders.mProviders.values()) { 17165 if (packageName != null && !packageName.equals(p.info.packageName)) { 17166 continue; 17167 } 17168 if (!printedSomething) { 17169 if (dumpState.onTitlePrinted()) 17170 pw.println(); 17171 pw.println("Registered ContentProviders:"); 17172 printedSomething = true; 17173 } 17174 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 17175 pw.print(" "); pw.println(p.toString()); 17176 } 17177 printedSomething = false; 17178 for (Map.Entry<String, PackageParser.Provider> entry : 17179 mProvidersByAuthority.entrySet()) { 17180 PackageParser.Provider p = entry.getValue(); 17181 if (packageName != null && !packageName.equals(p.info.packageName)) { 17182 continue; 17183 } 17184 if (!printedSomething) { 17185 if (dumpState.onTitlePrinted()) 17186 pw.println(); 17187 pw.println("ContentProvider Authorities:"); 17188 printedSomething = true; 17189 } 17190 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 17191 pw.print(" "); pw.println(p.toString()); 17192 if (p.info != null && p.info.applicationInfo != null) { 17193 final String appInfo = p.info.applicationInfo.toString(); 17194 pw.print(" applicationInfo="); pw.println(appInfo); 17195 } 17196 } 17197 } 17198 17199 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 17200 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 17201 } 17202 17203 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 17204 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 17205 } 17206 17207 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 17208 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 17209 } 17210 17211 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 17212 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 17213 } 17214 17215 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 17216 // XXX should handle packageName != null by dumping only install data that 17217 // the given package is involved with. 17218 if (dumpState.onTitlePrinted()) pw.println(); 17219 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 17220 } 17221 17222 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 17223 if (dumpState.onTitlePrinted()) pw.println(); 17224 mSettings.dumpReadMessagesLPr(pw, dumpState); 17225 17226 pw.println(); 17227 pw.println("Package warning messages:"); 17228 BufferedReader in = null; 17229 String line = null; 17230 try { 17231 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 17232 while ((line = in.readLine()) != null) { 17233 if (line.contains("ignored: updated version")) continue; 17234 pw.println(line); 17235 } 17236 } catch (IOException ignored) { 17237 } finally { 17238 IoUtils.closeQuietly(in); 17239 } 17240 } 17241 17242 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 17243 BufferedReader in = null; 17244 String line = null; 17245 try { 17246 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 17247 while ((line = in.readLine()) != null) { 17248 if (line.contains("ignored: updated version")) continue; 17249 pw.print("msg,"); 17250 pw.println(line); 17251 } 17252 } catch (IOException ignored) { 17253 } finally { 17254 IoUtils.closeQuietly(in); 17255 } 17256 } 17257 } 17258 } 17259 17260 private String dumpDomainString(String packageName) { 17261 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 17262 List<IntentFilter> filters = getAllIntentFilters(packageName); 17263 17264 ArraySet<String> result = new ArraySet<>(); 17265 if (iviList.size() > 0) { 17266 for (IntentFilterVerificationInfo ivi : iviList) { 17267 for (String host : ivi.getDomains()) { 17268 result.add(host); 17269 } 17270 } 17271 } 17272 if (filters != null && filters.size() > 0) { 17273 for (IntentFilter filter : filters) { 17274 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 17275 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 17276 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 17277 result.addAll(filter.getHostsList()); 17278 } 17279 } 17280 } 17281 17282 StringBuilder sb = new StringBuilder(result.size() * 16); 17283 for (String domain : result) { 17284 if (sb.length() > 0) sb.append(" "); 17285 sb.append(domain); 17286 } 17287 return sb.toString(); 17288 } 17289 17290 // ------- apps on sdcard specific code ------- 17291 static final boolean DEBUG_SD_INSTALL = false; 17292 17293 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 17294 17295 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 17296 17297 private boolean mMediaMounted = false; 17298 17299 static String getEncryptKey() { 17300 try { 17301 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 17302 SD_ENCRYPTION_KEYSTORE_NAME); 17303 if (sdEncKey == null) { 17304 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 17305 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 17306 if (sdEncKey == null) { 17307 Slog.e(TAG, "Failed to create encryption keys"); 17308 return null; 17309 } 17310 } 17311 return sdEncKey; 17312 } catch (NoSuchAlgorithmException nsae) { 17313 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 17314 return null; 17315 } catch (IOException ioe) { 17316 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 17317 return null; 17318 } 17319 } 17320 17321 /* 17322 * Update media status on PackageManager. 17323 */ 17324 @Override 17325 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 17326 int callingUid = Binder.getCallingUid(); 17327 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 17328 throw new SecurityException("Media status can only be updated by the system"); 17329 } 17330 // reader; this apparently protects mMediaMounted, but should probably 17331 // be a different lock in that case. 17332 synchronized (mPackages) { 17333 Log.i(TAG, "Updating external media status from " 17334 + (mMediaMounted ? "mounted" : "unmounted") + " to " 17335 + (mediaStatus ? "mounted" : "unmounted")); 17336 if (DEBUG_SD_INSTALL) 17337 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 17338 + ", mMediaMounted=" + mMediaMounted); 17339 if (mediaStatus == mMediaMounted) { 17340 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 17341 : 0, -1); 17342 mHandler.sendMessage(msg); 17343 return; 17344 } 17345 mMediaMounted = mediaStatus; 17346 } 17347 // Queue up an async operation since the package installation may take a 17348 // little while. 17349 mHandler.post(new Runnable() { 17350 public void run() { 17351 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 17352 } 17353 }); 17354 } 17355 17356 /** 17357 * Called by MountService when the initial ASECs to scan are available. 17358 * Should block until all the ASEC containers are finished being scanned. 17359 */ 17360 public void scanAvailableAsecs() { 17361 updateExternalMediaStatusInner(true, false, false); 17362 } 17363 17364 /* 17365 * Collect information of applications on external media, map them against 17366 * existing containers and update information based on current mount status. 17367 * Please note that we always have to report status if reportStatus has been 17368 * set to true especially when unloading packages. 17369 */ 17370 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 17371 boolean externalStorage) { 17372 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 17373 int[] uidArr = EmptyArray.INT; 17374 17375 final String[] list = PackageHelper.getSecureContainerList(); 17376 if (ArrayUtils.isEmpty(list)) { 17377 Log.i(TAG, "No secure containers found"); 17378 } else { 17379 // Process list of secure containers and categorize them 17380 // as active or stale based on their package internal state. 17381 17382 // reader 17383 synchronized (mPackages) { 17384 for (String cid : list) { 17385 // Leave stages untouched for now; installer service owns them 17386 if (PackageInstallerService.isStageName(cid)) continue; 17387 17388 if (DEBUG_SD_INSTALL) 17389 Log.i(TAG, "Processing container " + cid); 17390 String pkgName = getAsecPackageName(cid); 17391 if (pkgName == null) { 17392 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 17393 continue; 17394 } 17395 if (DEBUG_SD_INSTALL) 17396 Log.i(TAG, "Looking for pkg : " + pkgName); 17397 17398 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17399 if (ps == null) { 17400 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 17401 continue; 17402 } 17403 17404 /* 17405 * Skip packages that are not external if we're unmounting 17406 * external storage. 17407 */ 17408 if (externalStorage && !isMounted && !isExternal(ps)) { 17409 continue; 17410 } 17411 17412 final AsecInstallArgs args = new AsecInstallArgs(cid, 17413 getAppDexInstructionSets(ps), ps.isForwardLocked()); 17414 // The package status is changed only if the code path 17415 // matches between settings and the container id. 17416 if (ps.codePathString != null 17417 && ps.codePathString.startsWith(args.getCodePath())) { 17418 if (DEBUG_SD_INSTALL) { 17419 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 17420 + " at code path: " + ps.codePathString); 17421 } 17422 17423 // We do have a valid package installed on sdcard 17424 processCids.put(args, ps.codePathString); 17425 final int uid = ps.appId; 17426 if (uid != -1) { 17427 uidArr = ArrayUtils.appendInt(uidArr, uid); 17428 } 17429 } else { 17430 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 17431 + ps.codePathString); 17432 } 17433 } 17434 } 17435 17436 Arrays.sort(uidArr); 17437 } 17438 17439 // Process packages with valid entries. 17440 if (isMounted) { 17441 if (DEBUG_SD_INSTALL) 17442 Log.i(TAG, "Loading packages"); 17443 loadMediaPackages(processCids, uidArr, externalStorage); 17444 startCleaningPackages(); 17445 mInstallerService.onSecureContainersAvailable(); 17446 } else { 17447 if (DEBUG_SD_INSTALL) 17448 Log.i(TAG, "Unloading packages"); 17449 unloadMediaPackages(processCids, uidArr, reportStatus); 17450 } 17451 } 17452 17453 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17454 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 17455 final int size = infos.size(); 17456 final String[] packageNames = new String[size]; 17457 final int[] packageUids = new int[size]; 17458 for (int i = 0; i < size; i++) { 17459 final ApplicationInfo info = infos.get(i); 17460 packageNames[i] = info.packageName; 17461 packageUids[i] = info.uid; 17462 } 17463 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 17464 finishedReceiver); 17465 } 17466 17467 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17468 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 17469 sendResourcesChangedBroadcast(mediaStatus, replacing, 17470 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 17471 } 17472 17473 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17474 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 17475 int size = pkgList.length; 17476 if (size > 0) { 17477 // Send broadcasts here 17478 Bundle extras = new Bundle(); 17479 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 17480 if (uidArr != null) { 17481 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 17482 } 17483 if (replacing) { 17484 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 17485 } 17486 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 17487 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 17488 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 17489 } 17490 } 17491 17492 /* 17493 * Look at potentially valid container ids from processCids If package 17494 * information doesn't match the one on record or package scanning fails, 17495 * the cid is added to list of removeCids. We currently don't delete stale 17496 * containers. 17497 */ 17498 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 17499 boolean externalStorage) { 17500 ArrayList<String> pkgList = new ArrayList<String>(); 17501 Set<AsecInstallArgs> keys = processCids.keySet(); 17502 17503 for (AsecInstallArgs args : keys) { 17504 String codePath = processCids.get(args); 17505 if (DEBUG_SD_INSTALL) 17506 Log.i(TAG, "Loading container : " + args.cid); 17507 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 17508 try { 17509 // Make sure there are no container errors first. 17510 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 17511 Slog.e(TAG, "Failed to mount cid : " + args.cid 17512 + " when installing from sdcard"); 17513 continue; 17514 } 17515 // Check code path here. 17516 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 17517 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 17518 + " does not match one in settings " + codePath); 17519 continue; 17520 } 17521 // Parse package 17522 int parseFlags = mDefParseFlags; 17523 if (args.isExternalAsec()) { 17524 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 17525 } 17526 if (args.isFwdLocked()) { 17527 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 17528 } 17529 17530 synchronized (mInstallLock) { 17531 PackageParser.Package pkg = null; 17532 try { 17533 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 17534 } catch (PackageManagerException e) { 17535 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 17536 } 17537 // Scan the package 17538 if (pkg != null) { 17539 /* 17540 * TODO why is the lock being held? doPostInstall is 17541 * called in other places without the lock. This needs 17542 * to be straightened out. 17543 */ 17544 // writer 17545 synchronized (mPackages) { 17546 retCode = PackageManager.INSTALL_SUCCEEDED; 17547 pkgList.add(pkg.packageName); 17548 // Post process args 17549 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 17550 pkg.applicationInfo.uid); 17551 } 17552 } else { 17553 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 17554 } 17555 } 17556 17557 } finally { 17558 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 17559 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 17560 } 17561 } 17562 } 17563 // writer 17564 synchronized (mPackages) { 17565 // If the platform SDK has changed since the last time we booted, 17566 // we need to re-grant app permission to catch any new ones that 17567 // appear. This is really a hack, and means that apps can in some 17568 // cases get permissions that the user didn't initially explicitly 17569 // allow... it would be nice to have some better way to handle 17570 // this situation. 17571 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 17572 : mSettings.getInternalVersion(); 17573 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 17574 : StorageManager.UUID_PRIVATE_INTERNAL; 17575 17576 int updateFlags = UPDATE_PERMISSIONS_ALL; 17577 if (ver.sdkVersion != mSdkVersion) { 17578 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 17579 + mSdkVersion + "; regranting permissions for external"); 17580 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 17581 } 17582 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 17583 17584 // Yay, everything is now upgraded 17585 ver.forceCurrent(); 17586 17587 // can downgrade to reader 17588 // Persist settings 17589 mSettings.writeLPr(); 17590 } 17591 // Send a broadcast to let everyone know we are done processing 17592 if (pkgList.size() > 0) { 17593 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 17594 } 17595 } 17596 17597 /* 17598 * Utility method to unload a list of specified containers 17599 */ 17600 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 17601 // Just unmount all valid containers. 17602 for (AsecInstallArgs arg : cidArgs) { 17603 synchronized (mInstallLock) { 17604 arg.doPostDeleteLI(false); 17605 } 17606 } 17607 } 17608 17609 /* 17610 * Unload packages mounted on external media. This involves deleting package 17611 * data from internal structures, sending broadcasts about disabled packages, 17612 * gc'ing to free up references, unmounting all secure containers 17613 * corresponding to packages on external media, and posting a 17614 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 17615 * that we always have to post this message if status has been requested no 17616 * matter what. 17617 */ 17618 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 17619 final boolean reportStatus) { 17620 if (DEBUG_SD_INSTALL) 17621 Log.i(TAG, "unloading media packages"); 17622 ArrayList<String> pkgList = new ArrayList<String>(); 17623 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 17624 final Set<AsecInstallArgs> keys = processCids.keySet(); 17625 for (AsecInstallArgs args : keys) { 17626 String pkgName = args.getPackageName(); 17627 if (DEBUG_SD_INSTALL) 17628 Log.i(TAG, "Trying to unload pkg : " + pkgName); 17629 // Delete package internally 17630 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 17631 synchronized (mInstallLock) { 17632 boolean res = deletePackageLI(pkgName, null, false, null, 17633 PackageManager.DELETE_KEEP_DATA, outInfo, false, null); 17634 if (res) { 17635 pkgList.add(pkgName); 17636 } else { 17637 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 17638 failedList.add(args); 17639 } 17640 } 17641 } 17642 17643 // reader 17644 synchronized (mPackages) { 17645 // We didn't update the settings after removing each package; 17646 // write them now for all packages. 17647 mSettings.writeLPr(); 17648 } 17649 17650 // We have to absolutely send UPDATED_MEDIA_STATUS only 17651 // after confirming that all the receivers processed the ordered 17652 // broadcast when packages get disabled, force a gc to clean things up. 17653 // and unload all the containers. 17654 if (pkgList.size() > 0) { 17655 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 17656 new IIntentReceiver.Stub() { 17657 public void performReceive(Intent intent, int resultCode, String data, 17658 Bundle extras, boolean ordered, boolean sticky, 17659 int sendingUser) throws RemoteException { 17660 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 17661 reportStatus ? 1 : 0, 1, keys); 17662 mHandler.sendMessage(msg); 17663 } 17664 }); 17665 } else { 17666 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 17667 keys); 17668 mHandler.sendMessage(msg); 17669 } 17670 } 17671 17672 private void loadPrivatePackages(final VolumeInfo vol) { 17673 mHandler.post(new Runnable() { 17674 @Override 17675 public void run() { 17676 loadPrivatePackagesInner(vol); 17677 } 17678 }); 17679 } 17680 17681 private void loadPrivatePackagesInner(VolumeInfo vol) { 17682 final String volumeUuid = vol.fsUuid; 17683 if (TextUtils.isEmpty(volumeUuid)) { 17684 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 17685 return; 17686 } 17687 17688 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 17689 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 17690 17691 final VersionInfo ver; 17692 final List<PackageSetting> packages; 17693 synchronized (mPackages) { 17694 ver = mSettings.findOrCreateVersion(volumeUuid); 17695 packages = mSettings.getVolumePackagesLPr(volumeUuid); 17696 } 17697 17698 // TODO: introduce a new concept similar to "frozen" to prevent these 17699 // apps from being launched until after data has been fully reconciled 17700 for (PackageSetting ps : packages) { 17701 synchronized (mInstallLock) { 17702 final PackageParser.Package pkg; 17703 try { 17704 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 17705 loaded.add(pkg.applicationInfo); 17706 17707 } catch (PackageManagerException e) { 17708 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 17709 } 17710 17711 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 17712 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 17713 } 17714 } 17715 } 17716 17717 // Reconcile app data for all started/unlocked users 17718 final StorageManager sm = mContext.getSystemService(StorageManager.class); 17719 final UserManager um = mContext.getSystemService(UserManager.class); 17720 for (UserInfo user : um.getUsers()) { 17721 final int flags; 17722 if (um.isUserUnlocked(user.id)) { 17723 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 17724 } else if (um.isUserRunning(user.id)) { 17725 flags = StorageManager.FLAG_STORAGE_DE; 17726 } else { 17727 continue; 17728 } 17729 17730 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 17731 reconcileAppsData(volumeUuid, user.id, flags); 17732 } 17733 17734 synchronized (mPackages) { 17735 int updateFlags = UPDATE_PERMISSIONS_ALL; 17736 if (ver.sdkVersion != mSdkVersion) { 17737 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 17738 + mSdkVersion + "; regranting permissions for " + volumeUuid); 17739 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 17740 } 17741 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 17742 17743 // Yay, everything is now upgraded 17744 ver.forceCurrent(); 17745 17746 mSettings.writeLPr(); 17747 } 17748 17749 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 17750 sendResourcesChangedBroadcast(true, false, loaded, null); 17751 } 17752 17753 private void unloadPrivatePackages(final VolumeInfo vol) { 17754 mHandler.post(new Runnable() { 17755 @Override 17756 public void run() { 17757 unloadPrivatePackagesInner(vol); 17758 } 17759 }); 17760 } 17761 17762 private void unloadPrivatePackagesInner(VolumeInfo vol) { 17763 final String volumeUuid = vol.fsUuid; 17764 if (TextUtils.isEmpty(volumeUuid)) { 17765 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 17766 return; 17767 } 17768 17769 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 17770 synchronized (mInstallLock) { 17771 synchronized (mPackages) { 17772 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 17773 for (PackageSetting ps : packages) { 17774 if (ps.pkg == null) continue; 17775 17776 final ApplicationInfo info = ps.pkg.applicationInfo; 17777 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 17778 if (deletePackageLI(ps.name, null, false, null, 17779 PackageManager.DELETE_KEEP_DATA, outInfo, false, null)) { 17780 unloaded.add(info); 17781 } else { 17782 Slog.w(TAG, "Failed to unload " + ps.codePath); 17783 } 17784 } 17785 17786 mSettings.writeLPr(); 17787 } 17788 } 17789 17790 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 17791 sendResourcesChangedBroadcast(false, false, unloaded, null); 17792 } 17793 17794 /** 17795 * Examine all users present on given mounted volume, and destroy data 17796 * belonging to users that are no longer valid, or whose user ID has been 17797 * recycled. 17798 */ 17799 private void reconcileUsers(String volumeUuid) { 17800 // TODO: also reconcile DE directories 17801 final File[] files = FileUtils 17802 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)); 17803 for (File file : files) { 17804 if (!file.isDirectory()) continue; 17805 17806 final int userId; 17807 final UserInfo info; 17808 try { 17809 userId = Integer.parseInt(file.getName()); 17810 info = sUserManager.getUserInfo(userId); 17811 } catch (NumberFormatException e) { 17812 Slog.w(TAG, "Invalid user directory " + file); 17813 continue; 17814 } 17815 17816 boolean destroyUser = false; 17817 if (info == null) { 17818 logCriticalInfo(Log.WARN, "Destroying user directory " + file 17819 + " because no matching user was found"); 17820 destroyUser = true; 17821 } else { 17822 try { 17823 UserManagerService.enforceSerialNumber(file, info.serialNumber); 17824 } catch (IOException e) { 17825 logCriticalInfo(Log.WARN, "Destroying user directory " + file 17826 + " because we failed to enforce serial number: " + e); 17827 destroyUser = true; 17828 } 17829 } 17830 17831 if (destroyUser) { 17832 synchronized (mInstallLock) { 17833 try { 17834 mInstaller.removeUserDataDirs(volumeUuid, userId); 17835 } catch (InstallerException e) { 17836 Slog.w(TAG, "Failed to clean up user dirs", e); 17837 } 17838 } 17839 } 17840 } 17841 } 17842 17843 private void assertPackageKnown(String volumeUuid, String packageName) 17844 throws PackageManagerException { 17845 synchronized (mPackages) { 17846 final PackageSetting ps = mSettings.mPackages.get(packageName); 17847 if (ps == null) { 17848 throw new PackageManagerException("Package " + packageName + " is unknown"); 17849 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 17850 throw new PackageManagerException( 17851 "Package " + packageName + " found on unknown volume " + volumeUuid 17852 + "; expected volume " + ps.volumeUuid); 17853 } 17854 } 17855 } 17856 17857 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 17858 throws PackageManagerException { 17859 synchronized (mPackages) { 17860 final PackageSetting ps = mSettings.mPackages.get(packageName); 17861 if (ps == null) { 17862 throw new PackageManagerException("Package " + packageName + " is unknown"); 17863 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 17864 throw new PackageManagerException( 17865 "Package " + packageName + " found on unknown volume " + volumeUuid 17866 + "; expected volume " + ps.volumeUuid); 17867 } else if (!ps.getInstalled(userId)) { 17868 throw new PackageManagerException( 17869 "Package " + packageName + " not installed for user " + userId); 17870 } 17871 } 17872 } 17873 17874 /** 17875 * Examine all apps present on given mounted volume, and destroy apps that 17876 * aren't expected, either due to uninstallation or reinstallation on 17877 * another volume. 17878 */ 17879 private void reconcileApps(String volumeUuid) { 17880 final File[] files = FileUtils 17881 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 17882 for (File file : files) { 17883 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 17884 && !PackageInstallerService.isStageName(file.getName()); 17885 if (!isPackage) { 17886 // Ignore entries which are not packages 17887 continue; 17888 } 17889 17890 try { 17891 final PackageLite pkg = PackageParser.parsePackageLite(file, 17892 PackageParser.PARSE_MUST_BE_APK); 17893 assertPackageKnown(volumeUuid, pkg.packageName); 17894 17895 } catch (PackageParserException | PackageManagerException e) { 17896 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 17897 synchronized (mInstallLock) { 17898 removeCodePathLI(file); 17899 } 17900 } 17901 } 17902 } 17903 17904 /** 17905 * Reconcile all app data for the given user. 17906 * <p> 17907 * Verifies that directories exist and that ownership and labeling is 17908 * correct for all installed apps on all mounted volumes. 17909 */ 17910 void reconcileAppsData(int userId, int flags) { 17911 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17912 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 17913 final String volumeUuid = vol.getFsUuid(); 17914 reconcileAppsData(volumeUuid, userId, flags); 17915 } 17916 } 17917 17918 /** 17919 * Reconcile all app data on given mounted volume. 17920 * <p> 17921 * Destroys app data that isn't expected, either due to uninstallation or 17922 * reinstallation on another volume. 17923 * <p> 17924 * Verifies that directories exist and that ownership and labeling is 17925 * correct for all installed apps. 17926 */ 17927 private void reconcileAppsData(String volumeUuid, int userId, int flags) { 17928 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 17929 + Integer.toHexString(flags)); 17930 17931 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 17932 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 17933 17934 boolean restoreconNeeded = false; 17935 17936 // First look for stale data that doesn't belong, and check if things 17937 // have changed since we did our last restorecon 17938 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 17939 if (!isUserKeyUnlocked(userId)) { 17940 throw new RuntimeException( 17941 "Yikes, someone asked us to reconcile CE storage while " + userId 17942 + " was still locked; this would have caused massive data loss!"); 17943 } 17944 17945 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 17946 17947 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 17948 for (File file : files) { 17949 final String packageName = file.getName(); 17950 try { 17951 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 17952 } catch (PackageManagerException e) { 17953 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 17954 synchronized (mInstallLock) { 17955 destroyAppDataLI(volumeUuid, packageName, userId, 17956 StorageManager.FLAG_STORAGE_CE); 17957 } 17958 } 17959 } 17960 } 17961 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 17962 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 17963 17964 final File[] files = FileUtils.listFilesOrEmpty(deDir); 17965 for (File file : files) { 17966 final String packageName = file.getName(); 17967 try { 17968 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 17969 } catch (PackageManagerException e) { 17970 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 17971 synchronized (mInstallLock) { 17972 destroyAppDataLI(volumeUuid, packageName, userId, 17973 StorageManager.FLAG_STORAGE_DE); 17974 } 17975 } 17976 } 17977 } 17978 17979 // Ensure that data directories are ready to roll for all packages 17980 // installed for this volume and user 17981 final List<PackageSetting> packages; 17982 synchronized (mPackages) { 17983 packages = mSettings.getVolumePackagesLPr(volumeUuid); 17984 } 17985 int preparedCount = 0; 17986 for (PackageSetting ps : packages) { 17987 final String packageName = ps.name; 17988 if (ps.pkg == null) { 17989 Slog.w(TAG, "Odd, missing scanned package " + packageName); 17990 // TODO: might be due to legacy ASEC apps; we should circle back 17991 // and reconcile again once they're scanned 17992 continue; 17993 } 17994 17995 if (ps.getInstalled(userId)) { 17996 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 17997 17998 if (maybeMigrateAppData(volumeUuid, userId, ps.pkg)) { 17999 // We may have just shuffled around app data directories, so 18000 // prepare them one more time 18001 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 18002 } 18003 18004 preparedCount++; 18005 } 18006 } 18007 18008 if (restoreconNeeded) { 18009 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18010 SELinuxMMAC.setRestoreconDone(ceDir); 18011 } 18012 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18013 SELinuxMMAC.setRestoreconDone(deDir); 18014 } 18015 } 18016 18017 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 18018 + " packages; restoreconNeeded was " + restoreconNeeded); 18019 } 18020 18021 /** 18022 * Prepare app data for the given app just after it was installed or 18023 * upgraded. This method carefully only touches users that it's installed 18024 * for, and it forces a restorecon to handle any seinfo changes. 18025 * <p> 18026 * Verifies that directories exist and that ownership and labeling is 18027 * correct for all installed apps. If there is an ownership mismatch, it 18028 * will try recovering system apps by wiping data; third-party app data is 18029 * left intact. 18030 * <p> 18031 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 18032 */ 18033 private void prepareAppDataAfterInstall(PackageParser.Package pkg) { 18034 prepareAppDataAfterInstallInternal(pkg); 18035 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 18036 for (int i = 0; i < childCount; i++) { 18037 PackageParser.Package childPackage = pkg.childPackages.get(i); 18038 prepareAppDataAfterInstallInternal(childPackage); 18039 } 18040 } 18041 18042 private void prepareAppDataAfterInstallInternal(PackageParser.Package pkg) { 18043 final PackageSetting ps; 18044 synchronized (mPackages) { 18045 ps = mSettings.mPackages.get(pkg.packageName); 18046 mSettings.writeKernelMappingLPr(ps); 18047 } 18048 18049 final UserManager um = mContext.getSystemService(UserManager.class); 18050 for (UserInfo user : um.getUsers()) { 18051 final int flags; 18052 if (um.isUserUnlocked(user.id)) { 18053 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18054 } else if (um.isUserRunning(user.id)) { 18055 flags = StorageManager.FLAG_STORAGE_DE; 18056 } else { 18057 continue; 18058 } 18059 18060 if (ps.getInstalled(user.id)) { 18061 // Whenever an app changes, force a restorecon of its data 18062 // TODO: when user data is locked, mark that we're still dirty 18063 prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true); 18064 } 18065 } 18066 } 18067 18068 /** 18069 * Prepare app data for the given app. 18070 * <p> 18071 * Verifies that directories exist and that ownership and labeling is 18072 * correct for all installed apps. If there is an ownership mismatch, this 18073 * will try recovering system apps by wiping data; third-party app data is 18074 * left intact. 18075 */ 18076 private void prepareAppData(String volumeUuid, int userId, int flags, 18077 PackageParser.Package pkg, boolean restoreconNeeded) { 18078 if (DEBUG_APP_DATA) { 18079 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 18080 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 18081 } 18082 18083 final String packageName = pkg.packageName; 18084 final ApplicationInfo app = pkg.applicationInfo; 18085 final int appId = UserHandle.getAppId(app.uid); 18086 18087 Preconditions.checkNotNull(app.seinfo); 18088 18089 synchronized (mInstallLock) { 18090 try { 18091 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18092 appId, app.seinfo, app.targetSdkVersion); 18093 } catch (InstallerException e) { 18094 if (app.isSystemApp()) { 18095 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 18096 + ", but trying to recover: " + e); 18097 destroyAppDataLI(volumeUuid, packageName, userId, flags); 18098 try { 18099 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18100 appId, app.seinfo, app.targetSdkVersion); 18101 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 18102 } catch (InstallerException e2) { 18103 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 18104 } 18105 } else { 18106 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 18107 } 18108 } 18109 18110 if (restoreconNeeded) { 18111 restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo); 18112 } 18113 18114 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18115 // Create a native library symlink only if we have native libraries 18116 // and if the native libraries are 32 bit libraries. We do not provide 18117 // this symlink for 64 bit libraries. 18118 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 18119 final String nativeLibPath = app.nativeLibraryDir; 18120 try { 18121 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 18122 nativeLibPath, userId); 18123 } catch (InstallerException e) { 18124 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 18125 } 18126 } 18127 } 18128 } 18129 } 18130 18131 /** 18132 * For system apps on non-FBE devices, this method migrates any existing 18133 * CE/DE data to match the {@code forceDeviceEncrypted} flag requested by 18134 * the app. 18135 */ 18136 private boolean maybeMigrateAppData(String volumeUuid, int userId, PackageParser.Package pkg) { 18137 if (pkg.isSystemApp() && !StorageManager.isFileBasedEncryptionEnabled() 18138 && PackageManager.APPLY_FORCE_DEVICE_ENCRYPTED) { 18139 final int storageTarget = pkg.applicationInfo.isForceDeviceEncrypted() 18140 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 18141 synchronized (mInstallLock) { 18142 try { 18143 mInstaller.migrateAppData(volumeUuid, pkg.packageName, userId, storageTarget); 18144 } catch (InstallerException e) { 18145 logCriticalInfo(Log.WARN, 18146 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 18147 } 18148 } 18149 return true; 18150 } else { 18151 return false; 18152 } 18153 } 18154 18155 private void unfreezePackage(String packageName) { 18156 synchronized (mPackages) { 18157 final PackageSetting ps = mSettings.mPackages.get(packageName); 18158 if (ps != null) { 18159 ps.frozen = false; 18160 } 18161 } 18162 } 18163 18164 @Override 18165 public int movePackage(final String packageName, final String volumeUuid) { 18166 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 18167 18168 final int moveId = mNextMoveId.getAndIncrement(); 18169 mHandler.post(new Runnable() { 18170 @Override 18171 public void run() { 18172 try { 18173 movePackageInternal(packageName, volumeUuid, moveId); 18174 } catch (PackageManagerException e) { 18175 Slog.w(TAG, "Failed to move " + packageName, e); 18176 mMoveCallbacks.notifyStatusChanged(moveId, 18177 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 18178 } 18179 } 18180 }); 18181 return moveId; 18182 } 18183 18184 private void movePackageInternal(final String packageName, final String volumeUuid, 18185 final int moveId) throws PackageManagerException { 18186 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 18187 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18188 final PackageManager pm = mContext.getPackageManager(); 18189 18190 final boolean currentAsec; 18191 final String currentVolumeUuid; 18192 final File codeFile; 18193 final String installerPackageName; 18194 final String packageAbiOverride; 18195 final int appId; 18196 final String seinfo; 18197 final String label; 18198 final int targetSdkVersion; 18199 18200 // reader 18201 synchronized (mPackages) { 18202 final PackageParser.Package pkg = mPackages.get(packageName); 18203 final PackageSetting ps = mSettings.mPackages.get(packageName); 18204 if (pkg == null || ps == null) { 18205 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 18206 } 18207 18208 if (pkg.applicationInfo.isSystemApp()) { 18209 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 18210 "Cannot move system application"); 18211 } 18212 18213 if (pkg.applicationInfo.isExternalAsec()) { 18214 currentAsec = true; 18215 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 18216 } else if (pkg.applicationInfo.isForwardLocked()) { 18217 currentAsec = true; 18218 currentVolumeUuid = "forward_locked"; 18219 } else { 18220 currentAsec = false; 18221 currentVolumeUuid = ps.volumeUuid; 18222 18223 final File probe = new File(pkg.codePath); 18224 final File probeOat = new File(probe, "oat"); 18225 if (!probe.isDirectory() || !probeOat.isDirectory()) { 18226 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18227 "Move only supported for modern cluster style installs"); 18228 } 18229 } 18230 18231 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 18232 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18233 "Package already moved to " + volumeUuid); 18234 } 18235 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 18236 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 18237 "Device admin cannot be moved"); 18238 } 18239 18240 if (ps.frozen) { 18241 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 18242 "Failed to move already frozen package"); 18243 } 18244 ps.frozen = true; 18245 18246 codeFile = new File(pkg.codePath); 18247 installerPackageName = ps.installerPackageName; 18248 packageAbiOverride = ps.cpuAbiOverrideString; 18249 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18250 seinfo = pkg.applicationInfo.seinfo; 18251 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 18252 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 18253 } 18254 18255 // Now that we're guarded by frozen state, kill app during move 18256 final long token = Binder.clearCallingIdentity(); 18257 try { 18258 killApplication(packageName, appId, "move pkg"); 18259 } finally { 18260 Binder.restoreCallingIdentity(token); 18261 } 18262 18263 final Bundle extras = new Bundle(); 18264 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 18265 extras.putString(Intent.EXTRA_TITLE, label); 18266 mMoveCallbacks.notifyCreated(moveId, extras); 18267 18268 int installFlags; 18269 final boolean moveCompleteApp; 18270 final File measurePath; 18271 18272 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 18273 installFlags = INSTALL_INTERNAL; 18274 moveCompleteApp = !currentAsec; 18275 measurePath = Environment.getDataAppDirectory(volumeUuid); 18276 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 18277 installFlags = INSTALL_EXTERNAL; 18278 moveCompleteApp = false; 18279 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 18280 } else { 18281 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 18282 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 18283 || !volume.isMountedWritable()) { 18284 unfreezePackage(packageName); 18285 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18286 "Move location not mounted private volume"); 18287 } 18288 18289 Preconditions.checkState(!currentAsec); 18290 18291 installFlags = INSTALL_INTERNAL; 18292 moveCompleteApp = true; 18293 measurePath = Environment.getDataAppDirectory(volumeUuid); 18294 } 18295 18296 final PackageStats stats = new PackageStats(null, -1); 18297 synchronized (mInstaller) { 18298 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 18299 unfreezePackage(packageName); 18300 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18301 "Failed to measure package size"); 18302 } 18303 } 18304 18305 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 18306 + stats.dataSize); 18307 18308 final long startFreeBytes = measurePath.getFreeSpace(); 18309 final long sizeBytes; 18310 if (moveCompleteApp) { 18311 sizeBytes = stats.codeSize + stats.dataSize; 18312 } else { 18313 sizeBytes = stats.codeSize; 18314 } 18315 18316 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 18317 unfreezePackage(packageName); 18318 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18319 "Not enough free space to move"); 18320 } 18321 18322 mMoveCallbacks.notifyStatusChanged(moveId, 10); 18323 18324 final CountDownLatch installedLatch = new CountDownLatch(1); 18325 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 18326 @Override 18327 public void onUserActionRequired(Intent intent) throws RemoteException { 18328 throw new IllegalStateException(); 18329 } 18330 18331 @Override 18332 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 18333 Bundle extras) throws RemoteException { 18334 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 18335 + PackageManager.installStatusToString(returnCode, msg)); 18336 18337 installedLatch.countDown(); 18338 18339 // Regardless of success or failure of the move operation, 18340 // always unfreeze the package 18341 unfreezePackage(packageName); 18342 18343 final int status = PackageManager.installStatusToPublicStatus(returnCode); 18344 switch (status) { 18345 case PackageInstaller.STATUS_SUCCESS: 18346 mMoveCallbacks.notifyStatusChanged(moveId, 18347 PackageManager.MOVE_SUCCEEDED); 18348 break; 18349 case PackageInstaller.STATUS_FAILURE_STORAGE: 18350 mMoveCallbacks.notifyStatusChanged(moveId, 18351 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 18352 break; 18353 default: 18354 mMoveCallbacks.notifyStatusChanged(moveId, 18355 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 18356 break; 18357 } 18358 } 18359 }; 18360 18361 final MoveInfo move; 18362 if (moveCompleteApp) { 18363 // Kick off a thread to report progress estimates 18364 new Thread() { 18365 @Override 18366 public void run() { 18367 while (true) { 18368 try { 18369 if (installedLatch.await(1, TimeUnit.SECONDS)) { 18370 break; 18371 } 18372 } catch (InterruptedException ignored) { 18373 } 18374 18375 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 18376 final int progress = 10 + (int) MathUtils.constrain( 18377 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 18378 mMoveCallbacks.notifyStatusChanged(moveId, progress); 18379 } 18380 } 18381 }.start(); 18382 18383 final String dataAppName = codeFile.getName(); 18384 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 18385 dataAppName, appId, seinfo, targetSdkVersion); 18386 } else { 18387 move = null; 18388 } 18389 18390 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 18391 18392 final Message msg = mHandler.obtainMessage(INIT_COPY); 18393 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 18394 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 18395 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 18396 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 18397 msg.obj = params; 18398 18399 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 18400 System.identityHashCode(msg.obj)); 18401 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 18402 System.identityHashCode(msg.obj)); 18403 18404 mHandler.sendMessage(msg); 18405 } 18406 18407 @Override 18408 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 18409 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 18410 18411 final int realMoveId = mNextMoveId.getAndIncrement(); 18412 final Bundle extras = new Bundle(); 18413 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 18414 mMoveCallbacks.notifyCreated(realMoveId, extras); 18415 18416 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 18417 @Override 18418 public void onCreated(int moveId, Bundle extras) { 18419 // Ignored 18420 } 18421 18422 @Override 18423 public void onStatusChanged(int moveId, int status, long estMillis) { 18424 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 18425 } 18426 }; 18427 18428 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18429 storage.setPrimaryStorageUuid(volumeUuid, callback); 18430 return realMoveId; 18431 } 18432 18433 @Override 18434 public int getMoveStatus(int moveId) { 18435 mContext.enforceCallingOrSelfPermission( 18436 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18437 return mMoveCallbacks.mLastStatus.get(moveId); 18438 } 18439 18440 @Override 18441 public void registerMoveCallback(IPackageMoveObserver callback) { 18442 mContext.enforceCallingOrSelfPermission( 18443 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18444 mMoveCallbacks.register(callback); 18445 } 18446 18447 @Override 18448 public void unregisterMoveCallback(IPackageMoveObserver callback) { 18449 mContext.enforceCallingOrSelfPermission( 18450 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18451 mMoveCallbacks.unregister(callback); 18452 } 18453 18454 @Override 18455 public boolean setInstallLocation(int loc) { 18456 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 18457 null); 18458 if (getInstallLocation() == loc) { 18459 return true; 18460 } 18461 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 18462 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 18463 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 18464 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 18465 return true; 18466 } 18467 return false; 18468 } 18469 18470 @Override 18471 public int getInstallLocation() { 18472 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 18473 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 18474 PackageHelper.APP_INSTALL_AUTO); 18475 } 18476 18477 /** Called by UserManagerService */ 18478 void cleanUpUser(UserManagerService userManager, int userHandle) { 18479 synchronized (mPackages) { 18480 mDirtyUsers.remove(userHandle); 18481 mUserNeedsBadging.delete(userHandle); 18482 mSettings.removeUserLPw(userHandle); 18483 mPendingBroadcasts.remove(userHandle); 18484 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 18485 } 18486 synchronized (mInstallLock) { 18487 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18488 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18489 final String volumeUuid = vol.getFsUuid(); 18490 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 18491 try { 18492 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 18493 } catch (InstallerException e) { 18494 Slog.w(TAG, "Failed to remove user data", e); 18495 } 18496 } 18497 synchronized (mPackages) { 18498 removeUnusedPackagesLILPw(userManager, userHandle); 18499 } 18500 } 18501 } 18502 18503 /** 18504 * We're removing userHandle and would like to remove any downloaded packages 18505 * that are no longer in use by any other user. 18506 * @param userHandle the user being removed 18507 */ 18508 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 18509 final boolean DEBUG_CLEAN_APKS = false; 18510 int [] users = userManager.getUserIds(); 18511 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 18512 while (psit.hasNext()) { 18513 PackageSetting ps = psit.next(); 18514 if (ps.pkg == null) { 18515 continue; 18516 } 18517 final String packageName = ps.pkg.packageName; 18518 // Skip over if system app 18519 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 18520 continue; 18521 } 18522 if (DEBUG_CLEAN_APKS) { 18523 Slog.i(TAG, "Checking package " + packageName); 18524 } 18525 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 18526 if (keep) { 18527 if (DEBUG_CLEAN_APKS) { 18528 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 18529 } 18530 } else { 18531 for (int i = 0; i < users.length; i++) { 18532 if (users[i] != userHandle && ps.getInstalled(users[i])) { 18533 keep = true; 18534 if (DEBUG_CLEAN_APKS) { 18535 Slog.i(TAG, " Keeping package " + packageName + " for user " 18536 + users[i]); 18537 } 18538 break; 18539 } 18540 } 18541 } 18542 if (!keep) { 18543 if (DEBUG_CLEAN_APKS) { 18544 Slog.i(TAG, " Removing package " + packageName); 18545 } 18546 mHandler.post(new Runnable() { 18547 public void run() { 18548 deletePackageX(packageName, userHandle, 0); 18549 } //end run 18550 }); 18551 } 18552 } 18553 } 18554 18555 /** Called by UserManagerService */ 18556 void createNewUser(int userHandle) { 18557 synchronized (mInstallLock) { 18558 try { 18559 mInstaller.createUserConfig(userHandle); 18560 } catch (InstallerException e) { 18561 Slog.w(TAG, "Failed to create user config", e); 18562 } 18563 mSettings.createNewUserLI(this, mInstaller, userHandle); 18564 } 18565 synchronized (mPackages) { 18566 applyFactoryDefaultBrowserLPw(userHandle); 18567 primeDomainVerificationsLPw(userHandle); 18568 } 18569 } 18570 18571 void newUserCreated(final int userHandle) { 18572 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 18573 // If permission review for legacy apps is required, we represent 18574 // dagerous permissions for such apps as always granted runtime 18575 // permissions to keep per user flag state whether review is needed. 18576 // Hence, if a new user is added we have to propagate dangerous 18577 // permission grants for these legacy apps. 18578 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 18579 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 18580 | UPDATE_PERMISSIONS_REPLACE_ALL); 18581 } 18582 } 18583 18584 @Override 18585 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 18586 mContext.enforceCallingOrSelfPermission( 18587 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 18588 "Only package verification agents can read the verifier device identity"); 18589 18590 synchronized (mPackages) { 18591 return mSettings.getVerifierDeviceIdentityLPw(); 18592 } 18593 } 18594 18595 @Override 18596 public void setPermissionEnforced(String permission, boolean enforced) { 18597 // TODO: Now that we no longer change GID for storage, this should to away. 18598 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 18599 "setPermissionEnforced"); 18600 if (READ_EXTERNAL_STORAGE.equals(permission)) { 18601 synchronized (mPackages) { 18602 if (mSettings.mReadExternalStorageEnforced == null 18603 || mSettings.mReadExternalStorageEnforced != enforced) { 18604 mSettings.mReadExternalStorageEnforced = enforced; 18605 mSettings.writeLPr(); 18606 } 18607 } 18608 // kill any non-foreground processes so we restart them and 18609 // grant/revoke the GID. 18610 final IActivityManager am = ActivityManagerNative.getDefault(); 18611 if (am != null) { 18612 final long token = Binder.clearCallingIdentity(); 18613 try { 18614 am.killProcessesBelowForeground("setPermissionEnforcement"); 18615 } catch (RemoteException e) { 18616 } finally { 18617 Binder.restoreCallingIdentity(token); 18618 } 18619 } 18620 } else { 18621 throw new IllegalArgumentException("No selective enforcement for " + permission); 18622 } 18623 } 18624 18625 @Override 18626 @Deprecated 18627 public boolean isPermissionEnforced(String permission) { 18628 return true; 18629 } 18630 18631 @Override 18632 public boolean isStorageLow() { 18633 final long token = Binder.clearCallingIdentity(); 18634 try { 18635 final DeviceStorageMonitorInternal 18636 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 18637 if (dsm != null) { 18638 return dsm.isMemoryLow(); 18639 } else { 18640 return false; 18641 } 18642 } finally { 18643 Binder.restoreCallingIdentity(token); 18644 } 18645 } 18646 18647 @Override 18648 public IPackageInstaller getPackageInstaller() { 18649 return mInstallerService; 18650 } 18651 18652 private boolean userNeedsBadging(int userId) { 18653 int index = mUserNeedsBadging.indexOfKey(userId); 18654 if (index < 0) { 18655 final UserInfo userInfo; 18656 final long token = Binder.clearCallingIdentity(); 18657 try { 18658 userInfo = sUserManager.getUserInfo(userId); 18659 } finally { 18660 Binder.restoreCallingIdentity(token); 18661 } 18662 final boolean b; 18663 if (userInfo != null && userInfo.isManagedProfile()) { 18664 b = true; 18665 } else { 18666 b = false; 18667 } 18668 mUserNeedsBadging.put(userId, b); 18669 return b; 18670 } 18671 return mUserNeedsBadging.valueAt(index); 18672 } 18673 18674 @Override 18675 public KeySet getKeySetByAlias(String packageName, String alias) { 18676 if (packageName == null || alias == null) { 18677 return null; 18678 } 18679 synchronized(mPackages) { 18680 final PackageParser.Package pkg = mPackages.get(packageName); 18681 if (pkg == null) { 18682 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18683 throw new IllegalArgumentException("Unknown package: " + packageName); 18684 } 18685 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18686 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 18687 } 18688 } 18689 18690 @Override 18691 public KeySet getSigningKeySet(String packageName) { 18692 if (packageName == null) { 18693 return null; 18694 } 18695 synchronized(mPackages) { 18696 final PackageParser.Package pkg = mPackages.get(packageName); 18697 if (pkg == null) { 18698 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18699 throw new IllegalArgumentException("Unknown package: " + packageName); 18700 } 18701 if (pkg.applicationInfo.uid != Binder.getCallingUid() 18702 && Process.SYSTEM_UID != Binder.getCallingUid()) { 18703 throw new SecurityException("May not access signing KeySet of other apps."); 18704 } 18705 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18706 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 18707 } 18708 } 18709 18710 @Override 18711 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 18712 if (packageName == null || ks == null) { 18713 return false; 18714 } 18715 synchronized(mPackages) { 18716 final PackageParser.Package pkg = mPackages.get(packageName); 18717 if (pkg == null) { 18718 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18719 throw new IllegalArgumentException("Unknown package: " + packageName); 18720 } 18721 IBinder ksh = ks.getToken(); 18722 if (ksh instanceof KeySetHandle) { 18723 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18724 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 18725 } 18726 return false; 18727 } 18728 } 18729 18730 @Override 18731 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 18732 if (packageName == null || ks == null) { 18733 return false; 18734 } 18735 synchronized(mPackages) { 18736 final PackageParser.Package pkg = mPackages.get(packageName); 18737 if (pkg == null) { 18738 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18739 throw new IllegalArgumentException("Unknown package: " + packageName); 18740 } 18741 IBinder ksh = ks.getToken(); 18742 if (ksh instanceof KeySetHandle) { 18743 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18744 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 18745 } 18746 return false; 18747 } 18748 } 18749 18750 private void deletePackageIfUnusedLPr(final String packageName) { 18751 PackageSetting ps = mSettings.mPackages.get(packageName); 18752 if (ps == null) { 18753 return; 18754 } 18755 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 18756 // TODO Implement atomic delete if package is unused 18757 // It is currently possible that the package will be deleted even if it is installed 18758 // after this method returns. 18759 mHandler.post(new Runnable() { 18760 public void run() { 18761 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 18762 } 18763 }); 18764 } 18765 } 18766 18767 /** 18768 * Check and throw if the given before/after packages would be considered a 18769 * downgrade. 18770 */ 18771 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 18772 throws PackageManagerException { 18773 if (after.versionCode < before.mVersionCode) { 18774 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 18775 "Update version code " + after.versionCode + " is older than current " 18776 + before.mVersionCode); 18777 } else if (after.versionCode == before.mVersionCode) { 18778 if (after.baseRevisionCode < before.baseRevisionCode) { 18779 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 18780 "Update base revision code " + after.baseRevisionCode 18781 + " is older than current " + before.baseRevisionCode); 18782 } 18783 18784 if (!ArrayUtils.isEmpty(after.splitNames)) { 18785 for (int i = 0; i < after.splitNames.length; i++) { 18786 final String splitName = after.splitNames[i]; 18787 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 18788 if (j != -1) { 18789 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 18790 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 18791 "Update split " + splitName + " revision code " 18792 + after.splitRevisionCodes[i] + " is older than current " 18793 + before.splitRevisionCodes[j]); 18794 } 18795 } 18796 } 18797 } 18798 } 18799 } 18800 18801 private static class MoveCallbacks extends Handler { 18802 private static final int MSG_CREATED = 1; 18803 private static final int MSG_STATUS_CHANGED = 2; 18804 18805 private final RemoteCallbackList<IPackageMoveObserver> 18806 mCallbacks = new RemoteCallbackList<>(); 18807 18808 private final SparseIntArray mLastStatus = new SparseIntArray(); 18809 18810 public MoveCallbacks(Looper looper) { 18811 super(looper); 18812 } 18813 18814 public void register(IPackageMoveObserver callback) { 18815 mCallbacks.register(callback); 18816 } 18817 18818 public void unregister(IPackageMoveObserver callback) { 18819 mCallbacks.unregister(callback); 18820 } 18821 18822 @Override 18823 public void handleMessage(Message msg) { 18824 final SomeArgs args = (SomeArgs) msg.obj; 18825 final int n = mCallbacks.beginBroadcast(); 18826 for (int i = 0; i < n; i++) { 18827 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 18828 try { 18829 invokeCallback(callback, msg.what, args); 18830 } catch (RemoteException ignored) { 18831 } 18832 } 18833 mCallbacks.finishBroadcast(); 18834 args.recycle(); 18835 } 18836 18837 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 18838 throws RemoteException { 18839 switch (what) { 18840 case MSG_CREATED: { 18841 callback.onCreated(args.argi1, (Bundle) args.arg2); 18842 break; 18843 } 18844 case MSG_STATUS_CHANGED: { 18845 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 18846 break; 18847 } 18848 } 18849 } 18850 18851 private void notifyCreated(int moveId, Bundle extras) { 18852 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 18853 18854 final SomeArgs args = SomeArgs.obtain(); 18855 args.argi1 = moveId; 18856 args.arg2 = extras; 18857 obtainMessage(MSG_CREATED, args).sendToTarget(); 18858 } 18859 18860 private void notifyStatusChanged(int moveId, int status) { 18861 notifyStatusChanged(moveId, status, -1); 18862 } 18863 18864 private void notifyStatusChanged(int moveId, int status, long estMillis) { 18865 Slog.v(TAG, "Move " + moveId + " status " + status); 18866 18867 final SomeArgs args = SomeArgs.obtain(); 18868 args.argi1 = moveId; 18869 args.argi2 = status; 18870 args.arg3 = estMillis; 18871 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 18872 18873 synchronized (mLastStatus) { 18874 mLastStatus.put(moveId, status); 18875 } 18876 } 18877 } 18878 18879 private final static class OnPermissionChangeListeners extends Handler { 18880 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 18881 18882 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 18883 new RemoteCallbackList<>(); 18884 18885 public OnPermissionChangeListeners(Looper looper) { 18886 super(looper); 18887 } 18888 18889 @Override 18890 public void handleMessage(Message msg) { 18891 switch (msg.what) { 18892 case MSG_ON_PERMISSIONS_CHANGED: { 18893 final int uid = msg.arg1; 18894 handleOnPermissionsChanged(uid); 18895 } break; 18896 } 18897 } 18898 18899 public void addListenerLocked(IOnPermissionsChangeListener listener) { 18900 mPermissionListeners.register(listener); 18901 18902 } 18903 18904 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 18905 mPermissionListeners.unregister(listener); 18906 } 18907 18908 public void onPermissionsChanged(int uid) { 18909 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 18910 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 18911 } 18912 } 18913 18914 private void handleOnPermissionsChanged(int uid) { 18915 final int count = mPermissionListeners.beginBroadcast(); 18916 try { 18917 for (int i = 0; i < count; i++) { 18918 IOnPermissionsChangeListener callback = mPermissionListeners 18919 .getBroadcastItem(i); 18920 try { 18921 callback.onPermissionsChanged(uid); 18922 } catch (RemoteException e) { 18923 Log.e(TAG, "Permission listener is dead", e); 18924 } 18925 } 18926 } finally { 18927 mPermissionListeners.finishBroadcast(); 18928 } 18929 } 18930 } 18931 18932 private class PackageManagerInternalImpl extends PackageManagerInternal { 18933 @Override 18934 public void setLocationPackagesProvider(PackagesProvider provider) { 18935 synchronized (mPackages) { 18936 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 18937 } 18938 } 18939 18940 @Override 18941 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 18942 synchronized (mPackages) { 18943 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 18944 } 18945 } 18946 18947 @Override 18948 public void setSmsAppPackagesProvider(PackagesProvider provider) { 18949 synchronized (mPackages) { 18950 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 18951 } 18952 } 18953 18954 @Override 18955 public void setDialerAppPackagesProvider(PackagesProvider provider) { 18956 synchronized (mPackages) { 18957 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 18958 } 18959 } 18960 18961 @Override 18962 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 18963 synchronized (mPackages) { 18964 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 18965 } 18966 } 18967 18968 @Override 18969 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 18970 synchronized (mPackages) { 18971 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 18972 } 18973 } 18974 18975 @Override 18976 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 18977 synchronized (mPackages) { 18978 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 18979 packageName, userId); 18980 } 18981 } 18982 18983 @Override 18984 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 18985 synchronized (mPackages) { 18986 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 18987 packageName, userId); 18988 } 18989 } 18990 18991 @Override 18992 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 18993 synchronized (mPackages) { 18994 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 18995 packageName, userId); 18996 } 18997 } 18998 18999 @Override 19000 public void setKeepUninstalledPackages(final List<String> packageList) { 19001 Preconditions.checkNotNull(packageList); 19002 List<String> removedFromList = null; 19003 synchronized (mPackages) { 19004 if (mKeepUninstalledPackages != null) { 19005 final int packagesCount = mKeepUninstalledPackages.size(); 19006 for (int i = 0; i < packagesCount; i++) { 19007 String oldPackage = mKeepUninstalledPackages.get(i); 19008 if (packageList != null && packageList.contains(oldPackage)) { 19009 continue; 19010 } 19011 if (removedFromList == null) { 19012 removedFromList = new ArrayList<>(); 19013 } 19014 removedFromList.add(oldPackage); 19015 } 19016 } 19017 mKeepUninstalledPackages = new ArrayList<>(packageList); 19018 if (removedFromList != null) { 19019 final int removedCount = removedFromList.size(); 19020 for (int i = 0; i < removedCount; i++) { 19021 deletePackageIfUnusedLPr(removedFromList.get(i)); 19022 } 19023 } 19024 } 19025 } 19026 19027 @Override 19028 public boolean isPermissionsReviewRequired(String packageName, int userId) { 19029 synchronized (mPackages) { 19030 // If we do not support permission review, done. 19031 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 19032 return false; 19033 } 19034 19035 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 19036 if (packageSetting == null) { 19037 return false; 19038 } 19039 19040 // Permission review applies only to apps not supporting the new permission model. 19041 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 19042 return false; 19043 } 19044 19045 // Legacy apps have the permission and get user consent on launch. 19046 PermissionsState permissionsState = packageSetting.getPermissionsState(); 19047 return permissionsState.isPermissionReviewRequired(userId); 19048 } 19049 } 19050 } 19051 19052 @Override 19053 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 19054 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 19055 synchronized (mPackages) { 19056 final long identity = Binder.clearCallingIdentity(); 19057 try { 19058 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 19059 packageNames, userId); 19060 } finally { 19061 Binder.restoreCallingIdentity(identity); 19062 } 19063 } 19064 } 19065 19066 private static void enforceSystemOrPhoneCaller(String tag) { 19067 int callingUid = Binder.getCallingUid(); 19068 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 19069 throw new SecurityException( 19070 "Cannot call " + tag + " from UID " + callingUid); 19071 } 19072 } 19073 19074 boolean isHistoricalPackageUsageAvailable() { 19075 return mPackageUsage.isHistoricalPackageUsageAvailable(); 19076 } 19077} 19078