PackageManagerService.java revision 115d2c189a46f535778d9dd0923f703ff2f888fe
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_DOESNT_EXIST; 69import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 70import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 71import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 72import static android.content.pm.PackageManager.PERMISSION_DENIED; 73import static android.content.pm.PackageManager.PERMISSION_GRANTED; 74import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 75import static android.content.pm.PackageParser.isApkFile; 76import static android.os.Process.PACKAGE_INFO_GID; 77import static android.os.Process.SYSTEM_UID; 78import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 79import static android.system.OsConstants.O_CREAT; 80import static android.system.OsConstants.O_RDWR; 81 82import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 83import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 84import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 85import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 86import static com.android.internal.util.ArrayUtils.appendInt; 87import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 88import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 89import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 90import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 91import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 92import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 93import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 94import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 95import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 96 97import android.Manifest; 98import android.annotation.NonNull; 99import android.annotation.Nullable; 100import android.app.ActivityManager; 101import android.app.ActivityManagerNative; 102import android.app.IActivityManager; 103import android.app.admin.IDevicePolicyManager; 104import android.app.backup.IBackupManager; 105import android.content.BroadcastReceiver; 106import android.content.ComponentName; 107import android.content.Context; 108import android.content.IIntentReceiver; 109import android.content.Intent; 110import android.content.IntentFilter; 111import android.content.IntentSender; 112import android.content.IntentSender.SendIntentException; 113import android.content.ServiceConnection; 114import android.content.pm.ActivityInfo; 115import android.content.pm.ApplicationInfo; 116import android.content.pm.AppsQueryHelper; 117import android.content.pm.ComponentInfo; 118import android.content.pm.EphemeralApplicationInfo; 119import android.content.pm.EphemeralResolveInfo; 120import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 121import android.content.pm.FeatureInfo; 122import android.content.pm.IOnPermissionsChangeListener; 123import android.content.pm.IPackageDataObserver; 124import android.content.pm.IPackageDeleteObserver; 125import android.content.pm.IPackageDeleteObserver2; 126import android.content.pm.IPackageInstallObserver2; 127import android.content.pm.IPackageInstaller; 128import android.content.pm.IPackageManager; 129import android.content.pm.IPackageMoveObserver; 130import android.content.pm.IPackageStatsObserver; 131import android.content.pm.InstrumentationInfo; 132import android.content.pm.IntentFilterVerificationInfo; 133import android.content.pm.KeySet; 134import android.content.pm.PackageCleanItem; 135import android.content.pm.PackageInfo; 136import android.content.pm.PackageInfoLite; 137import android.content.pm.PackageInstaller; 138import android.content.pm.PackageManager; 139import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 140import android.content.pm.PackageManagerInternal; 141import android.content.pm.PackageParser; 142import android.content.pm.PackageParser.ActivityIntentInfo; 143import android.content.pm.PackageParser.PackageLite; 144import android.content.pm.PackageParser.PackageParserException; 145import android.content.pm.PackageStats; 146import android.content.pm.PackageUserState; 147import android.content.pm.ParceledListSlice; 148import android.content.pm.PermissionGroupInfo; 149import android.content.pm.PermissionInfo; 150import android.content.pm.ProviderInfo; 151import android.content.pm.ResolveInfo; 152import android.content.pm.ServiceInfo; 153import android.content.pm.Signature; 154import android.content.pm.UserInfo; 155import android.content.pm.VerificationParams; 156import android.content.pm.VerifierDeviceIdentity; 157import android.content.pm.VerifierInfo; 158import android.content.res.Resources; 159import android.graphics.Bitmap; 160import android.hardware.display.DisplayManager; 161import android.net.Uri; 162import android.os.Binder; 163import android.os.Build; 164import android.os.Bundle; 165import android.os.Debug; 166import android.os.Environment; 167import android.os.Environment.UserEnvironment; 168import android.os.FileUtils; 169import android.os.Handler; 170import android.os.IBinder; 171import android.os.Looper; 172import android.os.Message; 173import android.os.Parcel; 174import android.os.ParcelFileDescriptor; 175import android.os.Process; 176import android.os.RemoteCallbackList; 177import android.os.RemoteException; 178import android.os.ResultReceiver; 179import android.os.SELinux; 180import android.os.ServiceManager; 181import android.os.SystemClock; 182import android.os.SystemProperties; 183import android.os.Trace; 184import android.os.UserHandle; 185import android.os.UserManager; 186import android.os.storage.IMountService; 187import android.os.storage.MountServiceInternal; 188import android.os.storage.StorageEventListener; 189import android.os.storage.StorageManager; 190import android.os.storage.VolumeInfo; 191import android.os.storage.VolumeRecord; 192import android.security.KeyStore; 193import android.security.SystemKeyStore; 194import android.system.ErrnoException; 195import android.system.Os; 196import android.text.TextUtils; 197import android.text.format.DateUtils; 198import android.util.ArrayMap; 199import android.util.ArraySet; 200import android.util.AtomicFile; 201import android.util.DisplayMetrics; 202import android.util.EventLog; 203import android.util.ExceptionUtils; 204import android.util.Log; 205import android.util.LogPrinter; 206import android.util.MathUtils; 207import android.util.PrintStreamPrinter; 208import android.util.Slog; 209import android.util.SparseArray; 210import android.util.SparseBooleanArray; 211import android.util.SparseIntArray; 212import android.util.Xml; 213import android.view.Display; 214 215import com.android.internal.R; 216import com.android.internal.annotations.GuardedBy; 217import com.android.internal.app.IMediaContainerService; 218import com.android.internal.app.ResolverActivity; 219import com.android.internal.content.NativeLibraryHelper; 220import com.android.internal.content.PackageHelper; 221import com.android.internal.os.IParcelFileDescriptorFactory; 222import com.android.internal.os.InstallerConnection.InstallerException; 223import com.android.internal.os.SomeArgs; 224import com.android.internal.os.Zygote; 225import com.android.internal.util.ArrayUtils; 226import com.android.internal.util.FastPrintWriter; 227import com.android.internal.util.FastXmlSerializer; 228import com.android.internal.util.IndentingPrintWriter; 229import com.android.internal.util.Preconditions; 230import com.android.internal.util.XmlUtils; 231import com.android.server.EventLogTags; 232import com.android.server.FgThread; 233import com.android.server.IntentResolver; 234import com.android.server.LocalServices; 235import com.android.server.ServiceThread; 236import com.android.server.SystemConfig; 237import com.android.server.Watchdog; 238import com.android.server.pm.PermissionsState.PermissionState; 239import com.android.server.pm.Settings.DatabaseVersion; 240import com.android.server.pm.Settings.VersionInfo; 241import com.android.server.storage.DeviceStorageMonitorInternal; 242 243import dalvik.system.DexFile; 244import dalvik.system.VMRuntime; 245 246import libcore.io.IoUtils; 247import libcore.util.EmptyArray; 248 249import org.xmlpull.v1.XmlPullParser; 250import org.xmlpull.v1.XmlPullParserException; 251import org.xmlpull.v1.XmlSerializer; 252 253import java.io.BufferedInputStream; 254import java.io.BufferedOutputStream; 255import java.io.BufferedReader; 256import java.io.ByteArrayInputStream; 257import java.io.ByteArrayOutputStream; 258import java.io.File; 259import java.io.FileDescriptor; 260import java.io.FileNotFoundException; 261import java.io.FileOutputStream; 262import java.io.FileReader; 263import java.io.FilenameFilter; 264import java.io.IOException; 265import java.io.InputStream; 266import java.io.PrintWriter; 267import java.nio.charset.StandardCharsets; 268import java.security.MessageDigest; 269import java.security.NoSuchAlgorithmException; 270import java.security.PublicKey; 271import java.security.cert.CertificateEncodingException; 272import java.security.cert.CertificateException; 273import java.text.SimpleDateFormat; 274import java.util.ArrayList; 275import java.util.Arrays; 276import java.util.Collection; 277import java.util.Collections; 278import java.util.Comparator; 279import java.util.Date; 280import java.util.HashSet; 281import java.util.Iterator; 282import java.util.List; 283import java.util.Map; 284import java.util.Objects; 285import java.util.Set; 286import java.util.concurrent.CountDownLatch; 287import java.util.concurrent.TimeUnit; 288import java.util.concurrent.atomic.AtomicBoolean; 289import java.util.concurrent.atomic.AtomicInteger; 290import java.util.concurrent.atomic.AtomicLong; 291 292/** 293 * Keep track of all those .apks everywhere. 294 * 295 * This is very central to the platform's security; please run the unit 296 * tests whenever making modifications here: 297 * 298runtest -c android.content.pm.PackageManagerTests frameworks-core 299 * 300 * {@hide} 301 */ 302public class PackageManagerService extends IPackageManager.Stub { 303 static final String TAG = "PackageManager"; 304 static final boolean DEBUG_SETTINGS = false; 305 static final boolean DEBUG_PREFERRED = false; 306 static final boolean DEBUG_UPGRADE = false; 307 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 308 private static final boolean DEBUG_BACKUP = false; 309 private static final boolean DEBUG_INSTALL = false; 310 private static final boolean DEBUG_REMOVE = false; 311 private static final boolean DEBUG_BROADCASTS = false; 312 private static final boolean DEBUG_SHOW_INFO = false; 313 private static final boolean DEBUG_PACKAGE_INFO = false; 314 private static final boolean DEBUG_INTENT_MATCHING = false; 315 private static final boolean DEBUG_PACKAGE_SCANNING = false; 316 private static final boolean DEBUG_VERIFY = false; 317 318 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 319 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 320 // user, but by default initialize to this. 321 static final boolean DEBUG_DEXOPT = false; 322 323 private static final boolean DEBUG_ABI_SELECTION = false; 324 private static final boolean DEBUG_EPHEMERAL = false; 325 private static final boolean DEBUG_TRIAGED_MISSING = false; 326 private static final boolean DEBUG_APP_DATA = false; 327 328 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 329 330 private static final boolean DISABLE_EPHEMERAL_APPS = true; 331 332 private static final int RADIO_UID = Process.PHONE_UID; 333 private static final int LOG_UID = Process.LOG_UID; 334 private static final int NFC_UID = Process.NFC_UID; 335 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 336 private static final int SHELL_UID = Process.SHELL_UID; 337 338 // Cap the size of permission trees that 3rd party apps can define 339 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 340 341 // Suffix used during package installation when copying/moving 342 // package apks to install directory. 343 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 344 345 static final int SCAN_NO_DEX = 1<<1; 346 static final int SCAN_FORCE_DEX = 1<<2; 347 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 348 static final int SCAN_NEW_INSTALL = 1<<4; 349 static final int SCAN_NO_PATHS = 1<<5; 350 static final int SCAN_UPDATE_TIME = 1<<6; 351 static final int SCAN_DEFER_DEX = 1<<7; 352 static final int SCAN_BOOTING = 1<<8; 353 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 354 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 355 static final int SCAN_REPLACING = 1<<11; 356 static final int SCAN_REQUIRE_KNOWN = 1<<12; 357 static final int SCAN_MOVE = 1<<13; 358 static final int SCAN_INITIAL = 1<<14; 359 static final int SCAN_CHECK_ONLY = 1<<15; 360 361 static final int REMOVE_CHATTY = 1<<16; 362 363 private static final int[] EMPTY_INT_ARRAY = new int[0]; 364 365 /** 366 * Timeout (in milliseconds) after which the watchdog should declare that 367 * our handler thread is wedged. The usual default for such things is one 368 * minute but we sometimes do very lengthy I/O operations on this thread, 369 * such as installing multi-gigabyte applications, so ours needs to be longer. 370 */ 371 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 372 373 /** 374 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 375 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 376 * settings entry if available, otherwise we use the hardcoded default. If it's been 377 * more than this long since the last fstrim, we force one during the boot sequence. 378 * 379 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 380 * one gets run at the next available charging+idle time. This final mandatory 381 * no-fstrim check kicks in only of the other scheduling criteria is never met. 382 */ 383 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 384 385 /** 386 * Whether verification is enabled by default. 387 */ 388 private static final boolean DEFAULT_VERIFY_ENABLE = true; 389 390 /** 391 * The default maximum time to wait for the verification agent to return in 392 * milliseconds. 393 */ 394 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 395 396 /** 397 * The default response for package verification timeout. 398 * 399 * This can be either PackageManager.VERIFICATION_ALLOW or 400 * PackageManager.VERIFICATION_REJECT. 401 */ 402 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 403 404 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 405 406 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 407 DEFAULT_CONTAINER_PACKAGE, 408 "com.android.defcontainer.DefaultContainerService"); 409 410 private static final String KILL_APP_REASON_GIDS_CHANGED = 411 "permission grant or revoke changed gids"; 412 413 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 414 "permissions revoked"; 415 416 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 417 418 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 419 420 /** Permission grant: not grant the permission. */ 421 private static final int GRANT_DENIED = 1; 422 423 /** Permission grant: grant the permission as an install permission. */ 424 private static final int GRANT_INSTALL = 2; 425 426 /** Permission grant: grant the permission as a runtime one. */ 427 private static final int GRANT_RUNTIME = 3; 428 429 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 430 private static final int GRANT_UPGRADE = 4; 431 432 /** Canonical intent used to identify what counts as a "web browser" app */ 433 private static final Intent sBrowserIntent; 434 static { 435 sBrowserIntent = new Intent(); 436 sBrowserIntent.setAction(Intent.ACTION_VIEW); 437 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 438 sBrowserIntent.setData(Uri.parse("http:")); 439 } 440 441 final ServiceThread mHandlerThread; 442 443 final PackageHandler mHandler; 444 445 /** 446 * Messages for {@link #mHandler} that need to wait for system ready before 447 * being dispatched. 448 */ 449 private ArrayList<Message> mPostSystemReadyMessages; 450 451 final int mSdkVersion = Build.VERSION.SDK_INT; 452 453 final Context mContext; 454 final boolean mFactoryTest; 455 final boolean mOnlyCore; 456 final DisplayMetrics mMetrics; 457 final int mDefParseFlags; 458 final String[] mSeparateProcesses; 459 final boolean mIsUpgrade; 460 461 /** The location for ASEC container files on internal storage. */ 462 final String mAsecInternalPath; 463 464 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 465 // LOCK HELD. Can be called with mInstallLock held. 466 @GuardedBy("mInstallLock") 467 final Installer mInstaller; 468 469 /** Directory where installed third-party apps stored */ 470 final File mAppInstallDir; 471 final File mEphemeralInstallDir; 472 473 /** 474 * Directory to which applications installed internally have their 475 * 32 bit native libraries copied. 476 */ 477 private File mAppLib32InstallDir; 478 479 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 480 // apps. 481 final File mDrmAppPrivateInstallDir; 482 483 // ---------------------------------------------------------------- 484 485 // Lock for state used when installing and doing other long running 486 // operations. Methods that must be called with this lock held have 487 // the suffix "LI". 488 final Object mInstallLock = new Object(); 489 490 // ---------------------------------------------------------------- 491 492 // Keys are String (package name), values are Package. This also serves 493 // as the lock for the global state. Methods that must be called with 494 // this lock held have the prefix "LP". 495 @GuardedBy("mPackages") 496 final ArrayMap<String, PackageParser.Package> mPackages = 497 new ArrayMap<String, PackageParser.Package>(); 498 499 // Tracks available target package names -> overlay package paths. 500 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 501 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 502 503 /** 504 * Tracks new system packages [received in an OTA] that we expect to 505 * find updated user-installed versions. Keys are package name, values 506 * are package location. 507 */ 508 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 509 510 /** 511 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 512 */ 513 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 514 /** 515 * Whether or not system app permissions should be promoted from install to runtime. 516 */ 517 boolean mPromoteSystemApps; 518 519 final Settings mSettings; 520 boolean mRestoredSettings; 521 522 // System configuration read by SystemConfig. 523 final int[] mGlobalGids; 524 final SparseArray<ArraySet<String>> mSystemPermissions; 525 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 526 527 // If mac_permissions.xml was found for seinfo labeling. 528 boolean mFoundPolicyFile; 529 530 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 531 532 public static final class SharedLibraryEntry { 533 public final String path; 534 public final String apk; 535 536 SharedLibraryEntry(String _path, String _apk) { 537 path = _path; 538 apk = _apk; 539 } 540 } 541 542 // Currently known shared libraries. 543 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 544 new ArrayMap<String, SharedLibraryEntry>(); 545 546 // All available activities, for your resolving pleasure. 547 final ActivityIntentResolver mActivities = 548 new ActivityIntentResolver(); 549 550 // All available receivers, for your resolving pleasure. 551 final ActivityIntentResolver mReceivers = 552 new ActivityIntentResolver(); 553 554 // All available services, for your resolving pleasure. 555 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 556 557 // All available providers, for your resolving pleasure. 558 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 559 560 // Mapping from provider base names (first directory in content URI codePath) 561 // to the provider information. 562 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 563 new ArrayMap<String, PackageParser.Provider>(); 564 565 // Mapping from instrumentation class names to info about them. 566 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 567 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 568 569 // Mapping from permission names to info about them. 570 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 571 new ArrayMap<String, PackageParser.PermissionGroup>(); 572 573 // Packages whose data we have transfered into another package, thus 574 // should no longer exist. 575 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 576 577 // Broadcast actions that are only available to the system. 578 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 579 580 /** List of packages waiting for verification. */ 581 final SparseArray<PackageVerificationState> mPendingVerification 582 = new SparseArray<PackageVerificationState>(); 583 584 /** Set of packages associated with each app op permission. */ 585 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 586 587 final PackageInstallerService mInstallerService; 588 589 private final PackageDexOptimizer mPackageDexOptimizer; 590 591 private AtomicInteger mNextMoveId = new AtomicInteger(); 592 private final MoveCallbacks mMoveCallbacks; 593 594 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 595 596 // Cache of users who need badging. 597 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 598 599 /** Token for keys in mPendingVerification. */ 600 private int mPendingVerificationToken = 0; 601 602 volatile boolean mSystemReady; 603 volatile boolean mSafeMode; 604 volatile boolean mHasSystemUidErrors; 605 606 ApplicationInfo mAndroidApplication; 607 final ActivityInfo mResolveActivity = new ActivityInfo(); 608 final ResolveInfo mResolveInfo = new ResolveInfo(); 609 ComponentName mResolveComponentName; 610 PackageParser.Package mPlatformPackage; 611 ComponentName mCustomResolverComponentName; 612 613 boolean mResolverReplaced = false; 614 615 private final @Nullable ComponentName mIntentFilterVerifierComponent; 616 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 617 618 private int mIntentFilterVerificationToken = 0; 619 620 /** Component that knows whether or not an ephemeral application exists */ 621 final ComponentName mEphemeralResolverComponent; 622 /** The service connection to the ephemeral resolver */ 623 final EphemeralResolverConnection mEphemeralResolverConnection; 624 625 /** Component used to install ephemeral applications */ 626 final ComponentName mEphemeralInstallerComponent; 627 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 628 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 629 630 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 631 = new SparseArray<IntentFilterVerificationState>(); 632 633 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 634 new DefaultPermissionGrantPolicy(this); 635 636 // List of packages names to keep cached, even if they are uninstalled for all users 637 private List<String> mKeepUninstalledPackages; 638 639 private boolean mUseJitProfiles = 640 SystemProperties.getBoolean("dalvik.vm.usejitprofiles", false); 641 642 private static class IFVerificationParams { 643 PackageParser.Package pkg; 644 boolean replacing; 645 int userId; 646 int verifierUid; 647 648 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 649 int _userId, int _verifierUid) { 650 pkg = _pkg; 651 replacing = _replacing; 652 userId = _userId; 653 replacing = _replacing; 654 verifierUid = _verifierUid; 655 } 656 } 657 658 private interface IntentFilterVerifier<T extends IntentFilter> { 659 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 660 T filter, String packageName); 661 void startVerifications(int userId); 662 void receiveVerificationResponse(int verificationId); 663 } 664 665 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 666 private Context mContext; 667 private ComponentName mIntentFilterVerifierComponent; 668 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 669 670 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 671 mContext = context; 672 mIntentFilterVerifierComponent = verifierComponent; 673 } 674 675 private String getDefaultScheme() { 676 return IntentFilter.SCHEME_HTTPS; 677 } 678 679 @Override 680 public void startVerifications(int userId) { 681 // Launch verifications requests 682 int count = mCurrentIntentFilterVerifications.size(); 683 for (int n=0; n<count; n++) { 684 int verificationId = mCurrentIntentFilterVerifications.get(n); 685 final IntentFilterVerificationState ivs = 686 mIntentFilterVerificationStates.get(verificationId); 687 688 String packageName = ivs.getPackageName(); 689 690 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 691 final int filterCount = filters.size(); 692 ArraySet<String> domainsSet = new ArraySet<>(); 693 for (int m=0; m<filterCount; m++) { 694 PackageParser.ActivityIntentInfo filter = filters.get(m); 695 domainsSet.addAll(filter.getHostsList()); 696 } 697 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 698 synchronized (mPackages) { 699 if (mSettings.createIntentFilterVerificationIfNeededLPw( 700 packageName, domainsList) != null) { 701 scheduleWriteSettingsLocked(); 702 } 703 } 704 sendVerificationRequest(userId, verificationId, ivs); 705 } 706 mCurrentIntentFilterVerifications.clear(); 707 } 708 709 private void sendVerificationRequest(int userId, int verificationId, 710 IntentFilterVerificationState ivs) { 711 712 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 713 verificationIntent.putExtra( 714 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 715 verificationId); 716 verificationIntent.putExtra( 717 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 718 getDefaultScheme()); 719 verificationIntent.putExtra( 720 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 721 ivs.getHostsString()); 722 verificationIntent.putExtra( 723 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 724 ivs.getPackageName()); 725 verificationIntent.setComponent(mIntentFilterVerifierComponent); 726 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 727 728 UserHandle user = new UserHandle(userId); 729 mContext.sendBroadcastAsUser(verificationIntent, user); 730 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 731 "Sending IntentFilter verification broadcast"); 732 } 733 734 public void receiveVerificationResponse(int verificationId) { 735 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 736 737 final boolean verified = ivs.isVerified(); 738 739 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 740 final int count = filters.size(); 741 if (DEBUG_DOMAIN_VERIFICATION) { 742 Slog.i(TAG, "Received verification response " + verificationId 743 + " for " + count + " filters, verified=" + verified); 744 } 745 for (int n=0; n<count; n++) { 746 PackageParser.ActivityIntentInfo filter = filters.get(n); 747 filter.setVerified(verified); 748 749 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 750 + " verified with result:" + verified + " and hosts:" 751 + ivs.getHostsString()); 752 } 753 754 mIntentFilterVerificationStates.remove(verificationId); 755 756 final String packageName = ivs.getPackageName(); 757 IntentFilterVerificationInfo ivi = null; 758 759 synchronized (mPackages) { 760 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 761 } 762 if (ivi == null) { 763 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 764 + verificationId + " packageName:" + packageName); 765 return; 766 } 767 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 768 "Updating IntentFilterVerificationInfo for package " + packageName 769 +" verificationId:" + verificationId); 770 771 synchronized (mPackages) { 772 if (verified) { 773 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 774 } else { 775 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 776 } 777 scheduleWriteSettingsLocked(); 778 779 final int userId = ivs.getUserId(); 780 if (userId != UserHandle.USER_ALL) { 781 final int userStatus = 782 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 783 784 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 785 boolean needUpdate = false; 786 787 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 788 // already been set by the User thru the Disambiguation dialog 789 switch (userStatus) { 790 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 791 if (verified) { 792 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 793 } else { 794 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 795 } 796 needUpdate = true; 797 break; 798 799 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 800 if (verified) { 801 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 802 needUpdate = true; 803 } 804 break; 805 806 default: 807 // Nothing to do 808 } 809 810 if (needUpdate) { 811 mSettings.updateIntentFilterVerificationStatusLPw( 812 packageName, updatedStatus, userId); 813 scheduleWritePackageRestrictionsLocked(userId); 814 } 815 } 816 } 817 } 818 819 @Override 820 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 821 ActivityIntentInfo filter, String packageName) { 822 if (!hasValidDomains(filter)) { 823 return false; 824 } 825 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 826 if (ivs == null) { 827 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 828 packageName); 829 } 830 if (DEBUG_DOMAIN_VERIFICATION) { 831 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 832 } 833 ivs.addFilter(filter); 834 return true; 835 } 836 837 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 838 int userId, int verificationId, String packageName) { 839 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 840 verifierUid, userId, packageName); 841 ivs.setPendingState(); 842 synchronized (mPackages) { 843 mIntentFilterVerificationStates.append(verificationId, ivs); 844 mCurrentIntentFilterVerifications.add(verificationId); 845 } 846 return ivs; 847 } 848 } 849 850 private static boolean hasValidDomains(ActivityIntentInfo filter) { 851 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 852 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 853 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 854 } 855 856 // Set of pending broadcasts for aggregating enable/disable of components. 857 static class PendingPackageBroadcasts { 858 // for each user id, a map of <package name -> components within that package> 859 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 860 861 public PendingPackageBroadcasts() { 862 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 863 } 864 865 public ArrayList<String> get(int userId, String packageName) { 866 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 867 return packages.get(packageName); 868 } 869 870 public void put(int userId, String packageName, ArrayList<String> components) { 871 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 872 packages.put(packageName, components); 873 } 874 875 public void remove(int userId, String packageName) { 876 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 877 if (packages != null) { 878 packages.remove(packageName); 879 } 880 } 881 882 public void remove(int userId) { 883 mUidMap.remove(userId); 884 } 885 886 public int userIdCount() { 887 return mUidMap.size(); 888 } 889 890 public int userIdAt(int n) { 891 return mUidMap.keyAt(n); 892 } 893 894 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 895 return mUidMap.get(userId); 896 } 897 898 public int size() { 899 // total number of pending broadcast entries across all userIds 900 int num = 0; 901 for (int i = 0; i< mUidMap.size(); i++) { 902 num += mUidMap.valueAt(i).size(); 903 } 904 return num; 905 } 906 907 public void clear() { 908 mUidMap.clear(); 909 } 910 911 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 912 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 913 if (map == null) { 914 map = new ArrayMap<String, ArrayList<String>>(); 915 mUidMap.put(userId, map); 916 } 917 return map; 918 } 919 } 920 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 921 922 // Service Connection to remote media container service to copy 923 // package uri's from external media onto secure containers 924 // or internal storage. 925 private IMediaContainerService mContainerService = null; 926 927 static final int SEND_PENDING_BROADCAST = 1; 928 static final int MCS_BOUND = 3; 929 static final int END_COPY = 4; 930 static final int INIT_COPY = 5; 931 static final int MCS_UNBIND = 6; 932 static final int START_CLEANING_PACKAGE = 7; 933 static final int FIND_INSTALL_LOC = 8; 934 static final int POST_INSTALL = 9; 935 static final int MCS_RECONNECT = 10; 936 static final int MCS_GIVE_UP = 11; 937 static final int UPDATED_MEDIA_STATUS = 12; 938 static final int WRITE_SETTINGS = 13; 939 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 940 static final int PACKAGE_VERIFIED = 15; 941 static final int CHECK_PENDING_VERIFICATION = 16; 942 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 943 static final int INTENT_FILTER_VERIFIED = 18; 944 945 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 946 947 // Delay time in millisecs 948 static final int BROADCAST_DELAY = 10 * 1000; 949 950 static UserManagerService sUserManager; 951 952 // Stores a list of users whose package restrictions file needs to be updated 953 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 954 955 final private DefaultContainerConnection mDefContainerConn = 956 new DefaultContainerConnection(); 957 class DefaultContainerConnection implements ServiceConnection { 958 public void onServiceConnected(ComponentName name, IBinder service) { 959 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 960 IMediaContainerService imcs = 961 IMediaContainerService.Stub.asInterface(service); 962 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 963 } 964 965 public void onServiceDisconnected(ComponentName name) { 966 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 967 } 968 } 969 970 // Recordkeeping of restore-after-install operations that are currently in flight 971 // between the Package Manager and the Backup Manager 972 static class PostInstallData { 973 public InstallArgs args; 974 public PackageInstalledInfo res; 975 976 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 977 args = _a; 978 res = _r; 979 } 980 } 981 982 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 983 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 984 985 // XML tags for backup/restore of various bits of state 986 private static final String TAG_PREFERRED_BACKUP = "pa"; 987 private static final String TAG_DEFAULT_APPS = "da"; 988 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 989 990 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 991 private static final String TAG_ALL_GRANTS = "rt-grants"; 992 private static final String TAG_GRANT = "grant"; 993 private static final String ATTR_PACKAGE_NAME = "pkg"; 994 995 private static final String TAG_PERMISSION = "perm"; 996 private static final String ATTR_PERMISSION_NAME = "name"; 997 private static final String ATTR_IS_GRANTED = "g"; 998 private static final String ATTR_USER_SET = "set"; 999 private static final String ATTR_USER_FIXED = "fixed"; 1000 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1001 1002 // System/policy permission grants are not backed up 1003 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1004 FLAG_PERMISSION_POLICY_FIXED 1005 | FLAG_PERMISSION_SYSTEM_FIXED 1006 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1007 1008 // And we back up these user-adjusted states 1009 private static final int USER_RUNTIME_GRANT_MASK = 1010 FLAG_PERMISSION_USER_SET 1011 | FLAG_PERMISSION_USER_FIXED 1012 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1013 1014 final @Nullable String mRequiredVerifierPackage; 1015 final @Nullable String mRequiredInstallerPackage; 1016 1017 private final PackageUsage mPackageUsage = new PackageUsage(); 1018 1019 private class PackageUsage { 1020 private static final int WRITE_INTERVAL 1021 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1022 1023 private final Object mFileLock = new Object(); 1024 private final AtomicLong mLastWritten = new AtomicLong(0); 1025 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1026 1027 private boolean mIsHistoricalPackageUsageAvailable = true; 1028 1029 boolean isHistoricalPackageUsageAvailable() { 1030 return mIsHistoricalPackageUsageAvailable; 1031 } 1032 1033 void write(boolean force) { 1034 if (force) { 1035 writeInternal(); 1036 return; 1037 } 1038 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1039 && !DEBUG_DEXOPT) { 1040 return; 1041 } 1042 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1043 new Thread("PackageUsage_DiskWriter") { 1044 @Override 1045 public void run() { 1046 try { 1047 writeInternal(); 1048 } finally { 1049 mBackgroundWriteRunning.set(false); 1050 } 1051 } 1052 }.start(); 1053 } 1054 } 1055 1056 private void writeInternal() { 1057 synchronized (mPackages) { 1058 synchronized (mFileLock) { 1059 AtomicFile file = getFile(); 1060 FileOutputStream f = null; 1061 try { 1062 f = file.startWrite(); 1063 BufferedOutputStream out = new BufferedOutputStream(f); 1064 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1065 StringBuilder sb = new StringBuilder(); 1066 for (PackageParser.Package pkg : mPackages.values()) { 1067 if (pkg.mLastPackageUsageTimeInMills == 0) { 1068 continue; 1069 } 1070 sb.setLength(0); 1071 sb.append(pkg.packageName); 1072 sb.append(' '); 1073 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1074 sb.append('\n'); 1075 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1076 } 1077 out.flush(); 1078 file.finishWrite(f); 1079 } catch (IOException e) { 1080 if (f != null) { 1081 file.failWrite(f); 1082 } 1083 Log.e(TAG, "Failed to write package usage times", e); 1084 } 1085 } 1086 } 1087 mLastWritten.set(SystemClock.elapsedRealtime()); 1088 } 1089 1090 void readLP() { 1091 synchronized (mFileLock) { 1092 AtomicFile file = getFile(); 1093 BufferedInputStream in = null; 1094 try { 1095 in = new BufferedInputStream(file.openRead()); 1096 StringBuffer sb = new StringBuffer(); 1097 while (true) { 1098 String packageName = readToken(in, sb, ' '); 1099 if (packageName == null) { 1100 break; 1101 } 1102 String timeInMillisString = readToken(in, sb, '\n'); 1103 if (timeInMillisString == null) { 1104 throw new IOException("Failed to find last usage time for package " 1105 + packageName); 1106 } 1107 PackageParser.Package pkg = mPackages.get(packageName); 1108 if (pkg == null) { 1109 continue; 1110 } 1111 long timeInMillis; 1112 try { 1113 timeInMillis = Long.parseLong(timeInMillisString); 1114 } catch (NumberFormatException e) { 1115 throw new IOException("Failed to parse " + timeInMillisString 1116 + " as a long.", e); 1117 } 1118 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1119 } 1120 } catch (FileNotFoundException expected) { 1121 mIsHistoricalPackageUsageAvailable = false; 1122 } catch (IOException e) { 1123 Log.w(TAG, "Failed to read package usage times", e); 1124 } finally { 1125 IoUtils.closeQuietly(in); 1126 } 1127 } 1128 mLastWritten.set(SystemClock.elapsedRealtime()); 1129 } 1130 1131 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1132 throws IOException { 1133 sb.setLength(0); 1134 while (true) { 1135 int ch = in.read(); 1136 if (ch == -1) { 1137 if (sb.length() == 0) { 1138 return null; 1139 } 1140 throw new IOException("Unexpected EOF"); 1141 } 1142 if (ch == endOfToken) { 1143 return sb.toString(); 1144 } 1145 sb.append((char)ch); 1146 } 1147 } 1148 1149 private AtomicFile getFile() { 1150 File dataDir = Environment.getDataDirectory(); 1151 File systemDir = new File(dataDir, "system"); 1152 File fname = new File(systemDir, "package-usage.list"); 1153 return new AtomicFile(fname); 1154 } 1155 } 1156 1157 class PackageHandler extends Handler { 1158 private boolean mBound = false; 1159 final ArrayList<HandlerParams> mPendingInstalls = 1160 new ArrayList<HandlerParams>(); 1161 1162 private boolean connectToService() { 1163 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1164 " DefaultContainerService"); 1165 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1166 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1167 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1168 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1169 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1170 mBound = true; 1171 return true; 1172 } 1173 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1174 return false; 1175 } 1176 1177 private void disconnectService() { 1178 mContainerService = null; 1179 mBound = false; 1180 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1181 mContext.unbindService(mDefContainerConn); 1182 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1183 } 1184 1185 PackageHandler(Looper looper) { 1186 super(looper); 1187 } 1188 1189 public void handleMessage(Message msg) { 1190 try { 1191 doHandleMessage(msg); 1192 } finally { 1193 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1194 } 1195 } 1196 1197 void doHandleMessage(Message msg) { 1198 switch (msg.what) { 1199 case INIT_COPY: { 1200 HandlerParams params = (HandlerParams) msg.obj; 1201 int idx = mPendingInstalls.size(); 1202 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1203 // If a bind was already initiated we dont really 1204 // need to do anything. The pending install 1205 // will be processed later on. 1206 if (!mBound) { 1207 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1208 System.identityHashCode(mHandler)); 1209 // If this is the only one pending we might 1210 // have to bind to the service again. 1211 if (!connectToService()) { 1212 Slog.e(TAG, "Failed to bind to media container service"); 1213 params.serviceError(); 1214 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1215 System.identityHashCode(mHandler)); 1216 if (params.traceMethod != null) { 1217 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1218 params.traceCookie); 1219 } 1220 return; 1221 } else { 1222 // Once we bind to the service, the first 1223 // pending request will be processed. 1224 mPendingInstalls.add(idx, params); 1225 } 1226 } else { 1227 mPendingInstalls.add(idx, params); 1228 // Already bound to the service. Just make 1229 // sure we trigger off processing the first request. 1230 if (idx == 0) { 1231 mHandler.sendEmptyMessage(MCS_BOUND); 1232 } 1233 } 1234 break; 1235 } 1236 case MCS_BOUND: { 1237 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1238 if (msg.obj != null) { 1239 mContainerService = (IMediaContainerService) msg.obj; 1240 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1241 System.identityHashCode(mHandler)); 1242 } 1243 if (mContainerService == null) { 1244 if (!mBound) { 1245 // Something seriously wrong since we are not bound and we are not 1246 // waiting for connection. Bail out. 1247 Slog.e(TAG, "Cannot bind to media container service"); 1248 for (HandlerParams params : mPendingInstalls) { 1249 // Indicate service bind error 1250 params.serviceError(); 1251 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1252 System.identityHashCode(params)); 1253 if (params.traceMethod != null) { 1254 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1255 params.traceMethod, params.traceCookie); 1256 } 1257 return; 1258 } 1259 mPendingInstalls.clear(); 1260 } else { 1261 Slog.w(TAG, "Waiting to connect to media container service"); 1262 } 1263 } else if (mPendingInstalls.size() > 0) { 1264 HandlerParams params = mPendingInstalls.get(0); 1265 if (params != null) { 1266 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1267 System.identityHashCode(params)); 1268 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1269 if (params.startCopy()) { 1270 // We are done... look for more work or to 1271 // go idle. 1272 if (DEBUG_SD_INSTALL) Log.i(TAG, 1273 "Checking for more work or unbind..."); 1274 // Delete pending install 1275 if (mPendingInstalls.size() > 0) { 1276 mPendingInstalls.remove(0); 1277 } 1278 if (mPendingInstalls.size() == 0) { 1279 if (mBound) { 1280 if (DEBUG_SD_INSTALL) Log.i(TAG, 1281 "Posting delayed MCS_UNBIND"); 1282 removeMessages(MCS_UNBIND); 1283 Message ubmsg = obtainMessage(MCS_UNBIND); 1284 // Unbind after a little delay, to avoid 1285 // continual thrashing. 1286 sendMessageDelayed(ubmsg, 10000); 1287 } 1288 } else { 1289 // There are more pending requests in queue. 1290 // Just post MCS_BOUND message to trigger processing 1291 // of next pending install. 1292 if (DEBUG_SD_INSTALL) Log.i(TAG, 1293 "Posting MCS_BOUND for next work"); 1294 mHandler.sendEmptyMessage(MCS_BOUND); 1295 } 1296 } 1297 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1298 } 1299 } else { 1300 // Should never happen ideally. 1301 Slog.w(TAG, "Empty queue"); 1302 } 1303 break; 1304 } 1305 case MCS_RECONNECT: { 1306 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1307 if (mPendingInstalls.size() > 0) { 1308 if (mBound) { 1309 disconnectService(); 1310 } 1311 if (!connectToService()) { 1312 Slog.e(TAG, "Failed to bind to media container service"); 1313 for (HandlerParams params : mPendingInstalls) { 1314 // Indicate service bind error 1315 params.serviceError(); 1316 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1317 System.identityHashCode(params)); 1318 } 1319 mPendingInstalls.clear(); 1320 } 1321 } 1322 break; 1323 } 1324 case MCS_UNBIND: { 1325 // If there is no actual work left, then time to unbind. 1326 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1327 1328 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1329 if (mBound) { 1330 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1331 1332 disconnectService(); 1333 } 1334 } else if (mPendingInstalls.size() > 0) { 1335 // There are more pending requests in queue. 1336 // Just post MCS_BOUND message to trigger processing 1337 // of next pending install. 1338 mHandler.sendEmptyMessage(MCS_BOUND); 1339 } 1340 1341 break; 1342 } 1343 case MCS_GIVE_UP: { 1344 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1345 HandlerParams params = mPendingInstalls.remove(0); 1346 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1347 System.identityHashCode(params)); 1348 break; 1349 } 1350 case SEND_PENDING_BROADCAST: { 1351 String packages[]; 1352 ArrayList<String> components[]; 1353 int size = 0; 1354 int uids[]; 1355 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1356 synchronized (mPackages) { 1357 if (mPendingBroadcasts == null) { 1358 return; 1359 } 1360 size = mPendingBroadcasts.size(); 1361 if (size <= 0) { 1362 // Nothing to be done. Just return 1363 return; 1364 } 1365 packages = new String[size]; 1366 components = new ArrayList[size]; 1367 uids = new int[size]; 1368 int i = 0; // filling out the above arrays 1369 1370 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1371 int packageUserId = mPendingBroadcasts.userIdAt(n); 1372 Iterator<Map.Entry<String, ArrayList<String>>> it 1373 = mPendingBroadcasts.packagesForUserId(packageUserId) 1374 .entrySet().iterator(); 1375 while (it.hasNext() && i < size) { 1376 Map.Entry<String, ArrayList<String>> ent = it.next(); 1377 packages[i] = ent.getKey(); 1378 components[i] = ent.getValue(); 1379 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1380 uids[i] = (ps != null) 1381 ? UserHandle.getUid(packageUserId, ps.appId) 1382 : -1; 1383 i++; 1384 } 1385 } 1386 size = i; 1387 mPendingBroadcasts.clear(); 1388 } 1389 // Send broadcasts 1390 for (int i = 0; i < size; i++) { 1391 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1392 } 1393 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1394 break; 1395 } 1396 case START_CLEANING_PACKAGE: { 1397 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1398 final String packageName = (String)msg.obj; 1399 final int userId = msg.arg1; 1400 final boolean andCode = msg.arg2 != 0; 1401 synchronized (mPackages) { 1402 if (userId == UserHandle.USER_ALL) { 1403 int[] users = sUserManager.getUserIds(); 1404 for (int user : users) { 1405 mSettings.addPackageToCleanLPw( 1406 new PackageCleanItem(user, packageName, andCode)); 1407 } 1408 } else { 1409 mSettings.addPackageToCleanLPw( 1410 new PackageCleanItem(userId, packageName, andCode)); 1411 } 1412 } 1413 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1414 startCleaningPackages(); 1415 } break; 1416 case POST_INSTALL: { 1417 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1418 1419 PostInstallData data = mRunningInstalls.get(msg.arg1); 1420 mRunningInstalls.delete(msg.arg1); 1421 1422 if (data != null) { 1423 InstallArgs args = data.args; 1424 PackageInstalledInfo parentRes = data.res; 1425 1426 final boolean grantPermissions = (args.installFlags 1427 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1428 final String[] grantedPermissions = args.installGrantPermissions; 1429 1430 // Handle the parent package 1431 handlePackagePostInstall(parentRes, grantPermissions, grantedPermissions, 1432 args.observer); 1433 1434 // Handle the child packages 1435 final int childCount = (parentRes.addedChildPackages != null) 1436 ? parentRes.addedChildPackages.size() : 0; 1437 for (int i = 0; i < childCount; i++) { 1438 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1439 handlePackagePostInstall(childRes, grantPermissions, grantedPermissions, 1440 args.observer); 1441 } 1442 1443 // Log tracing if needed 1444 if (args.traceMethod != null) { 1445 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1446 args.traceCookie); 1447 } 1448 } else { 1449 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1450 } 1451 1452 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1453 } break; 1454 case UPDATED_MEDIA_STATUS: { 1455 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1456 boolean reportStatus = msg.arg1 == 1; 1457 boolean doGc = msg.arg2 == 1; 1458 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1459 if (doGc) { 1460 // Force a gc to clear up stale containers. 1461 Runtime.getRuntime().gc(); 1462 } 1463 if (msg.obj != null) { 1464 @SuppressWarnings("unchecked") 1465 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1466 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1467 // Unload containers 1468 unloadAllContainers(args); 1469 } 1470 if (reportStatus) { 1471 try { 1472 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1473 PackageHelper.getMountService().finishMediaUpdate(); 1474 } catch (RemoteException e) { 1475 Log.e(TAG, "MountService not running?"); 1476 } 1477 } 1478 } break; 1479 case WRITE_SETTINGS: { 1480 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1481 synchronized (mPackages) { 1482 removeMessages(WRITE_SETTINGS); 1483 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1484 mSettings.writeLPr(); 1485 mDirtyUsers.clear(); 1486 } 1487 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1488 } break; 1489 case WRITE_PACKAGE_RESTRICTIONS: { 1490 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1491 synchronized (mPackages) { 1492 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1493 for (int userId : mDirtyUsers) { 1494 mSettings.writePackageRestrictionsLPr(userId); 1495 } 1496 mDirtyUsers.clear(); 1497 } 1498 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1499 } break; 1500 case CHECK_PENDING_VERIFICATION: { 1501 final int verificationId = msg.arg1; 1502 final PackageVerificationState state = mPendingVerification.get(verificationId); 1503 1504 if ((state != null) && !state.timeoutExtended()) { 1505 final InstallArgs args = state.getInstallArgs(); 1506 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1507 1508 Slog.i(TAG, "Verification timed out for " + originUri); 1509 mPendingVerification.remove(verificationId); 1510 1511 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1512 1513 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1514 Slog.i(TAG, "Continuing with installation of " + originUri); 1515 state.setVerifierResponse(Binder.getCallingUid(), 1516 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1517 broadcastPackageVerified(verificationId, originUri, 1518 PackageManager.VERIFICATION_ALLOW, 1519 state.getInstallArgs().getUser()); 1520 try { 1521 ret = args.copyApk(mContainerService, true); 1522 } catch (RemoteException e) { 1523 Slog.e(TAG, "Could not contact the ContainerService"); 1524 } 1525 } else { 1526 broadcastPackageVerified(verificationId, originUri, 1527 PackageManager.VERIFICATION_REJECT, 1528 state.getInstallArgs().getUser()); 1529 } 1530 1531 Trace.asyncTraceEnd( 1532 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1533 1534 processPendingInstall(args, ret); 1535 mHandler.sendEmptyMessage(MCS_UNBIND); 1536 } 1537 break; 1538 } 1539 case PACKAGE_VERIFIED: { 1540 final int verificationId = msg.arg1; 1541 1542 final PackageVerificationState state = mPendingVerification.get(verificationId); 1543 if (state == null) { 1544 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1545 break; 1546 } 1547 1548 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1549 1550 state.setVerifierResponse(response.callerUid, response.code); 1551 1552 if (state.isVerificationComplete()) { 1553 mPendingVerification.remove(verificationId); 1554 1555 final InstallArgs args = state.getInstallArgs(); 1556 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1557 1558 int ret; 1559 if (state.isInstallAllowed()) { 1560 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1561 broadcastPackageVerified(verificationId, originUri, 1562 response.code, state.getInstallArgs().getUser()); 1563 try { 1564 ret = args.copyApk(mContainerService, true); 1565 } catch (RemoteException e) { 1566 Slog.e(TAG, "Could not contact the ContainerService"); 1567 } 1568 } else { 1569 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1570 } 1571 1572 Trace.asyncTraceEnd( 1573 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1574 1575 processPendingInstall(args, ret); 1576 mHandler.sendEmptyMessage(MCS_UNBIND); 1577 } 1578 1579 break; 1580 } 1581 case START_INTENT_FILTER_VERIFICATIONS: { 1582 IFVerificationParams params = (IFVerificationParams) msg.obj; 1583 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1584 params.replacing, params.pkg); 1585 break; 1586 } 1587 case INTENT_FILTER_VERIFIED: { 1588 final int verificationId = msg.arg1; 1589 1590 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1591 verificationId); 1592 if (state == null) { 1593 Slog.w(TAG, "Invalid IntentFilter verification token " 1594 + verificationId + " received"); 1595 break; 1596 } 1597 1598 final int userId = state.getUserId(); 1599 1600 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1601 "Processing IntentFilter verification with token:" 1602 + verificationId + " and userId:" + userId); 1603 1604 final IntentFilterVerificationResponse response = 1605 (IntentFilterVerificationResponse) msg.obj; 1606 1607 state.setVerifierResponse(response.callerUid, response.code); 1608 1609 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1610 "IntentFilter verification with token:" + verificationId 1611 + " and userId:" + userId 1612 + " is settings verifier response with response code:" 1613 + response.code); 1614 1615 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1616 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1617 + response.getFailedDomainsString()); 1618 } 1619 1620 if (state.isVerificationComplete()) { 1621 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1622 } else { 1623 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1624 "IntentFilter verification with token:" + verificationId 1625 + " was not said to be complete"); 1626 } 1627 1628 break; 1629 } 1630 } 1631 } 1632 } 1633 1634 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1635 String[] grantedPermissions, IPackageInstallObserver2 installObserver) { 1636 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1637 // Send the removed broadcasts 1638 if (res.removedInfo != null) { 1639 res.removedInfo.sendPackageRemovedBroadcasts(); 1640 } 1641 1642 // Now that we successfully installed the package, grant runtime 1643 // permissions if requested before broadcasting the install. 1644 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1645 >= Build.VERSION_CODES.M) { 1646 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1647 } 1648 1649 final boolean update = res.removedInfo != null 1650 && res.removedInfo.removedPackage != null; 1651 1652 // If this is the first time we have child packages for a disabled privileged 1653 // app that had no children, we grant requested runtime permissions to the new 1654 // children if the parent on the system image had them already granted. 1655 if (res.pkg.parentPackage != null) { 1656 synchronized (mPackages) { 1657 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1658 } 1659 } 1660 1661 synchronized (mPackages) { 1662 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1663 } 1664 1665 final String packageName = res.pkg.applicationInfo.packageName; 1666 Bundle extras = new Bundle(1); 1667 extras.putInt(Intent.EXTRA_UID, res.uid); 1668 1669 // Determine the set of users who are adding this package for 1670 // the first time vs. those who are seeing an update. 1671 int[] firstUsers = EMPTY_INT_ARRAY; 1672 int[] updateUsers = EMPTY_INT_ARRAY; 1673 if (res.origUsers == null || res.origUsers.length == 0) { 1674 firstUsers = res.newUsers; 1675 } else { 1676 for (int newUser : res.newUsers) { 1677 boolean isNew = true; 1678 for (int origUser : res.origUsers) { 1679 if (origUser == newUser) { 1680 isNew = false; 1681 break; 1682 } 1683 } 1684 if (isNew) { 1685 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1686 } else { 1687 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1688 } 1689 } 1690 } 1691 1692 // Send installed broadcasts if the install/update is not ephemeral 1693 if (!isEphemeral(res.pkg)) { 1694 // Send added for users that see the package for the first time 1695 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1696 extras, 0 /*flags*/, null /*targetPackage*/, 1697 null /*finishedReceiver*/, firstUsers); 1698 1699 // Send added for users that don't see the package for the first time 1700 if (update) { 1701 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1702 } 1703 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1704 extras, 0 /*flags*/, null /*targetPackage*/, 1705 null /*finishedReceiver*/, updateUsers); 1706 1707 // Send replaced for users that don't see the package for the first time 1708 if (update) { 1709 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1710 packageName, extras, 0 /*flags*/, 1711 null /*targetPackage*/, null /*finishedReceiver*/, 1712 updateUsers); 1713 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1714 null /*package*/, null /*extras*/, 0 /*flags*/, 1715 packageName /*targetPackage*/, 1716 null /*finishedReceiver*/, updateUsers); 1717 } 1718 1719 // Send broadcast package appeared if forward locked/external for all users 1720 // treat asec-hosted packages like removable media on upgrade 1721 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1722 if (DEBUG_INSTALL) { 1723 Slog.i(TAG, "upgrading pkg " + res.pkg 1724 + " is ASEC-hosted -> AVAILABLE"); 1725 } 1726 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1727 ArrayList<String> pkgList = new ArrayList<>(1); 1728 pkgList.add(packageName); 1729 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1730 } 1731 } 1732 1733 // Work that needs to happen on first install within each user 1734 if (firstUsers != null && firstUsers.length > 0) { 1735 synchronized (mPackages) { 1736 for (int userId : firstUsers) { 1737 // If this app is a browser and it's newly-installed for some 1738 // users, clear any default-browser state in those users. The 1739 // app's nature doesn't depend on the user, so we can just check 1740 // its browser nature in any user and generalize. 1741 if (packageIsBrowser(packageName, userId)) { 1742 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1743 } 1744 1745 // We may also need to apply pending (restored) runtime 1746 // permission grants within these users. 1747 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1748 } 1749 } 1750 } 1751 1752 // Log current value of "unknown sources" setting 1753 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1754 getUnknownSourcesSettings()); 1755 1756 // Force a gc to clear up things 1757 Runtime.getRuntime().gc(); 1758 1759 // Remove the replaced package's older resources safely now 1760 // We delete after a gc for applications on sdcard. 1761 if (res.removedInfo != null && res.removedInfo.args != null) { 1762 synchronized (mInstallLock) { 1763 res.removedInfo.args.doPostDeleteLI(true); 1764 } 1765 } 1766 } 1767 1768 // If someone is watching installs - notify them 1769 if (installObserver != null) { 1770 try { 1771 Bundle extras = extrasForInstallResult(res); 1772 installObserver.onPackageInstalled(res.name, res.returnCode, 1773 res.returnMsg, extras); 1774 } catch (RemoteException e) { 1775 Slog.i(TAG, "Observer no longer exists."); 1776 } 1777 } 1778 } 1779 1780 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1781 PackageParser.Package pkg) { 1782 if (pkg.parentPackage == null) { 1783 return; 1784 } 1785 if (pkg.requestedPermissions == null) { 1786 return; 1787 } 1788 final PackageSetting disabledSysParentPs = mSettings 1789 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1790 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1791 || !disabledSysParentPs.isPrivileged() 1792 || (disabledSysParentPs.childPackageNames != null 1793 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1794 return; 1795 } 1796 final int[] allUserIds = sUserManager.getUserIds(); 1797 final int permCount = pkg.requestedPermissions.size(); 1798 for (int i = 0; i < permCount; i++) { 1799 String permission = pkg.requestedPermissions.get(i); 1800 BasePermission bp = mSettings.mPermissions.get(permission); 1801 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1802 continue; 1803 } 1804 for (int userId : allUserIds) { 1805 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1806 permission, userId)) { 1807 grantRuntimePermission(pkg.packageName, permission, userId); 1808 } 1809 } 1810 } 1811 } 1812 1813 private StorageEventListener mStorageListener = new StorageEventListener() { 1814 @Override 1815 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1816 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1817 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1818 final String volumeUuid = vol.getFsUuid(); 1819 1820 // Clean up any users or apps that were removed or recreated 1821 // while this volume was missing 1822 reconcileUsers(volumeUuid); 1823 reconcileApps(volumeUuid); 1824 1825 // Clean up any install sessions that expired or were 1826 // cancelled while this volume was missing 1827 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1828 1829 loadPrivatePackages(vol); 1830 1831 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1832 unloadPrivatePackages(vol); 1833 } 1834 } 1835 1836 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1837 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1838 updateExternalMediaStatus(true, false); 1839 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1840 updateExternalMediaStatus(false, false); 1841 } 1842 } 1843 } 1844 1845 @Override 1846 public void onVolumeForgotten(String fsUuid) { 1847 if (TextUtils.isEmpty(fsUuid)) { 1848 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1849 return; 1850 } 1851 1852 // Remove any apps installed on the forgotten volume 1853 synchronized (mPackages) { 1854 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1855 for (PackageSetting ps : packages) { 1856 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1857 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1858 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1859 } 1860 1861 mSettings.onVolumeForgotten(fsUuid); 1862 mSettings.writeLPr(); 1863 } 1864 } 1865 }; 1866 1867 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1868 String[] grantedPermissions) { 1869 for (int userId : userIds) { 1870 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1871 } 1872 1873 // We could have touched GID membership, so flush out packages.list 1874 synchronized (mPackages) { 1875 mSettings.writePackageListLPr(); 1876 } 1877 } 1878 1879 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1880 String[] grantedPermissions) { 1881 SettingBase sb = (SettingBase) pkg.mExtras; 1882 if (sb == null) { 1883 return; 1884 } 1885 1886 PermissionsState permissionsState = sb.getPermissionsState(); 1887 1888 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1889 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1890 1891 synchronized (mPackages) { 1892 for (String permission : pkg.requestedPermissions) { 1893 BasePermission bp = mSettings.mPermissions.get(permission); 1894 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1895 && (grantedPermissions == null 1896 || ArrayUtils.contains(grantedPermissions, permission))) { 1897 final int flags = permissionsState.getPermissionFlags(permission, userId); 1898 // Installer cannot change immutable permissions. 1899 if ((flags & immutableFlags) == 0) { 1900 grantRuntimePermission(pkg.packageName, permission, userId); 1901 } 1902 } 1903 } 1904 } 1905 } 1906 1907 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1908 Bundle extras = null; 1909 switch (res.returnCode) { 1910 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1911 extras = new Bundle(); 1912 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1913 res.origPermission); 1914 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1915 res.origPackage); 1916 break; 1917 } 1918 case PackageManager.INSTALL_SUCCEEDED: { 1919 extras = new Bundle(); 1920 extras.putBoolean(Intent.EXTRA_REPLACING, 1921 res.removedInfo != null && res.removedInfo.removedPackage != null); 1922 break; 1923 } 1924 } 1925 return extras; 1926 } 1927 1928 void scheduleWriteSettingsLocked() { 1929 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1930 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1931 } 1932 } 1933 1934 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 1935 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 1936 scheduleWritePackageRestrictionsLocked(userId); 1937 } 1938 1939 void scheduleWritePackageRestrictionsLocked(int userId) { 1940 final int[] userIds = (userId == UserHandle.USER_ALL) 1941 ? sUserManager.getUserIds() : new int[]{userId}; 1942 for (int nextUserId : userIds) { 1943 if (!sUserManager.exists(nextUserId)) return; 1944 mDirtyUsers.add(nextUserId); 1945 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1946 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1947 } 1948 } 1949 } 1950 1951 public static PackageManagerService main(Context context, Installer installer, 1952 boolean factoryTest, boolean onlyCore) { 1953 PackageManagerService m = new PackageManagerService(context, installer, 1954 factoryTest, onlyCore); 1955 m.enableSystemUserPackages(); 1956 ServiceManager.addService("package", m); 1957 return m; 1958 } 1959 1960 private void enableSystemUserPackages() { 1961 if (!UserManager.isSplitSystemUser()) { 1962 return; 1963 } 1964 // For system user, enable apps based on the following conditions: 1965 // - app is whitelisted or belong to one of these groups: 1966 // -- system app which has no launcher icons 1967 // -- system app which has INTERACT_ACROSS_USERS permission 1968 // -- system IME app 1969 // - app is not in the blacklist 1970 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 1971 Set<String> enableApps = new ArraySet<>(); 1972 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 1973 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 1974 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 1975 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 1976 enableApps.addAll(wlApps); 1977 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 1978 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 1979 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 1980 enableApps.removeAll(blApps); 1981 Log.i(TAG, "Applications installed for system user: " + enableApps); 1982 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 1983 UserHandle.SYSTEM); 1984 final int allAppsSize = allAps.size(); 1985 synchronized (mPackages) { 1986 for (int i = 0; i < allAppsSize; i++) { 1987 String pName = allAps.get(i); 1988 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 1989 // Should not happen, but we shouldn't be failing if it does 1990 if (pkgSetting == null) { 1991 continue; 1992 } 1993 boolean install = enableApps.contains(pName); 1994 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 1995 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 1996 + " for system user"); 1997 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 1998 } 1999 } 2000 } 2001 } 2002 2003 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2004 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2005 Context.DISPLAY_SERVICE); 2006 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2007 } 2008 2009 public PackageManagerService(Context context, Installer installer, 2010 boolean factoryTest, boolean onlyCore) { 2011 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2012 SystemClock.uptimeMillis()); 2013 2014 if (mSdkVersion <= 0) { 2015 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2016 } 2017 2018 mContext = context; 2019 mFactoryTest = factoryTest; 2020 mOnlyCore = onlyCore; 2021 mMetrics = new DisplayMetrics(); 2022 mSettings = new Settings(mPackages); 2023 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2024 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2025 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2026 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2027 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2028 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2029 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2030 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2031 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2032 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2033 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2034 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2035 2036 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2037 if (separateProcesses != null && separateProcesses.length() > 0) { 2038 if ("*".equals(separateProcesses)) { 2039 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2040 mSeparateProcesses = null; 2041 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2042 } else { 2043 mDefParseFlags = 0; 2044 mSeparateProcesses = separateProcesses.split(","); 2045 Slog.w(TAG, "Running with debug.separate_processes: " 2046 + separateProcesses); 2047 } 2048 } else { 2049 mDefParseFlags = 0; 2050 mSeparateProcesses = null; 2051 } 2052 2053 mInstaller = installer; 2054 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2055 "*dexopt*"); 2056 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2057 2058 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2059 FgThread.get().getLooper()); 2060 2061 getDefaultDisplayMetrics(context, mMetrics); 2062 2063 SystemConfig systemConfig = SystemConfig.getInstance(); 2064 mGlobalGids = systemConfig.getGlobalGids(); 2065 mSystemPermissions = systemConfig.getSystemPermissions(); 2066 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2067 2068 synchronized (mInstallLock) { 2069 // writer 2070 synchronized (mPackages) { 2071 mHandlerThread = new ServiceThread(TAG, 2072 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2073 mHandlerThread.start(); 2074 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2075 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2076 2077 File dataDir = Environment.getDataDirectory(); 2078 mAppInstallDir = new File(dataDir, "app"); 2079 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2080 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2081 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2082 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2083 2084 sUserManager = new UserManagerService(context, this, mPackages); 2085 2086 // Propagate permission configuration in to package manager. 2087 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2088 = systemConfig.getPermissions(); 2089 for (int i=0; i<permConfig.size(); i++) { 2090 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2091 BasePermission bp = mSettings.mPermissions.get(perm.name); 2092 if (bp == null) { 2093 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2094 mSettings.mPermissions.put(perm.name, bp); 2095 } 2096 if (perm.gids != null) { 2097 bp.setGids(perm.gids, perm.perUser); 2098 } 2099 } 2100 2101 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2102 for (int i=0; i<libConfig.size(); i++) { 2103 mSharedLibraries.put(libConfig.keyAt(i), 2104 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2105 } 2106 2107 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2108 2109 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2110 2111 String customResolverActivity = Resources.getSystem().getString( 2112 R.string.config_customResolverActivity); 2113 if (TextUtils.isEmpty(customResolverActivity)) { 2114 customResolverActivity = null; 2115 } else { 2116 mCustomResolverComponentName = ComponentName.unflattenFromString( 2117 customResolverActivity); 2118 } 2119 2120 long startTime = SystemClock.uptimeMillis(); 2121 2122 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2123 startTime); 2124 2125 // Set flag to monitor and not change apk file paths when 2126 // scanning install directories. 2127 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2128 2129 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2130 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2131 2132 if (bootClassPath == null) { 2133 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2134 } 2135 2136 if (systemServerClassPath == null) { 2137 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2138 } 2139 2140 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2141 final String[] dexCodeInstructionSets = 2142 getDexCodeInstructionSets( 2143 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2144 2145 /** 2146 * Ensure all external libraries have had dexopt run on them. 2147 */ 2148 if (mSharedLibraries.size() > 0) { 2149 // NOTE: For now, we're compiling these system "shared libraries" 2150 // (and framework jars) into all available architectures. It's possible 2151 // to compile them only when we come across an app that uses them (there's 2152 // already logic for that in scanPackageLI) but that adds some complexity. 2153 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2154 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2155 final String lib = libEntry.path; 2156 if (lib == null) { 2157 continue; 2158 } 2159 2160 try { 2161 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 2162 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2163 // Shared libraries do not have profiles so we perform a full 2164 // AOT compilation. 2165 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2166 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2167 StorageManager.UUID_PRIVATE_INTERNAL, 2168 false /*useProfiles*/); 2169 } 2170 } catch (FileNotFoundException e) { 2171 Slog.w(TAG, "Library not found: " + lib); 2172 } catch (IOException | InstallerException e) { 2173 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2174 + e.getMessage()); 2175 } 2176 } 2177 } 2178 } 2179 2180 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2181 2182 final VersionInfo ver = mSettings.getInternalVersion(); 2183 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2184 // when upgrading from pre-M, promote system app permissions from install to runtime 2185 mPromoteSystemApps = 2186 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2187 2188 // save off the names of pre-existing system packages prior to scanning; we don't 2189 // want to automatically grant runtime permissions for new system apps 2190 if (mPromoteSystemApps) { 2191 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2192 while (pkgSettingIter.hasNext()) { 2193 PackageSetting ps = pkgSettingIter.next(); 2194 if (isSystemApp(ps)) { 2195 mExistingSystemPackages.add(ps.name); 2196 } 2197 } 2198 } 2199 2200 // Collect vendor overlay packages. 2201 // (Do this before scanning any apps.) 2202 // For security and version matching reason, only consider 2203 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2204 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2205 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2206 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2207 2208 // Find base frameworks (resource packages without code). 2209 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2210 | PackageParser.PARSE_IS_SYSTEM_DIR 2211 | PackageParser.PARSE_IS_PRIVILEGED, 2212 scanFlags | SCAN_NO_DEX, 0); 2213 2214 // Collected privileged system packages. 2215 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2216 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2217 | PackageParser.PARSE_IS_SYSTEM_DIR 2218 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2219 2220 // Collect ordinary system packages. 2221 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2222 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2223 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2224 2225 // Collect all vendor packages. 2226 File vendorAppDir = new File("/vendor/app"); 2227 try { 2228 vendorAppDir = vendorAppDir.getCanonicalFile(); 2229 } catch (IOException e) { 2230 // failed to look up canonical path, continue with original one 2231 } 2232 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2233 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2234 2235 // Collect all OEM packages. 2236 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2237 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2238 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2239 2240 // Prune any system packages that no longer exist. 2241 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2242 if (!mOnlyCore) { 2243 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2244 while (psit.hasNext()) { 2245 PackageSetting ps = psit.next(); 2246 2247 /* 2248 * If this is not a system app, it can't be a 2249 * disable system app. 2250 */ 2251 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2252 continue; 2253 } 2254 2255 /* 2256 * If the package is scanned, it's not erased. 2257 */ 2258 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2259 if (scannedPkg != null) { 2260 /* 2261 * If the system app is both scanned and in the 2262 * disabled packages list, then it must have been 2263 * added via OTA. Remove it from the currently 2264 * scanned package so the previously user-installed 2265 * application can be scanned. 2266 */ 2267 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2268 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2269 + ps.name + "; removing system app. Last known codePath=" 2270 + ps.codePathString + ", installStatus=" + ps.installStatus 2271 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2272 + scannedPkg.mVersionCode); 2273 removePackageLI(scannedPkg, true); 2274 mExpectingBetter.put(ps.name, ps.codePath); 2275 } 2276 2277 continue; 2278 } 2279 2280 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2281 psit.remove(); 2282 logCriticalInfo(Log.WARN, "System package " + ps.name 2283 + " no longer exists; wiping its data"); 2284 removeDataDirsLI(null, ps.name); 2285 } else { 2286 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2287 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2288 possiblyDeletedUpdatedSystemApps.add(ps.name); 2289 } 2290 } 2291 } 2292 } 2293 2294 //look for any incomplete package installations 2295 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2296 //clean up list 2297 for(int i = 0; i < deletePkgsList.size(); i++) { 2298 //clean up here 2299 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2300 } 2301 //delete tmp files 2302 deleteTempPackageFiles(); 2303 2304 // Remove any shared userIDs that have no associated packages 2305 mSettings.pruneSharedUsersLPw(); 2306 2307 if (!mOnlyCore) { 2308 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2309 SystemClock.uptimeMillis()); 2310 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2311 2312 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2313 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2314 2315 scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL, 2316 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2317 2318 /** 2319 * Remove disable package settings for any updated system 2320 * apps that were removed via an OTA. If they're not a 2321 * previously-updated app, remove them completely. 2322 * Otherwise, just revoke their system-level permissions. 2323 */ 2324 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2325 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2326 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2327 2328 String msg; 2329 if (deletedPkg == null) { 2330 msg = "Updated system package " + deletedAppName 2331 + " no longer exists; wiping its data"; 2332 removeDataDirsLI(null, deletedAppName); 2333 } else { 2334 msg = "Updated system app + " + deletedAppName 2335 + " no longer present; removing system privileges for " 2336 + deletedAppName; 2337 2338 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2339 2340 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2341 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2342 } 2343 logCriticalInfo(Log.WARN, msg); 2344 } 2345 2346 /** 2347 * Make sure all system apps that we expected to appear on 2348 * the userdata partition actually showed up. If they never 2349 * appeared, crawl back and revive the system version. 2350 */ 2351 for (int i = 0; i < mExpectingBetter.size(); i++) { 2352 final String packageName = mExpectingBetter.keyAt(i); 2353 if (!mPackages.containsKey(packageName)) { 2354 final File scanFile = mExpectingBetter.valueAt(i); 2355 2356 logCriticalInfo(Log.WARN, "Expected better " + packageName 2357 + " but never showed up; reverting to system"); 2358 2359 final int reparseFlags; 2360 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2361 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2362 | PackageParser.PARSE_IS_SYSTEM_DIR 2363 | PackageParser.PARSE_IS_PRIVILEGED; 2364 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2365 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2366 | PackageParser.PARSE_IS_SYSTEM_DIR; 2367 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2368 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2369 | PackageParser.PARSE_IS_SYSTEM_DIR; 2370 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2371 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2372 | PackageParser.PARSE_IS_SYSTEM_DIR; 2373 } else { 2374 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2375 continue; 2376 } 2377 2378 mSettings.enableSystemPackageLPw(packageName); 2379 2380 try { 2381 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2382 } catch (PackageManagerException e) { 2383 Slog.e(TAG, "Failed to parse original system package: " 2384 + e.getMessage()); 2385 } 2386 } 2387 } 2388 } 2389 mExpectingBetter.clear(); 2390 2391 // Now that we know all of the shared libraries, update all clients to have 2392 // the correct library paths. 2393 updateAllSharedLibrariesLPw(); 2394 2395 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2396 // NOTE: We ignore potential failures here during a system scan (like 2397 // the rest of the commands above) because there's precious little we 2398 // can do about it. A settings error is reported, though. 2399 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2400 false /* boot complete */); 2401 } 2402 2403 // Now that we know all the packages we are keeping, 2404 // read and update their last usage times. 2405 mPackageUsage.readLP(); 2406 2407 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2408 SystemClock.uptimeMillis()); 2409 Slog.i(TAG, "Time to scan packages: " 2410 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2411 + " seconds"); 2412 2413 // If the platform SDK has changed since the last time we booted, 2414 // we need to re-grant app permission to catch any new ones that 2415 // appear. This is really a hack, and means that apps can in some 2416 // cases get permissions that the user didn't initially explicitly 2417 // allow... it would be nice to have some better way to handle 2418 // this situation. 2419 int updateFlags = UPDATE_PERMISSIONS_ALL; 2420 if (ver.sdkVersion != mSdkVersion) { 2421 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2422 + mSdkVersion + "; regranting permissions for internal storage"); 2423 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2424 } 2425 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2426 ver.sdkVersion = mSdkVersion; 2427 2428 // If this is the first boot or an update from pre-M, and it is a normal 2429 // boot, then we need to initialize the default preferred apps across 2430 // all defined users. 2431 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2432 for (UserInfo user : sUserManager.getUsers(true)) { 2433 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2434 applyFactoryDefaultBrowserLPw(user.id); 2435 primeDomainVerificationsLPw(user.id); 2436 } 2437 } 2438 2439 // Prepare storage for system user really early during boot, 2440 // since core system apps like SettingsProvider and SystemUI 2441 // can't wait for user to start 2442 final int storageFlags; 2443 if (StorageManager.isFileBasedEncryptionEnabled()) { 2444 storageFlags = StorageManager.FLAG_STORAGE_DE; 2445 } else { 2446 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2447 } 2448 reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2449 storageFlags); 2450 2451 if (!StorageManager.isFileBasedEncryptionEnabled() 2452 && PackageManager.APPLY_FORCE_DEVICE_ENCRYPTED) { 2453 // When upgrading a non-FBE device, we might need to shuffle 2454 // around the default storage location of system apps 2455 final List<UserInfo> users = sUserManager.getUsers(true); 2456 for (PackageSetting ps : mSettings.mPackages.values()) { 2457 if (ps.pkg == null || !ps.isSystem()) continue; 2458 final int storageTarget = ps.pkg.applicationInfo.isForceDeviceEncrypted() 2459 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 2460 for (UserInfo user : users) { 2461 if (ps.getInstalled(user.id)) { 2462 try { 2463 mInstaller.migrateAppData(StorageManager.UUID_PRIVATE_INTERNAL, 2464 ps.name, user.id, storageTarget); 2465 } catch (InstallerException e) { 2466 logCriticalInfo(Log.WARN, 2467 "Failed to migrate " + ps.name + ": " + e.getMessage()); 2468 } 2469 // We may have just shuffled around app data 2470 // directories, so prepare it one more time 2471 prepareAppData(StorageManager.UUID_PRIVATE_INTERNAL, user.id, 2472 storageFlags, ps.pkg, false); 2473 } 2474 } 2475 } 2476 } 2477 2478 // If this is first boot after an OTA, and a normal boot, then 2479 // we need to clear code cache directories. 2480 if (mIsUpgrade && !onlyCore) { 2481 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2482 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2483 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2484 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2485 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2486 } 2487 } 2488 ver.fingerprint = Build.FINGERPRINT; 2489 } 2490 2491 checkDefaultBrowser(); 2492 2493 // clear only after permissions and other defaults have been updated 2494 mExistingSystemPackages.clear(); 2495 mPromoteSystemApps = false; 2496 2497 // All the changes are done during package scanning. 2498 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2499 2500 // can downgrade to reader 2501 mSettings.writeLPr(); 2502 2503 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2504 SystemClock.uptimeMillis()); 2505 2506 if (!mOnlyCore) { 2507 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2508 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2509 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2510 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2511 mIntentFilterVerifierComponent); 2512 } else { 2513 mRequiredVerifierPackage = null; 2514 mRequiredInstallerPackage = null; 2515 mIntentFilterVerifierComponent = null; 2516 mIntentFilterVerifier = null; 2517 } 2518 2519 mInstallerService = new PackageInstallerService(context, this); 2520 2521 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2522 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2523 // both the installer and resolver must be present to enable ephemeral 2524 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2525 if (DEBUG_EPHEMERAL) { 2526 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2527 + " installer:" + ephemeralInstallerComponent); 2528 } 2529 mEphemeralResolverComponent = ephemeralResolverComponent; 2530 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2531 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2532 mEphemeralResolverConnection = 2533 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2534 } else { 2535 if (DEBUG_EPHEMERAL) { 2536 final String missingComponent = 2537 (ephemeralResolverComponent == null) 2538 ? (ephemeralInstallerComponent == null) 2539 ? "resolver and installer" 2540 : "resolver" 2541 : "installer"; 2542 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2543 } 2544 mEphemeralResolverComponent = null; 2545 mEphemeralInstallerComponent = null; 2546 mEphemeralResolverConnection = null; 2547 } 2548 2549 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2550 } // synchronized (mPackages) 2551 } // synchronized (mInstallLock) 2552 2553 // Now after opening every single application zip, make sure they 2554 // are all flushed. Not really needed, but keeps things nice and 2555 // tidy. 2556 Runtime.getRuntime().gc(); 2557 2558 // The initial scanning above does many calls into installd while 2559 // holding the mPackages lock, but we're mostly interested in yelling 2560 // once we have a booted system. 2561 mInstaller.setWarnIfHeld(mPackages); 2562 2563 // Expose private service for system components to use. 2564 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2565 } 2566 2567 @Override 2568 public boolean isFirstBoot() { 2569 return !mRestoredSettings; 2570 } 2571 2572 @Override 2573 public boolean isOnlyCoreApps() { 2574 return mOnlyCore; 2575 } 2576 2577 @Override 2578 public boolean isUpgrade() { 2579 return mIsUpgrade; 2580 } 2581 2582 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2583 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2584 2585 final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE, 2586 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2587 if (matches.size() == 1) { 2588 return matches.get(0).getComponentInfo().packageName; 2589 } else { 2590 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2591 return null; 2592 } 2593 } 2594 2595 private @NonNull String getRequiredInstallerLPr() { 2596 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2597 intent.addCategory(Intent.CATEGORY_DEFAULT); 2598 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2599 2600 final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE, 2601 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2602 if (matches.size() == 1) { 2603 return matches.get(0).getComponentInfo().packageName; 2604 } else { 2605 throw new RuntimeException("There must be exactly one installer; found " + matches); 2606 } 2607 } 2608 2609 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2610 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2611 2612 final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE, 2613 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2614 ResolveInfo best = null; 2615 final int N = matches.size(); 2616 for (int i = 0; i < N; i++) { 2617 final ResolveInfo cur = matches.get(i); 2618 final String packageName = cur.getComponentInfo().packageName; 2619 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2620 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2621 continue; 2622 } 2623 2624 if (best == null || cur.priority > best.priority) { 2625 best = cur; 2626 } 2627 } 2628 2629 if (best != null) { 2630 return best.getComponentInfo().getComponentName(); 2631 } else { 2632 throw new RuntimeException("There must be at least one intent filter verifier"); 2633 } 2634 } 2635 2636 private @Nullable ComponentName getEphemeralResolverLPr() { 2637 final String[] packageArray = 2638 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2639 if (packageArray.length == 0) { 2640 if (DEBUG_EPHEMERAL) { 2641 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2642 } 2643 return null; 2644 } 2645 2646 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2647 final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, null, 2648 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2649 2650 final int N = resolvers.size(); 2651 if (N == 0) { 2652 if (DEBUG_EPHEMERAL) { 2653 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2654 } 2655 return null; 2656 } 2657 2658 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2659 for (int i = 0; i < N; i++) { 2660 final ResolveInfo info = resolvers.get(i); 2661 2662 if (info.serviceInfo == null) { 2663 continue; 2664 } 2665 2666 final String packageName = info.serviceInfo.packageName; 2667 if (!possiblePackages.contains(packageName)) { 2668 if (DEBUG_EPHEMERAL) { 2669 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2670 + " pkg: " + packageName + ", info:" + info); 2671 } 2672 continue; 2673 } 2674 2675 if (DEBUG_EPHEMERAL) { 2676 Slog.v(TAG, "Ephemeral resolver found;" 2677 + " pkg: " + packageName + ", info:" + info); 2678 } 2679 return new ComponentName(packageName, info.serviceInfo.name); 2680 } 2681 if (DEBUG_EPHEMERAL) { 2682 Slog.v(TAG, "Ephemeral resolver NOT found"); 2683 } 2684 return null; 2685 } 2686 2687 private @Nullable ComponentName getEphemeralInstallerLPr() { 2688 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2689 intent.addCategory(Intent.CATEGORY_DEFAULT); 2690 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2691 2692 final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE, 2693 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2694 if (matches.size() == 0) { 2695 return null; 2696 } else if (matches.size() == 1) { 2697 return matches.get(0).getComponentInfo().getComponentName(); 2698 } else { 2699 throw new RuntimeException( 2700 "There must be at most one ephemeral installer; found " + matches); 2701 } 2702 } 2703 2704 private void primeDomainVerificationsLPw(int userId) { 2705 if (DEBUG_DOMAIN_VERIFICATION) { 2706 Slog.d(TAG, "Priming domain verifications in user " + userId); 2707 } 2708 2709 SystemConfig systemConfig = SystemConfig.getInstance(); 2710 ArraySet<String> packages = systemConfig.getLinkedApps(); 2711 ArraySet<String> domains = new ArraySet<String>(); 2712 2713 for (String packageName : packages) { 2714 PackageParser.Package pkg = mPackages.get(packageName); 2715 if (pkg != null) { 2716 if (!pkg.isSystemApp()) { 2717 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2718 continue; 2719 } 2720 2721 domains.clear(); 2722 for (PackageParser.Activity a : pkg.activities) { 2723 for (ActivityIntentInfo filter : a.intents) { 2724 if (hasValidDomains(filter)) { 2725 domains.addAll(filter.getHostsList()); 2726 } 2727 } 2728 } 2729 2730 if (domains.size() > 0) { 2731 if (DEBUG_DOMAIN_VERIFICATION) { 2732 Slog.v(TAG, " + " + packageName); 2733 } 2734 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2735 // state w.r.t. the formal app-linkage "no verification attempted" state; 2736 // and then 'always' in the per-user state actually used for intent resolution. 2737 final IntentFilterVerificationInfo ivi; 2738 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2739 new ArrayList<String>(domains)); 2740 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2741 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2742 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2743 } else { 2744 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2745 + "' does not handle web links"); 2746 } 2747 } else { 2748 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2749 } 2750 } 2751 2752 scheduleWritePackageRestrictionsLocked(userId); 2753 scheduleWriteSettingsLocked(); 2754 } 2755 2756 private void applyFactoryDefaultBrowserLPw(int userId) { 2757 // The default browser app's package name is stored in a string resource, 2758 // with a product-specific overlay used for vendor customization. 2759 String browserPkg = mContext.getResources().getString( 2760 com.android.internal.R.string.default_browser); 2761 if (!TextUtils.isEmpty(browserPkg)) { 2762 // non-empty string => required to be a known package 2763 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2764 if (ps == null) { 2765 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2766 browserPkg = null; 2767 } else { 2768 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2769 } 2770 } 2771 2772 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2773 // default. If there's more than one, just leave everything alone. 2774 if (browserPkg == null) { 2775 calculateDefaultBrowserLPw(userId); 2776 } 2777 } 2778 2779 private void calculateDefaultBrowserLPw(int userId) { 2780 List<String> allBrowsers = resolveAllBrowserApps(userId); 2781 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2782 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2783 } 2784 2785 private List<String> resolveAllBrowserApps(int userId) { 2786 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2787 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2788 PackageManager.MATCH_ALL, userId); 2789 2790 final int count = list.size(); 2791 List<String> result = new ArrayList<String>(count); 2792 for (int i=0; i<count; i++) { 2793 ResolveInfo info = list.get(i); 2794 if (info.activityInfo == null 2795 || !info.handleAllWebDataURI 2796 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2797 || result.contains(info.activityInfo.packageName)) { 2798 continue; 2799 } 2800 result.add(info.activityInfo.packageName); 2801 } 2802 2803 return result; 2804 } 2805 2806 private boolean packageIsBrowser(String packageName, int userId) { 2807 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2808 PackageManager.MATCH_ALL, userId); 2809 final int N = list.size(); 2810 for (int i = 0; i < N; i++) { 2811 ResolveInfo info = list.get(i); 2812 if (packageName.equals(info.activityInfo.packageName)) { 2813 return true; 2814 } 2815 } 2816 return false; 2817 } 2818 2819 private void checkDefaultBrowser() { 2820 final int myUserId = UserHandle.myUserId(); 2821 final String packageName = getDefaultBrowserPackageName(myUserId); 2822 if (packageName != null) { 2823 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2824 if (info == null) { 2825 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2826 synchronized (mPackages) { 2827 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2828 } 2829 } 2830 } 2831 } 2832 2833 @Override 2834 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2835 throws RemoteException { 2836 try { 2837 return super.onTransact(code, data, reply, flags); 2838 } catch (RuntimeException e) { 2839 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2840 Slog.wtf(TAG, "Package Manager Crash", e); 2841 } 2842 throw e; 2843 } 2844 } 2845 2846 void cleanupInstallFailedPackage(PackageSetting ps) { 2847 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2848 2849 removeDataDirsLI(ps.volumeUuid, ps.name); 2850 if (ps.codePath != null) { 2851 removeCodePathLI(ps.codePath); 2852 } 2853 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2854 if (ps.resourcePath.isDirectory()) { 2855 FileUtils.deleteContents(ps.resourcePath); 2856 } 2857 ps.resourcePath.delete(); 2858 } 2859 mSettings.removePackageLPw(ps.name); 2860 } 2861 2862 static int[] appendInts(int[] cur, int[] add) { 2863 if (add == null) return cur; 2864 if (cur == null) return add; 2865 final int N = add.length; 2866 for (int i=0; i<N; i++) { 2867 cur = appendInt(cur, add[i]); 2868 } 2869 return cur; 2870 } 2871 2872 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2873 if (!sUserManager.exists(userId)) return null; 2874 final PackageSetting ps = (PackageSetting) p.mExtras; 2875 if (ps == null) { 2876 return null; 2877 } 2878 2879 final PermissionsState permissionsState = ps.getPermissionsState(); 2880 2881 final int[] gids = permissionsState.computeGids(userId); 2882 final Set<String> permissions = permissionsState.getPermissions(userId); 2883 final PackageUserState state = ps.readUserState(userId); 2884 2885 return PackageParser.generatePackageInfo(p, gids, flags, 2886 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2887 } 2888 2889 @Override 2890 public void checkPackageStartable(String packageName, int userId) { 2891 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 2892 2893 synchronized (mPackages) { 2894 final PackageSetting ps = mSettings.mPackages.get(packageName); 2895 if (ps == null) { 2896 throw new SecurityException("Package " + packageName + " was not found!"); 2897 } 2898 2899 if (mSafeMode && !ps.isSystem()) { 2900 throw new SecurityException("Package " + packageName + " not a system app!"); 2901 } 2902 2903 if (ps.frozen) { 2904 throw new SecurityException("Package " + packageName + " is currently frozen!"); 2905 } 2906 2907 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware() 2908 || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) { 2909 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 2910 } 2911 } 2912 } 2913 2914 @Override 2915 public boolean isPackageAvailable(String packageName, int userId) { 2916 if (!sUserManager.exists(userId)) return false; 2917 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2918 synchronized (mPackages) { 2919 PackageParser.Package p = mPackages.get(packageName); 2920 if (p != null) { 2921 final PackageSetting ps = (PackageSetting) p.mExtras; 2922 if (ps != null) { 2923 final PackageUserState state = ps.readUserState(userId); 2924 if (state != null) { 2925 return PackageParser.isAvailable(state); 2926 } 2927 } 2928 } 2929 } 2930 return false; 2931 } 2932 2933 @Override 2934 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2935 if (!sUserManager.exists(userId)) return null; 2936 flags = updateFlagsForPackage(flags, userId, packageName); 2937 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2938 // reader 2939 synchronized (mPackages) { 2940 PackageParser.Package p = mPackages.get(packageName); 2941 if (DEBUG_PACKAGE_INFO) 2942 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2943 if (p != null) { 2944 return generatePackageInfo(p, flags, userId); 2945 } 2946 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2947 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2948 } 2949 } 2950 return null; 2951 } 2952 2953 @Override 2954 public String[] currentToCanonicalPackageNames(String[] names) { 2955 String[] out = new String[names.length]; 2956 // reader 2957 synchronized (mPackages) { 2958 for (int i=names.length-1; i>=0; i--) { 2959 PackageSetting ps = mSettings.mPackages.get(names[i]); 2960 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2961 } 2962 } 2963 return out; 2964 } 2965 2966 @Override 2967 public String[] canonicalToCurrentPackageNames(String[] names) { 2968 String[] out = new String[names.length]; 2969 // reader 2970 synchronized (mPackages) { 2971 for (int i=names.length-1; i>=0; i--) { 2972 String cur = mSettings.mRenamedPackages.get(names[i]); 2973 out[i] = cur != null ? cur : names[i]; 2974 } 2975 } 2976 return out; 2977 } 2978 2979 @Override 2980 public int getPackageUid(String packageName, int flags, int userId) { 2981 if (!sUserManager.exists(userId)) return -1; 2982 flags = updateFlagsForPackage(flags, userId, packageName); 2983 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2984 2985 // reader 2986 synchronized (mPackages) { 2987 final PackageParser.Package p = mPackages.get(packageName); 2988 if (p != null && p.isMatch(flags)) { 2989 return UserHandle.getUid(userId, p.applicationInfo.uid); 2990 } 2991 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2992 final PackageSetting ps = mSettings.mPackages.get(packageName); 2993 if (ps != null && ps.isMatch(flags)) { 2994 return UserHandle.getUid(userId, ps.appId); 2995 } 2996 } 2997 } 2998 2999 return -1; 3000 } 3001 3002 @Override 3003 public int[] getPackageGids(String packageName, int flags, int userId) { 3004 if (!sUserManager.exists(userId)) return null; 3005 flags = updateFlagsForPackage(flags, userId, packageName); 3006 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 3007 "getPackageGids"); 3008 3009 // reader 3010 synchronized (mPackages) { 3011 final PackageParser.Package p = mPackages.get(packageName); 3012 if (p != null && p.isMatch(flags)) { 3013 PackageSetting ps = (PackageSetting) p.mExtras; 3014 return ps.getPermissionsState().computeGids(userId); 3015 } 3016 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3017 final PackageSetting ps = mSettings.mPackages.get(packageName); 3018 if (ps != null && ps.isMatch(flags)) { 3019 return ps.getPermissionsState().computeGids(userId); 3020 } 3021 } 3022 } 3023 3024 return null; 3025 } 3026 3027 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3028 if (bp.perm != null) { 3029 return PackageParser.generatePermissionInfo(bp.perm, flags); 3030 } 3031 PermissionInfo pi = new PermissionInfo(); 3032 pi.name = bp.name; 3033 pi.packageName = bp.sourcePackage; 3034 pi.nonLocalizedLabel = bp.name; 3035 pi.protectionLevel = bp.protectionLevel; 3036 return pi; 3037 } 3038 3039 @Override 3040 public PermissionInfo getPermissionInfo(String name, int flags) { 3041 // reader 3042 synchronized (mPackages) { 3043 final BasePermission p = mSettings.mPermissions.get(name); 3044 if (p != null) { 3045 return generatePermissionInfo(p, flags); 3046 } 3047 return null; 3048 } 3049 } 3050 3051 @Override 3052 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 3053 // reader 3054 synchronized (mPackages) { 3055 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3056 for (BasePermission p : mSettings.mPermissions.values()) { 3057 if (group == null) { 3058 if (p.perm == null || p.perm.info.group == null) { 3059 out.add(generatePermissionInfo(p, flags)); 3060 } 3061 } else { 3062 if (p.perm != null && group.equals(p.perm.info.group)) { 3063 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3064 } 3065 } 3066 } 3067 3068 if (out.size() > 0) { 3069 return out; 3070 } 3071 return mPermissionGroups.containsKey(group) ? out : null; 3072 } 3073 } 3074 3075 @Override 3076 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3077 // reader 3078 synchronized (mPackages) { 3079 return PackageParser.generatePermissionGroupInfo( 3080 mPermissionGroups.get(name), flags); 3081 } 3082 } 3083 3084 @Override 3085 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3086 // reader 3087 synchronized (mPackages) { 3088 final int N = mPermissionGroups.size(); 3089 ArrayList<PermissionGroupInfo> out 3090 = new ArrayList<PermissionGroupInfo>(N); 3091 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3092 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3093 } 3094 return out; 3095 } 3096 } 3097 3098 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3099 int userId) { 3100 if (!sUserManager.exists(userId)) return null; 3101 PackageSetting ps = mSettings.mPackages.get(packageName); 3102 if (ps != null) { 3103 if (ps.pkg == null) { 3104 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 3105 flags, userId); 3106 if (pInfo != null) { 3107 return pInfo.applicationInfo; 3108 } 3109 return null; 3110 } 3111 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3112 ps.readUserState(userId), userId); 3113 } 3114 return null; 3115 } 3116 3117 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 3118 int userId) { 3119 if (!sUserManager.exists(userId)) return null; 3120 PackageSetting ps = mSettings.mPackages.get(packageName); 3121 if (ps != null) { 3122 PackageParser.Package pkg = ps.pkg; 3123 if (pkg == null) { 3124 if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) { 3125 return null; 3126 } 3127 // Only data remains, so we aren't worried about code paths 3128 pkg = new PackageParser.Package(packageName); 3129 pkg.applicationInfo.packageName = packageName; 3130 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 3131 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 3132 pkg.applicationInfo.uid = ps.appId; 3133 pkg.applicationInfo.initForUser(userId); 3134 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 3135 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 3136 } 3137 return generatePackageInfo(pkg, flags, userId); 3138 } 3139 return null; 3140 } 3141 3142 @Override 3143 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3144 if (!sUserManager.exists(userId)) return null; 3145 flags = updateFlagsForApplication(flags, userId, packageName); 3146 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 3147 // writer 3148 synchronized (mPackages) { 3149 PackageParser.Package p = mPackages.get(packageName); 3150 if (DEBUG_PACKAGE_INFO) Log.v( 3151 TAG, "getApplicationInfo " + packageName 3152 + ": " + p); 3153 if (p != null) { 3154 PackageSetting ps = mSettings.mPackages.get(packageName); 3155 if (ps == null) return null; 3156 // Note: isEnabledLP() does not apply here - always return info 3157 return PackageParser.generateApplicationInfo( 3158 p, flags, ps.readUserState(userId), userId); 3159 } 3160 if ("android".equals(packageName)||"system".equals(packageName)) { 3161 return mAndroidApplication; 3162 } 3163 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3164 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3165 } 3166 } 3167 return null; 3168 } 3169 3170 @Override 3171 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3172 final IPackageDataObserver observer) { 3173 mContext.enforceCallingOrSelfPermission( 3174 android.Manifest.permission.CLEAR_APP_CACHE, null); 3175 // Queue up an async operation since clearing cache may take a little while. 3176 mHandler.post(new Runnable() { 3177 public void run() { 3178 mHandler.removeCallbacks(this); 3179 boolean success = true; 3180 synchronized (mInstallLock) { 3181 try { 3182 mInstaller.freeCache(volumeUuid, freeStorageSize); 3183 } catch (InstallerException e) { 3184 Slog.w(TAG, "Couldn't clear application caches: " + e); 3185 success = false; 3186 } 3187 } 3188 if (observer != null) { 3189 try { 3190 observer.onRemoveCompleted(null, success); 3191 } catch (RemoteException e) { 3192 Slog.w(TAG, "RemoveException when invoking call back"); 3193 } 3194 } 3195 } 3196 }); 3197 } 3198 3199 @Override 3200 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3201 final IntentSender pi) { 3202 mContext.enforceCallingOrSelfPermission( 3203 android.Manifest.permission.CLEAR_APP_CACHE, null); 3204 // Queue up an async operation since clearing cache may take a little while. 3205 mHandler.post(new Runnable() { 3206 public void run() { 3207 mHandler.removeCallbacks(this); 3208 boolean success = true; 3209 synchronized (mInstallLock) { 3210 try { 3211 mInstaller.freeCache(volumeUuid, freeStorageSize); 3212 } catch (InstallerException e) { 3213 Slog.w(TAG, "Couldn't clear application caches: " + e); 3214 success = false; 3215 } 3216 } 3217 if(pi != null) { 3218 try { 3219 // Callback via pending intent 3220 int code = success ? 1 : 0; 3221 pi.sendIntent(null, code, null, 3222 null, null); 3223 } catch (SendIntentException e1) { 3224 Slog.i(TAG, "Failed to send pending intent"); 3225 } 3226 } 3227 } 3228 }); 3229 } 3230 3231 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3232 synchronized (mInstallLock) { 3233 try { 3234 mInstaller.freeCache(volumeUuid, freeStorageSize); 3235 } catch (InstallerException e) { 3236 throw new IOException("Failed to free enough space", e); 3237 } 3238 } 3239 } 3240 3241 /** 3242 * Return if the user key is currently unlocked. 3243 */ 3244 private boolean isUserKeyUnlocked(int userId) { 3245 if (StorageManager.isFileBasedEncryptionEnabled()) { 3246 final IMountService mount = IMountService.Stub 3247 .asInterface(ServiceManager.getService("mount")); 3248 if (mount == null) { 3249 Slog.w(TAG, "Early during boot, assuming locked"); 3250 return false; 3251 } 3252 final long token = Binder.clearCallingIdentity(); 3253 try { 3254 return mount.isUserKeyUnlocked(userId); 3255 } catch (RemoteException e) { 3256 throw e.rethrowAsRuntimeException(); 3257 } finally { 3258 Binder.restoreCallingIdentity(token); 3259 } 3260 } else { 3261 return true; 3262 } 3263 } 3264 3265 /** 3266 * Update given flags based on encryption status of current user. 3267 */ 3268 private int updateFlags(int flags, int userId) { 3269 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3270 | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) { 3271 // Caller expressed an explicit opinion about what encryption 3272 // aware/unaware components they want to see, so fall through and 3273 // give them what they want 3274 } else { 3275 // Caller expressed no opinion, so match based on user state 3276 if (isUserKeyUnlocked(userId)) { 3277 flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE; 3278 } else { 3279 flags |= PackageManager.MATCH_ENCRYPTION_AWARE; 3280 } 3281 } 3282 return flags; 3283 } 3284 3285 /** 3286 * Update given flags when being used to request {@link PackageInfo}. 3287 */ 3288 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3289 boolean triaged = true; 3290 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3291 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3292 // Caller is asking for component details, so they'd better be 3293 // asking for specific encryption matching behavior, or be triaged 3294 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3295 | PackageManager.MATCH_ENCRYPTION_AWARE 3296 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3297 triaged = false; 3298 } 3299 } 3300 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3301 | PackageManager.MATCH_SYSTEM_ONLY 3302 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3303 triaged = false; 3304 } 3305 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3306 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3307 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3308 } 3309 return updateFlags(flags, userId); 3310 } 3311 3312 /** 3313 * Update given flags when being used to request {@link ApplicationInfo}. 3314 */ 3315 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3316 return updateFlagsForPackage(flags, userId, cookie); 3317 } 3318 3319 /** 3320 * Update given flags when being used to request {@link ComponentInfo}. 3321 */ 3322 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3323 if (cookie instanceof Intent) { 3324 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3325 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3326 } 3327 } 3328 3329 boolean triaged = true; 3330 // Caller is asking for component details, so they'd better be 3331 // asking for specific encryption matching behavior, or be triaged 3332 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3333 | PackageManager.MATCH_ENCRYPTION_AWARE 3334 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3335 triaged = false; 3336 } 3337 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3338 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3339 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3340 } 3341 3342 // Safe mode means we shouldn't match any third-party components 3343 if (mSafeMode) { 3344 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3345 } 3346 3347 return updateFlags(flags, userId); 3348 } 3349 3350 /** 3351 * Update given flags when being used to request {@link ResolveInfo}. 3352 */ 3353 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3354 return updateFlagsForComponent(flags, userId, cookie); 3355 } 3356 3357 @Override 3358 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3359 if (!sUserManager.exists(userId)) return null; 3360 flags = updateFlagsForComponent(flags, userId, component); 3361 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 3362 synchronized (mPackages) { 3363 PackageParser.Activity a = mActivities.mActivities.get(component); 3364 3365 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3366 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3367 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3368 if (ps == null) return null; 3369 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3370 userId); 3371 } 3372 if (mResolveComponentName.equals(component)) { 3373 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3374 new PackageUserState(), userId); 3375 } 3376 } 3377 return null; 3378 } 3379 3380 @Override 3381 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3382 String resolvedType) { 3383 synchronized (mPackages) { 3384 if (component.equals(mResolveComponentName)) { 3385 // The resolver supports EVERYTHING! 3386 return true; 3387 } 3388 PackageParser.Activity a = mActivities.mActivities.get(component); 3389 if (a == null) { 3390 return false; 3391 } 3392 for (int i=0; i<a.intents.size(); i++) { 3393 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3394 intent.getData(), intent.getCategories(), TAG) >= 0) { 3395 return true; 3396 } 3397 } 3398 return false; 3399 } 3400 } 3401 3402 @Override 3403 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3404 if (!sUserManager.exists(userId)) return null; 3405 flags = updateFlagsForComponent(flags, userId, component); 3406 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3407 synchronized (mPackages) { 3408 PackageParser.Activity a = mReceivers.mActivities.get(component); 3409 if (DEBUG_PACKAGE_INFO) Log.v( 3410 TAG, "getReceiverInfo " + component + ": " + a); 3411 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3412 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3413 if (ps == null) return null; 3414 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3415 userId); 3416 } 3417 } 3418 return null; 3419 } 3420 3421 @Override 3422 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3423 if (!sUserManager.exists(userId)) return null; 3424 flags = updateFlagsForComponent(flags, userId, component); 3425 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3426 synchronized (mPackages) { 3427 PackageParser.Service s = mServices.mServices.get(component); 3428 if (DEBUG_PACKAGE_INFO) Log.v( 3429 TAG, "getServiceInfo " + component + ": " + s); 3430 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3431 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3432 if (ps == null) return null; 3433 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3434 userId); 3435 } 3436 } 3437 return null; 3438 } 3439 3440 @Override 3441 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3442 if (!sUserManager.exists(userId)) return null; 3443 flags = updateFlagsForComponent(flags, userId, component); 3444 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3445 synchronized (mPackages) { 3446 PackageParser.Provider p = mProviders.mProviders.get(component); 3447 if (DEBUG_PACKAGE_INFO) Log.v( 3448 TAG, "getProviderInfo " + component + ": " + p); 3449 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3450 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3451 if (ps == null) return null; 3452 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3453 userId); 3454 } 3455 } 3456 return null; 3457 } 3458 3459 @Override 3460 public String[] getSystemSharedLibraryNames() { 3461 Set<String> libSet; 3462 synchronized (mPackages) { 3463 libSet = mSharedLibraries.keySet(); 3464 int size = libSet.size(); 3465 if (size > 0) { 3466 String[] libs = new String[size]; 3467 libSet.toArray(libs); 3468 return libs; 3469 } 3470 } 3471 return null; 3472 } 3473 3474 @Override 3475 public @Nullable String getServicesSystemSharedLibraryPackageName() { 3476 synchronized (mPackages) { 3477 SharedLibraryEntry libraryEntry = mSharedLibraries.get( 3478 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 3479 if (libraryEntry != null) { 3480 return libraryEntry.apk; 3481 } 3482 } 3483 return null; 3484 } 3485 3486 @Override 3487 public FeatureInfo[] getSystemAvailableFeatures() { 3488 Collection<FeatureInfo> featSet; 3489 synchronized (mPackages) { 3490 featSet = mAvailableFeatures.values(); 3491 int size = featSet.size(); 3492 if (size > 0) { 3493 FeatureInfo[] features = new FeatureInfo[size+1]; 3494 featSet.toArray(features); 3495 FeatureInfo fi = new FeatureInfo(); 3496 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3497 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3498 features[size] = fi; 3499 return features; 3500 } 3501 } 3502 return null; 3503 } 3504 3505 @Override 3506 public boolean hasSystemFeature(String name, int version) { 3507 synchronized (mPackages) { 3508 final FeatureInfo feat = mAvailableFeatures.get(name); 3509 if (feat == null) { 3510 return false; 3511 } else { 3512 return feat.version >= version; 3513 } 3514 } 3515 } 3516 3517 @Override 3518 public int checkPermission(String permName, String pkgName, int userId) { 3519 if (!sUserManager.exists(userId)) { 3520 return PackageManager.PERMISSION_DENIED; 3521 } 3522 3523 synchronized (mPackages) { 3524 final PackageParser.Package p = mPackages.get(pkgName); 3525 if (p != null && p.mExtras != null) { 3526 final PackageSetting ps = (PackageSetting) p.mExtras; 3527 final PermissionsState permissionsState = ps.getPermissionsState(); 3528 if (permissionsState.hasPermission(permName, userId)) { 3529 return PackageManager.PERMISSION_GRANTED; 3530 } 3531 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3532 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3533 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3534 return PackageManager.PERMISSION_GRANTED; 3535 } 3536 } 3537 } 3538 3539 return PackageManager.PERMISSION_DENIED; 3540 } 3541 3542 @Override 3543 public int checkUidPermission(String permName, int uid) { 3544 final int userId = UserHandle.getUserId(uid); 3545 3546 if (!sUserManager.exists(userId)) { 3547 return PackageManager.PERMISSION_DENIED; 3548 } 3549 3550 synchronized (mPackages) { 3551 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3552 if (obj != null) { 3553 final SettingBase ps = (SettingBase) obj; 3554 final PermissionsState permissionsState = ps.getPermissionsState(); 3555 if (permissionsState.hasPermission(permName, userId)) { 3556 return PackageManager.PERMISSION_GRANTED; 3557 } 3558 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3559 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3560 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3561 return PackageManager.PERMISSION_GRANTED; 3562 } 3563 } else { 3564 ArraySet<String> perms = mSystemPermissions.get(uid); 3565 if (perms != null) { 3566 if (perms.contains(permName)) { 3567 return PackageManager.PERMISSION_GRANTED; 3568 } 3569 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3570 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3571 return PackageManager.PERMISSION_GRANTED; 3572 } 3573 } 3574 } 3575 } 3576 3577 return PackageManager.PERMISSION_DENIED; 3578 } 3579 3580 @Override 3581 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3582 if (UserHandle.getCallingUserId() != userId) { 3583 mContext.enforceCallingPermission( 3584 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3585 "isPermissionRevokedByPolicy for user " + userId); 3586 } 3587 3588 if (checkPermission(permission, packageName, userId) 3589 == PackageManager.PERMISSION_GRANTED) { 3590 return false; 3591 } 3592 3593 final long identity = Binder.clearCallingIdentity(); 3594 try { 3595 final int flags = getPermissionFlags(permission, packageName, userId); 3596 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3597 } finally { 3598 Binder.restoreCallingIdentity(identity); 3599 } 3600 } 3601 3602 @Override 3603 public String getPermissionControllerPackageName() { 3604 synchronized (mPackages) { 3605 return mRequiredInstallerPackage; 3606 } 3607 } 3608 3609 /** 3610 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3611 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3612 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3613 * @param message the message to log on security exception 3614 */ 3615 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3616 boolean checkShell, String message) { 3617 if (userId < 0) { 3618 throw new IllegalArgumentException("Invalid userId " + userId); 3619 } 3620 if (checkShell) { 3621 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3622 } 3623 if (userId == UserHandle.getUserId(callingUid)) return; 3624 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3625 if (requireFullPermission) { 3626 mContext.enforceCallingOrSelfPermission( 3627 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3628 } else { 3629 try { 3630 mContext.enforceCallingOrSelfPermission( 3631 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3632 } catch (SecurityException se) { 3633 mContext.enforceCallingOrSelfPermission( 3634 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3635 } 3636 } 3637 } 3638 } 3639 3640 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3641 if (callingUid == Process.SHELL_UID) { 3642 if (userHandle >= 0 3643 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3644 throw new SecurityException("Shell does not have permission to access user " 3645 + userHandle); 3646 } else if (userHandle < 0) { 3647 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3648 + Debug.getCallers(3)); 3649 } 3650 } 3651 } 3652 3653 private BasePermission findPermissionTreeLP(String permName) { 3654 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3655 if (permName.startsWith(bp.name) && 3656 permName.length() > bp.name.length() && 3657 permName.charAt(bp.name.length()) == '.') { 3658 return bp; 3659 } 3660 } 3661 return null; 3662 } 3663 3664 private BasePermission checkPermissionTreeLP(String permName) { 3665 if (permName != null) { 3666 BasePermission bp = findPermissionTreeLP(permName); 3667 if (bp != null) { 3668 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3669 return bp; 3670 } 3671 throw new SecurityException("Calling uid " 3672 + Binder.getCallingUid() 3673 + " is not allowed to add to permission tree " 3674 + bp.name + " owned by uid " + bp.uid); 3675 } 3676 } 3677 throw new SecurityException("No permission tree found for " + permName); 3678 } 3679 3680 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3681 if (s1 == null) { 3682 return s2 == null; 3683 } 3684 if (s2 == null) { 3685 return false; 3686 } 3687 if (s1.getClass() != s2.getClass()) { 3688 return false; 3689 } 3690 return s1.equals(s2); 3691 } 3692 3693 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3694 if (pi1.icon != pi2.icon) return false; 3695 if (pi1.logo != pi2.logo) return false; 3696 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3697 if (!compareStrings(pi1.name, pi2.name)) return false; 3698 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3699 // We'll take care of setting this one. 3700 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3701 // These are not currently stored in settings. 3702 //if (!compareStrings(pi1.group, pi2.group)) return false; 3703 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3704 //if (pi1.labelRes != pi2.labelRes) return false; 3705 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3706 return true; 3707 } 3708 3709 int permissionInfoFootprint(PermissionInfo info) { 3710 int size = info.name.length(); 3711 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3712 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3713 return size; 3714 } 3715 3716 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3717 int size = 0; 3718 for (BasePermission perm : mSettings.mPermissions.values()) { 3719 if (perm.uid == tree.uid) { 3720 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3721 } 3722 } 3723 return size; 3724 } 3725 3726 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3727 // We calculate the max size of permissions defined by this uid and throw 3728 // if that plus the size of 'info' would exceed our stated maximum. 3729 if (tree.uid != Process.SYSTEM_UID) { 3730 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3731 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3732 throw new SecurityException("Permission tree size cap exceeded"); 3733 } 3734 } 3735 } 3736 3737 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3738 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3739 throw new SecurityException("Label must be specified in permission"); 3740 } 3741 BasePermission tree = checkPermissionTreeLP(info.name); 3742 BasePermission bp = mSettings.mPermissions.get(info.name); 3743 boolean added = bp == null; 3744 boolean changed = true; 3745 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3746 if (added) { 3747 enforcePermissionCapLocked(info, tree); 3748 bp = new BasePermission(info.name, tree.sourcePackage, 3749 BasePermission.TYPE_DYNAMIC); 3750 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3751 throw new SecurityException( 3752 "Not allowed to modify non-dynamic permission " 3753 + info.name); 3754 } else { 3755 if (bp.protectionLevel == fixedLevel 3756 && bp.perm.owner.equals(tree.perm.owner) 3757 && bp.uid == tree.uid 3758 && comparePermissionInfos(bp.perm.info, info)) { 3759 changed = false; 3760 } 3761 } 3762 bp.protectionLevel = fixedLevel; 3763 info = new PermissionInfo(info); 3764 info.protectionLevel = fixedLevel; 3765 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3766 bp.perm.info.packageName = tree.perm.info.packageName; 3767 bp.uid = tree.uid; 3768 if (added) { 3769 mSettings.mPermissions.put(info.name, bp); 3770 } 3771 if (changed) { 3772 if (!async) { 3773 mSettings.writeLPr(); 3774 } else { 3775 scheduleWriteSettingsLocked(); 3776 } 3777 } 3778 return added; 3779 } 3780 3781 @Override 3782 public boolean addPermission(PermissionInfo info) { 3783 synchronized (mPackages) { 3784 return addPermissionLocked(info, false); 3785 } 3786 } 3787 3788 @Override 3789 public boolean addPermissionAsync(PermissionInfo info) { 3790 synchronized (mPackages) { 3791 return addPermissionLocked(info, true); 3792 } 3793 } 3794 3795 @Override 3796 public void removePermission(String name) { 3797 synchronized (mPackages) { 3798 checkPermissionTreeLP(name); 3799 BasePermission bp = mSettings.mPermissions.get(name); 3800 if (bp != null) { 3801 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3802 throw new SecurityException( 3803 "Not allowed to modify non-dynamic permission " 3804 + name); 3805 } 3806 mSettings.mPermissions.remove(name); 3807 mSettings.writeLPr(); 3808 } 3809 } 3810 } 3811 3812 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3813 BasePermission bp) { 3814 int index = pkg.requestedPermissions.indexOf(bp.name); 3815 if (index == -1) { 3816 throw new SecurityException("Package " + pkg.packageName 3817 + " has not requested permission " + bp.name); 3818 } 3819 if (!bp.isRuntime() && !bp.isDevelopment()) { 3820 throw new SecurityException("Permission " + bp.name 3821 + " is not a changeable permission type"); 3822 } 3823 } 3824 3825 @Override 3826 public void grantRuntimePermission(String packageName, String name, final int userId) { 3827 if (!sUserManager.exists(userId)) { 3828 Log.e(TAG, "No such user:" + userId); 3829 return; 3830 } 3831 3832 mContext.enforceCallingOrSelfPermission( 3833 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3834 "grantRuntimePermission"); 3835 3836 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3837 "grantRuntimePermission"); 3838 3839 final int uid; 3840 final SettingBase sb; 3841 3842 synchronized (mPackages) { 3843 final PackageParser.Package pkg = mPackages.get(packageName); 3844 if (pkg == null) { 3845 throw new IllegalArgumentException("Unknown package: " + packageName); 3846 } 3847 3848 final BasePermission bp = mSettings.mPermissions.get(name); 3849 if (bp == null) { 3850 throw new IllegalArgumentException("Unknown permission: " + name); 3851 } 3852 3853 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3854 3855 // If a permission review is required for legacy apps we represent 3856 // their permissions as always granted runtime ones since we need 3857 // to keep the review required permission flag per user while an 3858 // install permission's state is shared across all users. 3859 if (Build.PERMISSIONS_REVIEW_REQUIRED 3860 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3861 && bp.isRuntime()) { 3862 return; 3863 } 3864 3865 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3866 sb = (SettingBase) pkg.mExtras; 3867 if (sb == null) { 3868 throw new IllegalArgumentException("Unknown package: " + packageName); 3869 } 3870 3871 final PermissionsState permissionsState = sb.getPermissionsState(); 3872 3873 final int flags = permissionsState.getPermissionFlags(name, userId); 3874 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3875 throw new SecurityException("Cannot grant system fixed permission " 3876 + name + " for package " + packageName); 3877 } 3878 3879 if (bp.isDevelopment()) { 3880 // Development permissions must be handled specially, since they are not 3881 // normal runtime permissions. For now they apply to all users. 3882 if (permissionsState.grantInstallPermission(bp) != 3883 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3884 scheduleWriteSettingsLocked(); 3885 } 3886 return; 3887 } 3888 3889 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 3890 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 3891 return; 3892 } 3893 3894 final int result = permissionsState.grantRuntimePermission(bp, userId); 3895 switch (result) { 3896 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3897 return; 3898 } 3899 3900 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3901 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3902 mHandler.post(new Runnable() { 3903 @Override 3904 public void run() { 3905 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3906 } 3907 }); 3908 } 3909 break; 3910 } 3911 3912 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3913 3914 // Not critical if that is lost - app has to request again. 3915 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3916 } 3917 3918 // Only need to do this if user is initialized. Otherwise it's a new user 3919 // and there are no processes running as the user yet and there's no need 3920 // to make an expensive call to remount processes for the changed permissions. 3921 if (READ_EXTERNAL_STORAGE.equals(name) 3922 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3923 final long token = Binder.clearCallingIdentity(); 3924 try { 3925 if (sUserManager.isInitialized(userId)) { 3926 MountServiceInternal mountServiceInternal = LocalServices.getService( 3927 MountServiceInternal.class); 3928 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3929 } 3930 } finally { 3931 Binder.restoreCallingIdentity(token); 3932 } 3933 } 3934 } 3935 3936 @Override 3937 public void revokeRuntimePermission(String packageName, String name, int userId) { 3938 if (!sUserManager.exists(userId)) { 3939 Log.e(TAG, "No such user:" + userId); 3940 return; 3941 } 3942 3943 mContext.enforceCallingOrSelfPermission( 3944 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3945 "revokeRuntimePermission"); 3946 3947 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3948 "revokeRuntimePermission"); 3949 3950 final int appId; 3951 3952 synchronized (mPackages) { 3953 final PackageParser.Package pkg = mPackages.get(packageName); 3954 if (pkg == null) { 3955 throw new IllegalArgumentException("Unknown package: " + packageName); 3956 } 3957 3958 final BasePermission bp = mSettings.mPermissions.get(name); 3959 if (bp == null) { 3960 throw new IllegalArgumentException("Unknown permission: " + name); 3961 } 3962 3963 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3964 3965 // If a permission review is required for legacy apps we represent 3966 // their permissions as always granted runtime ones since we need 3967 // to keep the review required permission flag per user while an 3968 // install permission's state is shared across all users. 3969 if (Build.PERMISSIONS_REVIEW_REQUIRED 3970 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3971 && bp.isRuntime()) { 3972 return; 3973 } 3974 3975 SettingBase sb = (SettingBase) pkg.mExtras; 3976 if (sb == null) { 3977 throw new IllegalArgumentException("Unknown package: " + packageName); 3978 } 3979 3980 final PermissionsState permissionsState = sb.getPermissionsState(); 3981 3982 final int flags = permissionsState.getPermissionFlags(name, userId); 3983 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3984 throw new SecurityException("Cannot revoke system fixed permission " 3985 + name + " for package " + packageName); 3986 } 3987 3988 if (bp.isDevelopment()) { 3989 // Development permissions must be handled specially, since they are not 3990 // normal runtime permissions. For now they apply to all users. 3991 if (permissionsState.revokeInstallPermission(bp) != 3992 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3993 scheduleWriteSettingsLocked(); 3994 } 3995 return; 3996 } 3997 3998 if (permissionsState.revokeRuntimePermission(bp, userId) == 3999 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4000 return; 4001 } 4002 4003 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4004 4005 // Critical, after this call app should never have the permission. 4006 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4007 4008 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4009 } 4010 4011 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4012 } 4013 4014 @Override 4015 public void resetRuntimePermissions() { 4016 mContext.enforceCallingOrSelfPermission( 4017 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4018 "revokeRuntimePermission"); 4019 4020 int callingUid = Binder.getCallingUid(); 4021 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4022 mContext.enforceCallingOrSelfPermission( 4023 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4024 "resetRuntimePermissions"); 4025 } 4026 4027 synchronized (mPackages) { 4028 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4029 for (int userId : UserManagerService.getInstance().getUserIds()) { 4030 final int packageCount = mPackages.size(); 4031 for (int i = 0; i < packageCount; i++) { 4032 PackageParser.Package pkg = mPackages.valueAt(i); 4033 if (!(pkg.mExtras instanceof PackageSetting)) { 4034 continue; 4035 } 4036 PackageSetting ps = (PackageSetting) pkg.mExtras; 4037 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4038 } 4039 } 4040 } 4041 } 4042 4043 @Override 4044 public int getPermissionFlags(String name, String packageName, int userId) { 4045 if (!sUserManager.exists(userId)) { 4046 return 0; 4047 } 4048 4049 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4050 4051 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 4052 "getPermissionFlags"); 4053 4054 synchronized (mPackages) { 4055 final PackageParser.Package pkg = mPackages.get(packageName); 4056 if (pkg == null) { 4057 throw new IllegalArgumentException("Unknown package: " + packageName); 4058 } 4059 4060 final BasePermission bp = mSettings.mPermissions.get(name); 4061 if (bp == null) { 4062 throw new IllegalArgumentException("Unknown permission: " + name); 4063 } 4064 4065 SettingBase sb = (SettingBase) pkg.mExtras; 4066 if (sb == null) { 4067 throw new IllegalArgumentException("Unknown package: " + packageName); 4068 } 4069 4070 PermissionsState permissionsState = sb.getPermissionsState(); 4071 return permissionsState.getPermissionFlags(name, userId); 4072 } 4073 } 4074 4075 @Override 4076 public void updatePermissionFlags(String name, String packageName, int flagMask, 4077 int flagValues, int userId) { 4078 if (!sUserManager.exists(userId)) { 4079 return; 4080 } 4081 4082 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4083 4084 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 4085 "updatePermissionFlags"); 4086 4087 // Only the system can change these flags and nothing else. 4088 if (getCallingUid() != Process.SYSTEM_UID) { 4089 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4090 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4091 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4092 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4093 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4094 } 4095 4096 synchronized (mPackages) { 4097 final PackageParser.Package pkg = mPackages.get(packageName); 4098 if (pkg == null) { 4099 throw new IllegalArgumentException("Unknown package: " + packageName); 4100 } 4101 4102 final BasePermission bp = mSettings.mPermissions.get(name); 4103 if (bp == null) { 4104 throw new IllegalArgumentException("Unknown permission: " + name); 4105 } 4106 4107 SettingBase sb = (SettingBase) pkg.mExtras; 4108 if (sb == null) { 4109 throw new IllegalArgumentException("Unknown package: " + packageName); 4110 } 4111 4112 PermissionsState permissionsState = sb.getPermissionsState(); 4113 4114 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4115 4116 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4117 // Install and runtime permissions are stored in different places, 4118 // so figure out what permission changed and persist the change. 4119 if (permissionsState.getInstallPermissionState(name) != null) { 4120 scheduleWriteSettingsLocked(); 4121 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4122 || hadState) { 4123 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4124 } 4125 } 4126 } 4127 } 4128 4129 /** 4130 * Update the permission flags for all packages and runtime permissions of a user in order 4131 * to allow device or profile owner to remove POLICY_FIXED. 4132 */ 4133 @Override 4134 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4135 if (!sUserManager.exists(userId)) { 4136 return; 4137 } 4138 4139 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4140 4141 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 4142 "updatePermissionFlagsForAllApps"); 4143 4144 // Only the system can change system fixed flags. 4145 if (getCallingUid() != Process.SYSTEM_UID) { 4146 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4147 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4148 } 4149 4150 synchronized (mPackages) { 4151 boolean changed = false; 4152 final int packageCount = mPackages.size(); 4153 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4154 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4155 SettingBase sb = (SettingBase) pkg.mExtras; 4156 if (sb == null) { 4157 continue; 4158 } 4159 PermissionsState permissionsState = sb.getPermissionsState(); 4160 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4161 userId, flagMask, flagValues); 4162 } 4163 if (changed) { 4164 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4165 } 4166 } 4167 } 4168 4169 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4170 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4171 != PackageManager.PERMISSION_GRANTED 4172 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4173 != PackageManager.PERMISSION_GRANTED) { 4174 throw new SecurityException(message + " requires " 4175 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4176 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4177 } 4178 } 4179 4180 @Override 4181 public boolean shouldShowRequestPermissionRationale(String permissionName, 4182 String packageName, int userId) { 4183 if (UserHandle.getCallingUserId() != userId) { 4184 mContext.enforceCallingPermission( 4185 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4186 "canShowRequestPermissionRationale for user " + userId); 4187 } 4188 4189 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4190 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4191 return false; 4192 } 4193 4194 if (checkPermission(permissionName, packageName, userId) 4195 == PackageManager.PERMISSION_GRANTED) { 4196 return false; 4197 } 4198 4199 final int flags; 4200 4201 final long identity = Binder.clearCallingIdentity(); 4202 try { 4203 flags = getPermissionFlags(permissionName, 4204 packageName, userId); 4205 } finally { 4206 Binder.restoreCallingIdentity(identity); 4207 } 4208 4209 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4210 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4211 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4212 4213 if ((flags & fixedFlags) != 0) { 4214 return false; 4215 } 4216 4217 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4218 } 4219 4220 @Override 4221 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4222 mContext.enforceCallingOrSelfPermission( 4223 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4224 "addOnPermissionsChangeListener"); 4225 4226 synchronized (mPackages) { 4227 mOnPermissionChangeListeners.addListenerLocked(listener); 4228 } 4229 } 4230 4231 @Override 4232 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4233 synchronized (mPackages) { 4234 mOnPermissionChangeListeners.removeListenerLocked(listener); 4235 } 4236 } 4237 4238 @Override 4239 public boolean isProtectedBroadcast(String actionName) { 4240 synchronized (mPackages) { 4241 if (mProtectedBroadcasts.contains(actionName)) { 4242 return true; 4243 } else if (actionName != null) { 4244 // TODO: remove these terrible hacks 4245 if (actionName.startsWith("android.net.netmon.lingerExpired") 4246 || actionName.startsWith("com.android.server.sip.SipWakeupTimer")) { 4247 return true; 4248 } 4249 } 4250 } 4251 return false; 4252 } 4253 4254 @Override 4255 public int checkSignatures(String pkg1, String pkg2) { 4256 synchronized (mPackages) { 4257 final PackageParser.Package p1 = mPackages.get(pkg1); 4258 final PackageParser.Package p2 = mPackages.get(pkg2); 4259 if (p1 == null || p1.mExtras == null 4260 || p2 == null || p2.mExtras == null) { 4261 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4262 } 4263 return compareSignatures(p1.mSignatures, p2.mSignatures); 4264 } 4265 } 4266 4267 @Override 4268 public int checkUidSignatures(int uid1, int uid2) { 4269 // Map to base uids. 4270 uid1 = UserHandle.getAppId(uid1); 4271 uid2 = UserHandle.getAppId(uid2); 4272 // reader 4273 synchronized (mPackages) { 4274 Signature[] s1; 4275 Signature[] s2; 4276 Object obj = mSettings.getUserIdLPr(uid1); 4277 if (obj != null) { 4278 if (obj instanceof SharedUserSetting) { 4279 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4280 } else if (obj instanceof PackageSetting) { 4281 s1 = ((PackageSetting)obj).signatures.mSignatures; 4282 } else { 4283 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4284 } 4285 } else { 4286 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4287 } 4288 obj = mSettings.getUserIdLPr(uid2); 4289 if (obj != null) { 4290 if (obj instanceof SharedUserSetting) { 4291 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4292 } else if (obj instanceof PackageSetting) { 4293 s2 = ((PackageSetting)obj).signatures.mSignatures; 4294 } else { 4295 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4296 } 4297 } else { 4298 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4299 } 4300 return compareSignatures(s1, s2); 4301 } 4302 } 4303 4304 private void killUid(int appId, int userId, String reason) { 4305 final long identity = Binder.clearCallingIdentity(); 4306 try { 4307 IActivityManager am = ActivityManagerNative.getDefault(); 4308 if (am != null) { 4309 try { 4310 am.killUid(appId, userId, reason); 4311 } catch (RemoteException e) { 4312 /* ignore - same process */ 4313 } 4314 } 4315 } finally { 4316 Binder.restoreCallingIdentity(identity); 4317 } 4318 } 4319 4320 /** 4321 * Compares two sets of signatures. Returns: 4322 * <br /> 4323 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4324 * <br /> 4325 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4326 * <br /> 4327 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4328 * <br /> 4329 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4330 * <br /> 4331 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4332 */ 4333 static int compareSignatures(Signature[] s1, Signature[] s2) { 4334 if (s1 == null) { 4335 return s2 == null 4336 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4337 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4338 } 4339 4340 if (s2 == null) { 4341 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4342 } 4343 4344 if (s1.length != s2.length) { 4345 return PackageManager.SIGNATURE_NO_MATCH; 4346 } 4347 4348 // Since both signature sets are of size 1, we can compare without HashSets. 4349 if (s1.length == 1) { 4350 return s1[0].equals(s2[0]) ? 4351 PackageManager.SIGNATURE_MATCH : 4352 PackageManager.SIGNATURE_NO_MATCH; 4353 } 4354 4355 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4356 for (Signature sig : s1) { 4357 set1.add(sig); 4358 } 4359 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4360 for (Signature sig : s2) { 4361 set2.add(sig); 4362 } 4363 // Make sure s2 contains all signatures in s1. 4364 if (set1.equals(set2)) { 4365 return PackageManager.SIGNATURE_MATCH; 4366 } 4367 return PackageManager.SIGNATURE_NO_MATCH; 4368 } 4369 4370 /** 4371 * If the database version for this type of package (internal storage or 4372 * external storage) is less than the version where package signatures 4373 * were updated, return true. 4374 */ 4375 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4376 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4377 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4378 } 4379 4380 /** 4381 * Used for backward compatibility to make sure any packages with 4382 * certificate chains get upgraded to the new style. {@code existingSigs} 4383 * will be in the old format (since they were stored on disk from before the 4384 * system upgrade) and {@code scannedSigs} will be in the newer format. 4385 */ 4386 private int compareSignaturesCompat(PackageSignatures existingSigs, 4387 PackageParser.Package scannedPkg) { 4388 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4389 return PackageManager.SIGNATURE_NO_MATCH; 4390 } 4391 4392 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4393 for (Signature sig : existingSigs.mSignatures) { 4394 existingSet.add(sig); 4395 } 4396 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4397 for (Signature sig : scannedPkg.mSignatures) { 4398 try { 4399 Signature[] chainSignatures = sig.getChainSignatures(); 4400 for (Signature chainSig : chainSignatures) { 4401 scannedCompatSet.add(chainSig); 4402 } 4403 } catch (CertificateEncodingException e) { 4404 scannedCompatSet.add(sig); 4405 } 4406 } 4407 /* 4408 * Make sure the expanded scanned set contains all signatures in the 4409 * existing one. 4410 */ 4411 if (scannedCompatSet.equals(existingSet)) { 4412 // Migrate the old signatures to the new scheme. 4413 existingSigs.assignSignatures(scannedPkg.mSignatures); 4414 // The new KeySets will be re-added later in the scanning process. 4415 synchronized (mPackages) { 4416 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4417 } 4418 return PackageManager.SIGNATURE_MATCH; 4419 } 4420 return PackageManager.SIGNATURE_NO_MATCH; 4421 } 4422 4423 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4424 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4425 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4426 } 4427 4428 private int compareSignaturesRecover(PackageSignatures existingSigs, 4429 PackageParser.Package scannedPkg) { 4430 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4431 return PackageManager.SIGNATURE_NO_MATCH; 4432 } 4433 4434 String msg = null; 4435 try { 4436 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4437 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4438 + scannedPkg.packageName); 4439 return PackageManager.SIGNATURE_MATCH; 4440 } 4441 } catch (CertificateException e) { 4442 msg = e.getMessage(); 4443 } 4444 4445 logCriticalInfo(Log.INFO, 4446 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4447 return PackageManager.SIGNATURE_NO_MATCH; 4448 } 4449 4450 @Override 4451 public String[] getPackagesForUid(int uid) { 4452 uid = UserHandle.getAppId(uid); 4453 // reader 4454 synchronized (mPackages) { 4455 Object obj = mSettings.getUserIdLPr(uid); 4456 if (obj instanceof SharedUserSetting) { 4457 final SharedUserSetting sus = (SharedUserSetting) obj; 4458 final int N = sus.packages.size(); 4459 final String[] res = new String[N]; 4460 final Iterator<PackageSetting> it = sus.packages.iterator(); 4461 int i = 0; 4462 while (it.hasNext()) { 4463 res[i++] = it.next().name; 4464 } 4465 return res; 4466 } else if (obj instanceof PackageSetting) { 4467 final PackageSetting ps = (PackageSetting) obj; 4468 return new String[] { ps.name }; 4469 } 4470 } 4471 return null; 4472 } 4473 4474 @Override 4475 public String getNameForUid(int uid) { 4476 // reader 4477 synchronized (mPackages) { 4478 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4479 if (obj instanceof SharedUserSetting) { 4480 final SharedUserSetting sus = (SharedUserSetting) obj; 4481 return sus.name + ":" + sus.userId; 4482 } else if (obj instanceof PackageSetting) { 4483 final PackageSetting ps = (PackageSetting) obj; 4484 return ps.name; 4485 } 4486 } 4487 return null; 4488 } 4489 4490 @Override 4491 public int getUidForSharedUser(String sharedUserName) { 4492 if(sharedUserName == null) { 4493 return -1; 4494 } 4495 // reader 4496 synchronized (mPackages) { 4497 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4498 if (suid == null) { 4499 return -1; 4500 } 4501 return suid.userId; 4502 } 4503 } 4504 4505 @Override 4506 public int getFlagsForUid(int uid) { 4507 synchronized (mPackages) { 4508 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4509 if (obj instanceof SharedUserSetting) { 4510 final SharedUserSetting sus = (SharedUserSetting) obj; 4511 return sus.pkgFlags; 4512 } else if (obj instanceof PackageSetting) { 4513 final PackageSetting ps = (PackageSetting) obj; 4514 return ps.pkgFlags; 4515 } 4516 } 4517 return 0; 4518 } 4519 4520 @Override 4521 public int getPrivateFlagsForUid(int uid) { 4522 synchronized (mPackages) { 4523 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4524 if (obj instanceof SharedUserSetting) { 4525 final SharedUserSetting sus = (SharedUserSetting) obj; 4526 return sus.pkgPrivateFlags; 4527 } else if (obj instanceof PackageSetting) { 4528 final PackageSetting ps = (PackageSetting) obj; 4529 return ps.pkgPrivateFlags; 4530 } 4531 } 4532 return 0; 4533 } 4534 4535 @Override 4536 public boolean isUidPrivileged(int uid) { 4537 uid = UserHandle.getAppId(uid); 4538 // reader 4539 synchronized (mPackages) { 4540 Object obj = mSettings.getUserIdLPr(uid); 4541 if (obj instanceof SharedUserSetting) { 4542 final SharedUserSetting sus = (SharedUserSetting) obj; 4543 final Iterator<PackageSetting> it = sus.packages.iterator(); 4544 while (it.hasNext()) { 4545 if (it.next().isPrivileged()) { 4546 return true; 4547 } 4548 } 4549 } else if (obj instanceof PackageSetting) { 4550 final PackageSetting ps = (PackageSetting) obj; 4551 return ps.isPrivileged(); 4552 } 4553 } 4554 return false; 4555 } 4556 4557 @Override 4558 public String[] getAppOpPermissionPackages(String permissionName) { 4559 synchronized (mPackages) { 4560 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4561 if (pkgs == null) { 4562 return null; 4563 } 4564 return pkgs.toArray(new String[pkgs.size()]); 4565 } 4566 } 4567 4568 @Override 4569 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4570 int flags, int userId) { 4571 if (!sUserManager.exists(userId)) return null; 4572 flags = updateFlagsForResolve(flags, userId, intent); 4573 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4574 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4575 final ResolveInfo bestChoice = 4576 chooseBestActivity(intent, resolvedType, flags, query, userId); 4577 4578 if (isEphemeralAllowed(intent, query, userId)) { 4579 final EphemeralResolveInfo ai = 4580 getEphemeralResolveInfo(intent, resolvedType, userId); 4581 if (ai != null) { 4582 if (DEBUG_EPHEMERAL) { 4583 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4584 } 4585 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4586 bestChoice.ephemeralResolveInfo = ai; 4587 } 4588 } 4589 return bestChoice; 4590 } 4591 4592 @Override 4593 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4594 IntentFilter filter, int match, ComponentName activity) { 4595 final int userId = UserHandle.getCallingUserId(); 4596 if (DEBUG_PREFERRED) { 4597 Log.v(TAG, "setLastChosenActivity intent=" + intent 4598 + " resolvedType=" + resolvedType 4599 + " flags=" + flags 4600 + " filter=" + filter 4601 + " match=" + match 4602 + " activity=" + activity); 4603 filter.dump(new PrintStreamPrinter(System.out), " "); 4604 } 4605 intent.setComponent(null); 4606 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4607 // Find any earlier preferred or last chosen entries and nuke them 4608 findPreferredActivity(intent, resolvedType, 4609 flags, query, 0, false, true, false, userId); 4610 // Add the new activity as the last chosen for this filter 4611 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4612 "Setting last chosen"); 4613 } 4614 4615 @Override 4616 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4617 final int userId = UserHandle.getCallingUserId(); 4618 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4619 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4620 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4621 false, false, false, userId); 4622 } 4623 4624 4625 private boolean isEphemeralAllowed( 4626 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4627 // Short circuit and return early if possible. 4628 if (DISABLE_EPHEMERAL_APPS) { 4629 return false; 4630 } 4631 final int callingUser = UserHandle.getCallingUserId(); 4632 if (callingUser != UserHandle.USER_SYSTEM) { 4633 return false; 4634 } 4635 if (mEphemeralResolverConnection == null) { 4636 return false; 4637 } 4638 if (intent.getComponent() != null) { 4639 return false; 4640 } 4641 if (intent.getPackage() != null) { 4642 return false; 4643 } 4644 final boolean isWebUri = hasWebURI(intent); 4645 if (!isWebUri) { 4646 return false; 4647 } 4648 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4649 synchronized (mPackages) { 4650 final int count = resolvedActivites.size(); 4651 for (int n = 0; n < count; n++) { 4652 ResolveInfo info = resolvedActivites.get(n); 4653 String packageName = info.activityInfo.packageName; 4654 PackageSetting ps = mSettings.mPackages.get(packageName); 4655 if (ps != null) { 4656 // Try to get the status from User settings first 4657 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4658 int status = (int) (packedStatus >> 32); 4659 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4660 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4661 if (DEBUG_EPHEMERAL) { 4662 Slog.v(TAG, "DENY ephemeral apps;" 4663 + " pkg: " + packageName + ", status: " + status); 4664 } 4665 return false; 4666 } 4667 } 4668 } 4669 } 4670 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4671 return true; 4672 } 4673 4674 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4675 int userId) { 4676 MessageDigest digest = null; 4677 try { 4678 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4679 } catch (NoSuchAlgorithmException e) { 4680 // If we can't create a digest, ignore ephemeral apps. 4681 return null; 4682 } 4683 4684 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4685 final byte[] digestBytes = digest.digest(hostBytes); 4686 int shaPrefix = 4687 digestBytes[0] << 24 4688 | digestBytes[1] << 16 4689 | digestBytes[2] << 8 4690 | digestBytes[3] << 0; 4691 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4692 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4693 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4694 // No hash prefix match; there are no ephemeral apps for this domain. 4695 return null; 4696 } 4697 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4698 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4699 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4700 continue; 4701 } 4702 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4703 // No filters; this should never happen. 4704 if (filters.isEmpty()) { 4705 continue; 4706 } 4707 // We have a domain match; resolve the filters to see if anything matches. 4708 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4709 for (int j = filters.size() - 1; j >= 0; --j) { 4710 final EphemeralResolveIntentInfo intentInfo = 4711 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4712 ephemeralResolver.addFilter(intentInfo); 4713 } 4714 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4715 intent, resolvedType, false /*defaultOnly*/, userId); 4716 if (!matchedResolveInfoList.isEmpty()) { 4717 return matchedResolveInfoList.get(0); 4718 } 4719 } 4720 // Hash or filter mis-match; no ephemeral apps for this domain. 4721 return null; 4722 } 4723 4724 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4725 int flags, List<ResolveInfo> query, int userId) { 4726 if (query != null) { 4727 final int N = query.size(); 4728 if (N == 1) { 4729 return query.get(0); 4730 } else if (N > 1) { 4731 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4732 // If there is more than one activity with the same priority, 4733 // then let the user decide between them. 4734 ResolveInfo r0 = query.get(0); 4735 ResolveInfo r1 = query.get(1); 4736 if (DEBUG_INTENT_MATCHING || debug) { 4737 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4738 + r1.activityInfo.name + "=" + r1.priority); 4739 } 4740 // If the first activity has a higher priority, or a different 4741 // default, then it is always desirable to pick it. 4742 if (r0.priority != r1.priority 4743 || r0.preferredOrder != r1.preferredOrder 4744 || r0.isDefault != r1.isDefault) { 4745 return query.get(0); 4746 } 4747 // If we have saved a preference for a preferred activity for 4748 // this Intent, use that. 4749 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4750 flags, query, r0.priority, true, false, debug, userId); 4751 if (ri != null) { 4752 return ri; 4753 } 4754 ri = new ResolveInfo(mResolveInfo); 4755 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4756 ri.activityInfo.applicationInfo = new ApplicationInfo( 4757 ri.activityInfo.applicationInfo); 4758 if (userId != 0) { 4759 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4760 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4761 } 4762 // Make sure that the resolver is displayable in car mode 4763 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4764 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4765 return ri; 4766 } 4767 } 4768 return null; 4769 } 4770 4771 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4772 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4773 final int N = query.size(); 4774 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4775 .get(userId); 4776 // Get the list of persistent preferred activities that handle the intent 4777 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4778 List<PersistentPreferredActivity> pprefs = ppir != null 4779 ? ppir.queryIntent(intent, resolvedType, 4780 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4781 : null; 4782 if (pprefs != null && pprefs.size() > 0) { 4783 final int M = pprefs.size(); 4784 for (int i=0; i<M; i++) { 4785 final PersistentPreferredActivity ppa = pprefs.get(i); 4786 if (DEBUG_PREFERRED || debug) { 4787 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4788 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4789 + "\n component=" + ppa.mComponent); 4790 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4791 } 4792 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4793 flags | MATCH_DISABLED_COMPONENTS, userId); 4794 if (DEBUG_PREFERRED || debug) { 4795 Slog.v(TAG, "Found persistent preferred activity:"); 4796 if (ai != null) { 4797 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4798 } else { 4799 Slog.v(TAG, " null"); 4800 } 4801 } 4802 if (ai == null) { 4803 // This previously registered persistent preferred activity 4804 // component is no longer known. Ignore it and do NOT remove it. 4805 continue; 4806 } 4807 for (int j=0; j<N; j++) { 4808 final ResolveInfo ri = query.get(j); 4809 if (!ri.activityInfo.applicationInfo.packageName 4810 .equals(ai.applicationInfo.packageName)) { 4811 continue; 4812 } 4813 if (!ri.activityInfo.name.equals(ai.name)) { 4814 continue; 4815 } 4816 // Found a persistent preference that can handle the intent. 4817 if (DEBUG_PREFERRED || debug) { 4818 Slog.v(TAG, "Returning persistent preferred activity: " + 4819 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4820 } 4821 return ri; 4822 } 4823 } 4824 } 4825 return null; 4826 } 4827 4828 // TODO: handle preferred activities missing while user has amnesia 4829 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4830 List<ResolveInfo> query, int priority, boolean always, 4831 boolean removeMatches, boolean debug, int userId) { 4832 if (!sUserManager.exists(userId)) return null; 4833 flags = updateFlagsForResolve(flags, userId, intent); 4834 // writer 4835 synchronized (mPackages) { 4836 if (intent.getSelector() != null) { 4837 intent = intent.getSelector(); 4838 } 4839 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4840 4841 // Try to find a matching persistent preferred activity. 4842 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4843 debug, userId); 4844 4845 // If a persistent preferred activity matched, use it. 4846 if (pri != null) { 4847 return pri; 4848 } 4849 4850 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4851 // Get the list of preferred activities that handle the intent 4852 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4853 List<PreferredActivity> prefs = pir != null 4854 ? pir.queryIntent(intent, resolvedType, 4855 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4856 : null; 4857 if (prefs != null && prefs.size() > 0) { 4858 boolean changed = false; 4859 try { 4860 // First figure out how good the original match set is. 4861 // We will only allow preferred activities that came 4862 // from the same match quality. 4863 int match = 0; 4864 4865 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4866 4867 final int N = query.size(); 4868 for (int j=0; j<N; j++) { 4869 final ResolveInfo ri = query.get(j); 4870 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4871 + ": 0x" + Integer.toHexString(match)); 4872 if (ri.match > match) { 4873 match = ri.match; 4874 } 4875 } 4876 4877 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4878 + Integer.toHexString(match)); 4879 4880 match &= IntentFilter.MATCH_CATEGORY_MASK; 4881 final int M = prefs.size(); 4882 for (int i=0; i<M; i++) { 4883 final PreferredActivity pa = prefs.get(i); 4884 if (DEBUG_PREFERRED || debug) { 4885 Slog.v(TAG, "Checking PreferredActivity ds=" 4886 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4887 + "\n component=" + pa.mPref.mComponent); 4888 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4889 } 4890 if (pa.mPref.mMatch != match) { 4891 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4892 + Integer.toHexString(pa.mPref.mMatch)); 4893 continue; 4894 } 4895 // If it's not an "always" type preferred activity and that's what we're 4896 // looking for, skip it. 4897 if (always && !pa.mPref.mAlways) { 4898 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4899 continue; 4900 } 4901 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4902 flags | MATCH_DISABLED_COMPONENTS, userId); 4903 if (DEBUG_PREFERRED || debug) { 4904 Slog.v(TAG, "Found preferred activity:"); 4905 if (ai != null) { 4906 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4907 } else { 4908 Slog.v(TAG, " null"); 4909 } 4910 } 4911 if (ai == null) { 4912 // This previously registered preferred activity 4913 // component is no longer known. Most likely an update 4914 // to the app was installed and in the new version this 4915 // component no longer exists. Clean it up by removing 4916 // it from the preferred activities list, and skip it. 4917 Slog.w(TAG, "Removing dangling preferred activity: " 4918 + pa.mPref.mComponent); 4919 pir.removeFilter(pa); 4920 changed = true; 4921 continue; 4922 } 4923 for (int j=0; j<N; j++) { 4924 final ResolveInfo ri = query.get(j); 4925 if (!ri.activityInfo.applicationInfo.packageName 4926 .equals(ai.applicationInfo.packageName)) { 4927 continue; 4928 } 4929 if (!ri.activityInfo.name.equals(ai.name)) { 4930 continue; 4931 } 4932 4933 if (removeMatches) { 4934 pir.removeFilter(pa); 4935 changed = true; 4936 if (DEBUG_PREFERRED) { 4937 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4938 } 4939 break; 4940 } 4941 4942 // Okay we found a previously set preferred or last chosen app. 4943 // If the result set is different from when this 4944 // was created, we need to clear it and re-ask the 4945 // user their preference, if we're looking for an "always" type entry. 4946 if (always && !pa.mPref.sameSet(query)) { 4947 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4948 + intent + " type " + resolvedType); 4949 if (DEBUG_PREFERRED) { 4950 Slog.v(TAG, "Removing preferred activity since set changed " 4951 + pa.mPref.mComponent); 4952 } 4953 pir.removeFilter(pa); 4954 // Re-add the filter as a "last chosen" entry (!always) 4955 PreferredActivity lastChosen = new PreferredActivity( 4956 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4957 pir.addFilter(lastChosen); 4958 changed = true; 4959 return null; 4960 } 4961 4962 // Yay! Either the set matched or we're looking for the last chosen 4963 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4964 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4965 return ri; 4966 } 4967 } 4968 } finally { 4969 if (changed) { 4970 if (DEBUG_PREFERRED) { 4971 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4972 } 4973 scheduleWritePackageRestrictionsLocked(userId); 4974 } 4975 } 4976 } 4977 } 4978 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4979 return null; 4980 } 4981 4982 /* 4983 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4984 */ 4985 @Override 4986 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4987 int targetUserId) { 4988 mContext.enforceCallingOrSelfPermission( 4989 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4990 List<CrossProfileIntentFilter> matches = 4991 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4992 if (matches != null) { 4993 int size = matches.size(); 4994 for (int i = 0; i < size; i++) { 4995 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4996 } 4997 } 4998 if (hasWebURI(intent)) { 4999 // cross-profile app linking works only towards the parent. 5000 final UserInfo parent = getProfileParent(sourceUserId); 5001 synchronized(mPackages) { 5002 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5003 intent, resolvedType, 0, sourceUserId, parent.id); 5004 return xpDomainInfo != null; 5005 } 5006 } 5007 return false; 5008 } 5009 5010 private UserInfo getProfileParent(int userId) { 5011 final long identity = Binder.clearCallingIdentity(); 5012 try { 5013 return sUserManager.getProfileParent(userId); 5014 } finally { 5015 Binder.restoreCallingIdentity(identity); 5016 } 5017 } 5018 5019 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5020 String resolvedType, int userId) { 5021 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5022 if (resolver != null) { 5023 return resolver.queryIntent(intent, resolvedType, false, userId); 5024 } 5025 return null; 5026 } 5027 5028 @Override 5029 public List<ResolveInfo> queryIntentActivities(Intent intent, 5030 String resolvedType, int flags, int userId) { 5031 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5032 flags = updateFlagsForResolve(flags, userId, intent); 5033 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 5034 ComponentName comp = intent.getComponent(); 5035 if (comp == null) { 5036 if (intent.getSelector() != null) { 5037 intent = intent.getSelector(); 5038 comp = intent.getComponent(); 5039 } 5040 } 5041 5042 if (comp != null) { 5043 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5044 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5045 if (ai != null) { 5046 final ResolveInfo ri = new ResolveInfo(); 5047 ri.activityInfo = ai; 5048 list.add(ri); 5049 } 5050 return list; 5051 } 5052 5053 // reader 5054 synchronized (mPackages) { 5055 final String pkgName = intent.getPackage(); 5056 if (pkgName == null) { 5057 List<CrossProfileIntentFilter> matchingFilters = 5058 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5059 // Check for results that need to skip the current profile. 5060 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5061 resolvedType, flags, userId); 5062 if (xpResolveInfo != null) { 5063 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5064 result.add(xpResolveInfo); 5065 return filterIfNotSystemUser(result, userId); 5066 } 5067 5068 // Check for results in the current profile. 5069 List<ResolveInfo> result = mActivities.queryIntent( 5070 intent, resolvedType, flags, userId); 5071 result = filterIfNotSystemUser(result, userId); 5072 5073 // Check for cross profile results. 5074 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5075 xpResolveInfo = queryCrossProfileIntents( 5076 matchingFilters, intent, resolvedType, flags, userId, 5077 hasNonNegativePriorityResult); 5078 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5079 boolean isVisibleToUser = filterIfNotSystemUser( 5080 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5081 if (isVisibleToUser) { 5082 result.add(xpResolveInfo); 5083 Collections.sort(result, mResolvePrioritySorter); 5084 } 5085 } 5086 if (hasWebURI(intent)) { 5087 CrossProfileDomainInfo xpDomainInfo = null; 5088 final UserInfo parent = getProfileParent(userId); 5089 if (parent != null) { 5090 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5091 flags, userId, parent.id); 5092 } 5093 if (xpDomainInfo != null) { 5094 if (xpResolveInfo != null) { 5095 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5096 // in the result. 5097 result.remove(xpResolveInfo); 5098 } 5099 if (result.size() == 0) { 5100 result.add(xpDomainInfo.resolveInfo); 5101 return result; 5102 } 5103 } else if (result.size() <= 1) { 5104 return result; 5105 } 5106 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5107 xpDomainInfo, userId); 5108 Collections.sort(result, mResolvePrioritySorter); 5109 } 5110 return result; 5111 } 5112 final PackageParser.Package pkg = mPackages.get(pkgName); 5113 if (pkg != null) { 5114 return filterIfNotSystemUser( 5115 mActivities.queryIntentForPackage( 5116 intent, resolvedType, flags, pkg.activities, userId), 5117 userId); 5118 } 5119 return new ArrayList<ResolveInfo>(); 5120 } 5121 } 5122 5123 private static class CrossProfileDomainInfo { 5124 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5125 ResolveInfo resolveInfo; 5126 /* Best domain verification status of the activities found in the other profile */ 5127 int bestDomainVerificationStatus; 5128 } 5129 5130 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5131 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5132 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5133 sourceUserId)) { 5134 return null; 5135 } 5136 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5137 resolvedType, flags, parentUserId); 5138 5139 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5140 return null; 5141 } 5142 CrossProfileDomainInfo result = null; 5143 int size = resultTargetUser.size(); 5144 for (int i = 0; i < size; i++) { 5145 ResolveInfo riTargetUser = resultTargetUser.get(i); 5146 // Intent filter verification is only for filters that specify a host. So don't return 5147 // those that handle all web uris. 5148 if (riTargetUser.handleAllWebDataURI) { 5149 continue; 5150 } 5151 String packageName = riTargetUser.activityInfo.packageName; 5152 PackageSetting ps = mSettings.mPackages.get(packageName); 5153 if (ps == null) { 5154 continue; 5155 } 5156 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5157 int status = (int)(verificationState >> 32); 5158 if (result == null) { 5159 result = new CrossProfileDomainInfo(); 5160 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5161 sourceUserId, parentUserId); 5162 result.bestDomainVerificationStatus = status; 5163 } else { 5164 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5165 result.bestDomainVerificationStatus); 5166 } 5167 } 5168 // Don't consider matches with status NEVER across profiles. 5169 if (result != null && result.bestDomainVerificationStatus 5170 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5171 return null; 5172 } 5173 return result; 5174 } 5175 5176 /** 5177 * Verification statuses are ordered from the worse to the best, except for 5178 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5179 */ 5180 private int bestDomainVerificationStatus(int status1, int status2) { 5181 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5182 return status2; 5183 } 5184 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5185 return status1; 5186 } 5187 return (int) MathUtils.max(status1, status2); 5188 } 5189 5190 private boolean isUserEnabled(int userId) { 5191 long callingId = Binder.clearCallingIdentity(); 5192 try { 5193 UserInfo userInfo = sUserManager.getUserInfo(userId); 5194 return userInfo != null && userInfo.isEnabled(); 5195 } finally { 5196 Binder.restoreCallingIdentity(callingId); 5197 } 5198 } 5199 5200 /** 5201 * Filter out activities with systemUserOnly flag set, when current user is not System. 5202 * 5203 * @return filtered list 5204 */ 5205 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5206 if (userId == UserHandle.USER_SYSTEM) { 5207 return resolveInfos; 5208 } 5209 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5210 ResolveInfo info = resolveInfos.get(i); 5211 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5212 resolveInfos.remove(i); 5213 } 5214 } 5215 return resolveInfos; 5216 } 5217 5218 /** 5219 * @param resolveInfos list of resolve infos in descending priority order 5220 * @return if the list contains a resolve info with non-negative priority 5221 */ 5222 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5223 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5224 } 5225 5226 private static boolean hasWebURI(Intent intent) { 5227 if (intent.getData() == null) { 5228 return false; 5229 } 5230 final String scheme = intent.getScheme(); 5231 if (TextUtils.isEmpty(scheme)) { 5232 return false; 5233 } 5234 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5235 } 5236 5237 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5238 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5239 int userId) { 5240 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5241 5242 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5243 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5244 candidates.size()); 5245 } 5246 5247 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5248 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5249 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5250 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5251 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5252 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5253 5254 synchronized (mPackages) { 5255 final int count = candidates.size(); 5256 // First, try to use linked apps. Partition the candidates into four lists: 5257 // one for the final results, one for the "do not use ever", one for "undefined status" 5258 // and finally one for "browser app type". 5259 for (int n=0; n<count; n++) { 5260 ResolveInfo info = candidates.get(n); 5261 String packageName = info.activityInfo.packageName; 5262 PackageSetting ps = mSettings.mPackages.get(packageName); 5263 if (ps != null) { 5264 // Add to the special match all list (Browser use case) 5265 if (info.handleAllWebDataURI) { 5266 matchAllList.add(info); 5267 continue; 5268 } 5269 // Try to get the status from User settings first 5270 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5271 int status = (int)(packedStatus >> 32); 5272 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5273 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5274 if (DEBUG_DOMAIN_VERIFICATION) { 5275 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5276 + " : linkgen=" + linkGeneration); 5277 } 5278 // Use link-enabled generation as preferredOrder, i.e. 5279 // prefer newly-enabled over earlier-enabled. 5280 info.preferredOrder = linkGeneration; 5281 alwaysList.add(info); 5282 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5283 if (DEBUG_DOMAIN_VERIFICATION) { 5284 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5285 } 5286 neverList.add(info); 5287 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5288 if (DEBUG_DOMAIN_VERIFICATION) { 5289 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5290 } 5291 alwaysAskList.add(info); 5292 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5293 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5294 if (DEBUG_DOMAIN_VERIFICATION) { 5295 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5296 } 5297 undefinedList.add(info); 5298 } 5299 } 5300 } 5301 5302 // We'll want to include browser possibilities in a few cases 5303 boolean includeBrowser = false; 5304 5305 // First try to add the "always" resolution(s) for the current user, if any 5306 if (alwaysList.size() > 0) { 5307 result.addAll(alwaysList); 5308 } else { 5309 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5310 result.addAll(undefinedList); 5311 // Maybe add one for the other profile. 5312 if (xpDomainInfo != null && ( 5313 xpDomainInfo.bestDomainVerificationStatus 5314 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5315 result.add(xpDomainInfo.resolveInfo); 5316 } 5317 includeBrowser = true; 5318 } 5319 5320 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5321 // If there were 'always' entries their preferred order has been set, so we also 5322 // back that off to make the alternatives equivalent 5323 if (alwaysAskList.size() > 0) { 5324 for (ResolveInfo i : result) { 5325 i.preferredOrder = 0; 5326 } 5327 result.addAll(alwaysAskList); 5328 includeBrowser = true; 5329 } 5330 5331 if (includeBrowser) { 5332 // Also add browsers (all of them or only the default one) 5333 if (DEBUG_DOMAIN_VERIFICATION) { 5334 Slog.v(TAG, " ...including browsers in candidate set"); 5335 } 5336 if ((matchFlags & MATCH_ALL) != 0) { 5337 result.addAll(matchAllList); 5338 } else { 5339 // Browser/generic handling case. If there's a default browser, go straight 5340 // to that (but only if there is no other higher-priority match). 5341 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5342 int maxMatchPrio = 0; 5343 ResolveInfo defaultBrowserMatch = null; 5344 final int numCandidates = matchAllList.size(); 5345 for (int n = 0; n < numCandidates; n++) { 5346 ResolveInfo info = matchAllList.get(n); 5347 // track the highest overall match priority... 5348 if (info.priority > maxMatchPrio) { 5349 maxMatchPrio = info.priority; 5350 } 5351 // ...and the highest-priority default browser match 5352 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5353 if (defaultBrowserMatch == null 5354 || (defaultBrowserMatch.priority < info.priority)) { 5355 if (debug) { 5356 Slog.v(TAG, "Considering default browser match " + info); 5357 } 5358 defaultBrowserMatch = info; 5359 } 5360 } 5361 } 5362 if (defaultBrowserMatch != null 5363 && defaultBrowserMatch.priority >= maxMatchPrio 5364 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5365 { 5366 if (debug) { 5367 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5368 } 5369 result.add(defaultBrowserMatch); 5370 } else { 5371 result.addAll(matchAllList); 5372 } 5373 } 5374 5375 // If there is nothing selected, add all candidates and remove the ones that the user 5376 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5377 if (result.size() == 0) { 5378 result.addAll(candidates); 5379 result.removeAll(neverList); 5380 } 5381 } 5382 } 5383 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5384 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5385 result.size()); 5386 for (ResolveInfo info : result) { 5387 Slog.v(TAG, " + " + info.activityInfo); 5388 } 5389 } 5390 return result; 5391 } 5392 5393 // Returns a packed value as a long: 5394 // 5395 // high 'int'-sized word: link status: undefined/ask/never/always. 5396 // low 'int'-sized word: relative priority among 'always' results. 5397 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5398 long result = ps.getDomainVerificationStatusForUser(userId); 5399 // if none available, get the master status 5400 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5401 if (ps.getIntentFilterVerificationInfo() != null) { 5402 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5403 } 5404 } 5405 return result; 5406 } 5407 5408 private ResolveInfo querySkipCurrentProfileIntents( 5409 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5410 int flags, int sourceUserId) { 5411 if (matchingFilters != null) { 5412 int size = matchingFilters.size(); 5413 for (int i = 0; i < size; i ++) { 5414 CrossProfileIntentFilter filter = matchingFilters.get(i); 5415 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5416 // Checking if there are activities in the target user that can handle the 5417 // intent. 5418 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5419 resolvedType, flags, sourceUserId); 5420 if (resolveInfo != null) { 5421 return resolveInfo; 5422 } 5423 } 5424 } 5425 } 5426 return null; 5427 } 5428 5429 // Return matching ResolveInfo in target user if any. 5430 private ResolveInfo queryCrossProfileIntents( 5431 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5432 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5433 if (matchingFilters != null) { 5434 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5435 // match the same intent. For performance reasons, it is better not to 5436 // run queryIntent twice for the same userId 5437 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5438 int size = matchingFilters.size(); 5439 for (int i = 0; i < size; i++) { 5440 CrossProfileIntentFilter filter = matchingFilters.get(i); 5441 int targetUserId = filter.getTargetUserId(); 5442 boolean skipCurrentProfile = 5443 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5444 boolean skipCurrentProfileIfNoMatchFound = 5445 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5446 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5447 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5448 // Checking if there are activities in the target user that can handle the 5449 // intent. 5450 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5451 resolvedType, flags, sourceUserId); 5452 if (resolveInfo != null) return resolveInfo; 5453 alreadyTriedUserIds.put(targetUserId, true); 5454 } 5455 } 5456 } 5457 return null; 5458 } 5459 5460 /** 5461 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5462 * will forward the intent to the filter's target user. 5463 * Otherwise, returns null. 5464 */ 5465 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5466 String resolvedType, int flags, int sourceUserId) { 5467 int targetUserId = filter.getTargetUserId(); 5468 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5469 resolvedType, flags, targetUserId); 5470 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5471 // If all the matches in the target profile are suspended, return null. 5472 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5473 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5474 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5475 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5476 targetUserId); 5477 } 5478 } 5479 } 5480 return null; 5481 } 5482 5483 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5484 int sourceUserId, int targetUserId) { 5485 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5486 long ident = Binder.clearCallingIdentity(); 5487 boolean targetIsProfile; 5488 try { 5489 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5490 } finally { 5491 Binder.restoreCallingIdentity(ident); 5492 } 5493 String className; 5494 if (targetIsProfile) { 5495 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5496 } else { 5497 className = FORWARD_INTENT_TO_PARENT; 5498 } 5499 ComponentName forwardingActivityComponentName = new ComponentName( 5500 mAndroidApplication.packageName, className); 5501 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5502 sourceUserId); 5503 if (!targetIsProfile) { 5504 forwardingActivityInfo.showUserIcon = targetUserId; 5505 forwardingResolveInfo.noResourceId = true; 5506 } 5507 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5508 forwardingResolveInfo.priority = 0; 5509 forwardingResolveInfo.preferredOrder = 0; 5510 forwardingResolveInfo.match = 0; 5511 forwardingResolveInfo.isDefault = true; 5512 forwardingResolveInfo.filter = filter; 5513 forwardingResolveInfo.targetUserId = targetUserId; 5514 return forwardingResolveInfo; 5515 } 5516 5517 @Override 5518 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5519 Intent[] specifics, String[] specificTypes, Intent intent, 5520 String resolvedType, int flags, int userId) { 5521 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5522 flags = updateFlagsForResolve(flags, userId, intent); 5523 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 5524 false, "query intent activity options"); 5525 final String resultsAction = intent.getAction(); 5526 5527 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 5528 | PackageManager.GET_RESOLVED_FILTER, userId); 5529 5530 if (DEBUG_INTENT_MATCHING) { 5531 Log.v(TAG, "Query " + intent + ": " + results); 5532 } 5533 5534 int specificsPos = 0; 5535 int N; 5536 5537 // todo: note that the algorithm used here is O(N^2). This 5538 // isn't a problem in our current environment, but if we start running 5539 // into situations where we have more than 5 or 10 matches then this 5540 // should probably be changed to something smarter... 5541 5542 // First we go through and resolve each of the specific items 5543 // that were supplied, taking care of removing any corresponding 5544 // duplicate items in the generic resolve list. 5545 if (specifics != null) { 5546 for (int i=0; i<specifics.length; i++) { 5547 final Intent sintent = specifics[i]; 5548 if (sintent == null) { 5549 continue; 5550 } 5551 5552 if (DEBUG_INTENT_MATCHING) { 5553 Log.v(TAG, "Specific #" + i + ": " + sintent); 5554 } 5555 5556 String action = sintent.getAction(); 5557 if (resultsAction != null && resultsAction.equals(action)) { 5558 // If this action was explicitly requested, then don't 5559 // remove things that have it. 5560 action = null; 5561 } 5562 5563 ResolveInfo ri = null; 5564 ActivityInfo ai = null; 5565 5566 ComponentName comp = sintent.getComponent(); 5567 if (comp == null) { 5568 ri = resolveIntent( 5569 sintent, 5570 specificTypes != null ? specificTypes[i] : null, 5571 flags, userId); 5572 if (ri == null) { 5573 continue; 5574 } 5575 if (ri == mResolveInfo) { 5576 // ACK! Must do something better with this. 5577 } 5578 ai = ri.activityInfo; 5579 comp = new ComponentName(ai.applicationInfo.packageName, 5580 ai.name); 5581 } else { 5582 ai = getActivityInfo(comp, flags, userId); 5583 if (ai == null) { 5584 continue; 5585 } 5586 } 5587 5588 // Look for any generic query activities that are duplicates 5589 // of this specific one, and remove them from the results. 5590 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5591 N = results.size(); 5592 int j; 5593 for (j=specificsPos; j<N; j++) { 5594 ResolveInfo sri = results.get(j); 5595 if ((sri.activityInfo.name.equals(comp.getClassName()) 5596 && sri.activityInfo.applicationInfo.packageName.equals( 5597 comp.getPackageName())) 5598 || (action != null && sri.filter.matchAction(action))) { 5599 results.remove(j); 5600 if (DEBUG_INTENT_MATCHING) Log.v( 5601 TAG, "Removing duplicate item from " + j 5602 + " due to specific " + specificsPos); 5603 if (ri == null) { 5604 ri = sri; 5605 } 5606 j--; 5607 N--; 5608 } 5609 } 5610 5611 // Add this specific item to its proper place. 5612 if (ri == null) { 5613 ri = new ResolveInfo(); 5614 ri.activityInfo = ai; 5615 } 5616 results.add(specificsPos, ri); 5617 ri.specificIndex = i; 5618 specificsPos++; 5619 } 5620 } 5621 5622 // Now we go through the remaining generic results and remove any 5623 // duplicate actions that are found here. 5624 N = results.size(); 5625 for (int i=specificsPos; i<N-1; i++) { 5626 final ResolveInfo rii = results.get(i); 5627 if (rii.filter == null) { 5628 continue; 5629 } 5630 5631 // Iterate over all of the actions of this result's intent 5632 // filter... typically this should be just one. 5633 final Iterator<String> it = rii.filter.actionsIterator(); 5634 if (it == null) { 5635 continue; 5636 } 5637 while (it.hasNext()) { 5638 final String action = it.next(); 5639 if (resultsAction != null && resultsAction.equals(action)) { 5640 // If this action was explicitly requested, then don't 5641 // remove things that have it. 5642 continue; 5643 } 5644 for (int j=i+1; j<N; j++) { 5645 final ResolveInfo rij = results.get(j); 5646 if (rij.filter != null && rij.filter.hasAction(action)) { 5647 results.remove(j); 5648 if (DEBUG_INTENT_MATCHING) Log.v( 5649 TAG, "Removing duplicate item from " + j 5650 + " due to action " + action + " at " + i); 5651 j--; 5652 N--; 5653 } 5654 } 5655 } 5656 5657 // If the caller didn't request filter information, drop it now 5658 // so we don't have to marshall/unmarshall it. 5659 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5660 rii.filter = null; 5661 } 5662 } 5663 5664 // Filter out the caller activity if so requested. 5665 if (caller != null) { 5666 N = results.size(); 5667 for (int i=0; i<N; i++) { 5668 ActivityInfo ainfo = results.get(i).activityInfo; 5669 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5670 && caller.getClassName().equals(ainfo.name)) { 5671 results.remove(i); 5672 break; 5673 } 5674 } 5675 } 5676 5677 // If the caller didn't request filter information, 5678 // drop them now so we don't have to 5679 // marshall/unmarshall it. 5680 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5681 N = results.size(); 5682 for (int i=0; i<N; i++) { 5683 results.get(i).filter = null; 5684 } 5685 } 5686 5687 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5688 return results; 5689 } 5690 5691 @Override 5692 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5693 int userId) { 5694 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5695 flags = updateFlagsForResolve(flags, userId, intent); 5696 ComponentName comp = intent.getComponent(); 5697 if (comp == null) { 5698 if (intent.getSelector() != null) { 5699 intent = intent.getSelector(); 5700 comp = intent.getComponent(); 5701 } 5702 } 5703 if (comp != null) { 5704 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5705 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5706 if (ai != null) { 5707 ResolveInfo ri = new ResolveInfo(); 5708 ri.activityInfo = ai; 5709 list.add(ri); 5710 } 5711 return list; 5712 } 5713 5714 // reader 5715 synchronized (mPackages) { 5716 String pkgName = intent.getPackage(); 5717 if (pkgName == null) { 5718 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5719 } 5720 final PackageParser.Package pkg = mPackages.get(pkgName); 5721 if (pkg != null) { 5722 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5723 userId); 5724 } 5725 return null; 5726 } 5727 } 5728 5729 @Override 5730 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5731 if (!sUserManager.exists(userId)) return null; 5732 flags = updateFlagsForResolve(flags, userId, intent); 5733 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5734 if (query != null) { 5735 if (query.size() >= 1) { 5736 // If there is more than one service with the same priority, 5737 // just arbitrarily pick the first one. 5738 return query.get(0); 5739 } 5740 } 5741 return null; 5742 } 5743 5744 @Override 5745 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5746 int userId) { 5747 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5748 flags = updateFlagsForResolve(flags, userId, intent); 5749 ComponentName comp = intent.getComponent(); 5750 if (comp == null) { 5751 if (intent.getSelector() != null) { 5752 intent = intent.getSelector(); 5753 comp = intent.getComponent(); 5754 } 5755 } 5756 if (comp != null) { 5757 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5758 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5759 if (si != null) { 5760 final ResolveInfo ri = new ResolveInfo(); 5761 ri.serviceInfo = si; 5762 list.add(ri); 5763 } 5764 return list; 5765 } 5766 5767 // reader 5768 synchronized (mPackages) { 5769 String pkgName = intent.getPackage(); 5770 if (pkgName == null) { 5771 return mServices.queryIntent(intent, resolvedType, flags, userId); 5772 } 5773 final PackageParser.Package pkg = mPackages.get(pkgName); 5774 if (pkg != null) { 5775 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5776 userId); 5777 } 5778 return null; 5779 } 5780 } 5781 5782 @Override 5783 public List<ResolveInfo> queryIntentContentProviders( 5784 Intent intent, String resolvedType, int flags, int userId) { 5785 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5786 flags = updateFlagsForResolve(flags, userId, intent); 5787 ComponentName comp = intent.getComponent(); 5788 if (comp == null) { 5789 if (intent.getSelector() != null) { 5790 intent = intent.getSelector(); 5791 comp = intent.getComponent(); 5792 } 5793 } 5794 if (comp != null) { 5795 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5796 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5797 if (pi != null) { 5798 final ResolveInfo ri = new ResolveInfo(); 5799 ri.providerInfo = pi; 5800 list.add(ri); 5801 } 5802 return list; 5803 } 5804 5805 // reader 5806 synchronized (mPackages) { 5807 String pkgName = intent.getPackage(); 5808 if (pkgName == null) { 5809 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5810 } 5811 final PackageParser.Package pkg = mPackages.get(pkgName); 5812 if (pkg != null) { 5813 return mProviders.queryIntentForPackage( 5814 intent, resolvedType, flags, pkg.providers, userId); 5815 } 5816 return null; 5817 } 5818 } 5819 5820 @Override 5821 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5822 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5823 flags = updateFlagsForPackage(flags, userId, null); 5824 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5825 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5826 5827 // writer 5828 synchronized (mPackages) { 5829 ArrayList<PackageInfo> list; 5830 if (listUninstalled) { 5831 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5832 for (PackageSetting ps : mSettings.mPackages.values()) { 5833 PackageInfo pi; 5834 if (ps.pkg != null) { 5835 pi = generatePackageInfo(ps.pkg, flags, userId); 5836 } else { 5837 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5838 } 5839 if (pi != null) { 5840 list.add(pi); 5841 } 5842 } 5843 } else { 5844 list = new ArrayList<PackageInfo>(mPackages.size()); 5845 for (PackageParser.Package p : mPackages.values()) { 5846 PackageInfo pi = generatePackageInfo(p, flags, userId); 5847 if (pi != null) { 5848 list.add(pi); 5849 } 5850 } 5851 } 5852 5853 return new ParceledListSlice<PackageInfo>(list); 5854 } 5855 } 5856 5857 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5858 String[] permissions, boolean[] tmp, int flags, int userId) { 5859 int numMatch = 0; 5860 final PermissionsState permissionsState = ps.getPermissionsState(); 5861 for (int i=0; i<permissions.length; i++) { 5862 final String permission = permissions[i]; 5863 if (permissionsState.hasPermission(permission, userId)) { 5864 tmp[i] = true; 5865 numMatch++; 5866 } else { 5867 tmp[i] = false; 5868 } 5869 } 5870 if (numMatch == 0) { 5871 return; 5872 } 5873 PackageInfo pi; 5874 if (ps.pkg != null) { 5875 pi = generatePackageInfo(ps.pkg, flags, userId); 5876 } else { 5877 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5878 } 5879 // The above might return null in cases of uninstalled apps or install-state 5880 // skew across users/profiles. 5881 if (pi != null) { 5882 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5883 if (numMatch == permissions.length) { 5884 pi.requestedPermissions = permissions; 5885 } else { 5886 pi.requestedPermissions = new String[numMatch]; 5887 numMatch = 0; 5888 for (int i=0; i<permissions.length; i++) { 5889 if (tmp[i]) { 5890 pi.requestedPermissions[numMatch] = permissions[i]; 5891 numMatch++; 5892 } 5893 } 5894 } 5895 } 5896 list.add(pi); 5897 } 5898 } 5899 5900 @Override 5901 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5902 String[] permissions, int flags, int userId) { 5903 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5904 flags = updateFlagsForPackage(flags, userId, permissions); 5905 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5906 5907 // writer 5908 synchronized (mPackages) { 5909 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5910 boolean[] tmpBools = new boolean[permissions.length]; 5911 if (listUninstalled) { 5912 for (PackageSetting ps : mSettings.mPackages.values()) { 5913 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5914 } 5915 } else { 5916 for (PackageParser.Package pkg : mPackages.values()) { 5917 PackageSetting ps = (PackageSetting)pkg.mExtras; 5918 if (ps != null) { 5919 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5920 userId); 5921 } 5922 } 5923 } 5924 5925 return new ParceledListSlice<PackageInfo>(list); 5926 } 5927 } 5928 5929 @Override 5930 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5931 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5932 flags = updateFlagsForApplication(flags, userId, null); 5933 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5934 5935 // writer 5936 synchronized (mPackages) { 5937 ArrayList<ApplicationInfo> list; 5938 if (listUninstalled) { 5939 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5940 for (PackageSetting ps : mSettings.mPackages.values()) { 5941 ApplicationInfo ai; 5942 if (ps.pkg != null) { 5943 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5944 ps.readUserState(userId), userId); 5945 } else { 5946 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5947 } 5948 if (ai != null) { 5949 list.add(ai); 5950 } 5951 } 5952 } else { 5953 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5954 for (PackageParser.Package p : mPackages.values()) { 5955 if (p.mExtras != null) { 5956 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5957 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5958 if (ai != null) { 5959 list.add(ai); 5960 } 5961 } 5962 } 5963 } 5964 5965 return new ParceledListSlice<ApplicationInfo>(list); 5966 } 5967 } 5968 5969 @Override 5970 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 5971 if (DISABLE_EPHEMERAL_APPS) { 5972 return null; 5973 } 5974 5975 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 5976 "getEphemeralApplications"); 5977 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5978 "getEphemeralApplications"); 5979 synchronized (mPackages) { 5980 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 5981 .getEphemeralApplicationsLPw(userId); 5982 if (ephemeralApps != null) { 5983 return new ParceledListSlice<>(ephemeralApps); 5984 } 5985 } 5986 return null; 5987 } 5988 5989 @Override 5990 public boolean isEphemeralApplication(String packageName, int userId) { 5991 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5992 "isEphemeral"); 5993 if (DISABLE_EPHEMERAL_APPS) { 5994 return false; 5995 } 5996 5997 if (!isCallerSameApp(packageName)) { 5998 return false; 5999 } 6000 synchronized (mPackages) { 6001 PackageParser.Package pkg = mPackages.get(packageName); 6002 if (pkg != null) { 6003 return pkg.applicationInfo.isEphemeralApp(); 6004 } 6005 } 6006 return false; 6007 } 6008 6009 @Override 6010 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6011 if (DISABLE_EPHEMERAL_APPS) { 6012 return null; 6013 } 6014 6015 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 6016 "getCookie"); 6017 if (!isCallerSameApp(packageName)) { 6018 return null; 6019 } 6020 synchronized (mPackages) { 6021 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6022 packageName, userId); 6023 } 6024 } 6025 6026 @Override 6027 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6028 if (DISABLE_EPHEMERAL_APPS) { 6029 return true; 6030 } 6031 6032 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 6033 "setCookie"); 6034 if (!isCallerSameApp(packageName)) { 6035 return false; 6036 } 6037 synchronized (mPackages) { 6038 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6039 packageName, cookie, userId); 6040 } 6041 } 6042 6043 @Override 6044 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6045 if (DISABLE_EPHEMERAL_APPS) { 6046 return null; 6047 } 6048 6049 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6050 "getEphemeralApplicationIcon"); 6051 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 6052 "getEphemeralApplicationIcon"); 6053 synchronized (mPackages) { 6054 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6055 packageName, userId); 6056 } 6057 } 6058 6059 private boolean isCallerSameApp(String packageName) { 6060 PackageParser.Package pkg = mPackages.get(packageName); 6061 return pkg != null 6062 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6063 } 6064 6065 public List<ApplicationInfo> getPersistentApplications(int flags) { 6066 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6067 6068 // reader 6069 synchronized (mPackages) { 6070 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6071 final int userId = UserHandle.getCallingUserId(); 6072 while (i.hasNext()) { 6073 final PackageParser.Package p = i.next(); 6074 if (p.applicationInfo != null 6075 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 6076 && (!mSafeMode || isSystemApp(p))) { 6077 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6078 if (ps != null) { 6079 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6080 ps.readUserState(userId), userId); 6081 if (ai != null) { 6082 finalList.add(ai); 6083 } 6084 } 6085 } 6086 } 6087 } 6088 6089 return finalList; 6090 } 6091 6092 @Override 6093 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6094 if (!sUserManager.exists(userId)) return null; 6095 flags = updateFlagsForComponent(flags, userId, name); 6096 // reader 6097 synchronized (mPackages) { 6098 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6099 PackageSetting ps = provider != null 6100 ? mSettings.mPackages.get(provider.owner.packageName) 6101 : null; 6102 return ps != null 6103 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6104 ? PackageParser.generateProviderInfo(provider, flags, 6105 ps.readUserState(userId), userId) 6106 : null; 6107 } 6108 } 6109 6110 /** 6111 * @deprecated 6112 */ 6113 @Deprecated 6114 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6115 // reader 6116 synchronized (mPackages) { 6117 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6118 .entrySet().iterator(); 6119 final int userId = UserHandle.getCallingUserId(); 6120 while (i.hasNext()) { 6121 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6122 PackageParser.Provider p = entry.getValue(); 6123 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6124 6125 if (ps != null && p.syncable 6126 && (!mSafeMode || (p.info.applicationInfo.flags 6127 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6128 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6129 ps.readUserState(userId), userId); 6130 if (info != null) { 6131 outNames.add(entry.getKey()); 6132 outInfo.add(info); 6133 } 6134 } 6135 } 6136 } 6137 } 6138 6139 @Override 6140 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6141 int uid, int flags) { 6142 final int userId = processName != null ? UserHandle.getUserId(uid) 6143 : UserHandle.getCallingUserId(); 6144 if (!sUserManager.exists(userId)) return null; 6145 flags = updateFlagsForComponent(flags, userId, processName); 6146 6147 ArrayList<ProviderInfo> finalList = null; 6148 // reader 6149 synchronized (mPackages) { 6150 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6151 while (i.hasNext()) { 6152 final PackageParser.Provider p = i.next(); 6153 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6154 if (ps != null && p.info.authority != null 6155 && (processName == null 6156 || (p.info.processName.equals(processName) 6157 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6158 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6159 if (finalList == null) { 6160 finalList = new ArrayList<ProviderInfo>(3); 6161 } 6162 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6163 ps.readUserState(userId), userId); 6164 if (info != null) { 6165 finalList.add(info); 6166 } 6167 } 6168 } 6169 } 6170 6171 if (finalList != null) { 6172 Collections.sort(finalList, mProviderInitOrderSorter); 6173 return new ParceledListSlice<ProviderInfo>(finalList); 6174 } 6175 6176 return null; 6177 } 6178 6179 @Override 6180 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6181 // reader 6182 synchronized (mPackages) { 6183 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6184 return PackageParser.generateInstrumentationInfo(i, flags); 6185 } 6186 } 6187 6188 @Override 6189 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 6190 int flags) { 6191 ArrayList<InstrumentationInfo> finalList = 6192 new ArrayList<InstrumentationInfo>(); 6193 6194 // reader 6195 synchronized (mPackages) { 6196 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6197 while (i.hasNext()) { 6198 final PackageParser.Instrumentation p = i.next(); 6199 if (targetPackage == null 6200 || targetPackage.equals(p.info.targetPackage)) { 6201 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6202 flags); 6203 if (ii != null) { 6204 finalList.add(ii); 6205 } 6206 } 6207 } 6208 } 6209 6210 return finalList; 6211 } 6212 6213 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6214 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6215 if (overlays == null) { 6216 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6217 return; 6218 } 6219 for (PackageParser.Package opkg : overlays.values()) { 6220 // Not much to do if idmap fails: we already logged the error 6221 // and we certainly don't want to abort installation of pkg simply 6222 // because an overlay didn't fit properly. For these reasons, 6223 // ignore the return value of createIdmapForPackagePairLI. 6224 createIdmapForPackagePairLI(pkg, opkg); 6225 } 6226 } 6227 6228 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6229 PackageParser.Package opkg) { 6230 if (!opkg.mTrustedOverlay) { 6231 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6232 opkg.baseCodePath + ": overlay not trusted"); 6233 return false; 6234 } 6235 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6236 if (overlaySet == null) { 6237 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6238 opkg.baseCodePath + " but target package has no known overlays"); 6239 return false; 6240 } 6241 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6242 // TODO: generate idmap for split APKs 6243 try { 6244 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6245 } catch (InstallerException e) { 6246 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6247 + opkg.baseCodePath); 6248 return false; 6249 } 6250 PackageParser.Package[] overlayArray = 6251 overlaySet.values().toArray(new PackageParser.Package[0]); 6252 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6253 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6254 return p1.mOverlayPriority - p2.mOverlayPriority; 6255 } 6256 }; 6257 Arrays.sort(overlayArray, cmp); 6258 6259 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6260 int i = 0; 6261 for (PackageParser.Package p : overlayArray) { 6262 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6263 } 6264 return true; 6265 } 6266 6267 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6268 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6269 try { 6270 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6271 } finally { 6272 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6273 } 6274 } 6275 6276 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6277 final File[] files = dir.listFiles(); 6278 if (ArrayUtils.isEmpty(files)) { 6279 Log.d(TAG, "No files in app dir " + dir); 6280 return; 6281 } 6282 6283 if (DEBUG_PACKAGE_SCANNING) { 6284 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6285 + " flags=0x" + Integer.toHexString(parseFlags)); 6286 } 6287 6288 for (File file : files) { 6289 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6290 && !PackageInstallerService.isStageName(file.getName()); 6291 if (!isPackage) { 6292 // Ignore entries which are not packages 6293 continue; 6294 } 6295 try { 6296 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6297 scanFlags, currentTime, null); 6298 } catch (PackageManagerException e) { 6299 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6300 6301 // Delete invalid userdata apps 6302 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6303 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6304 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6305 removeCodePathLI(file); 6306 } 6307 } 6308 } 6309 } 6310 6311 private static File getSettingsProblemFile() { 6312 File dataDir = Environment.getDataDirectory(); 6313 File systemDir = new File(dataDir, "system"); 6314 File fname = new File(systemDir, "uiderrors.txt"); 6315 return fname; 6316 } 6317 6318 static void reportSettingsProblem(int priority, String msg) { 6319 logCriticalInfo(priority, msg); 6320 } 6321 6322 static void logCriticalInfo(int priority, String msg) { 6323 Slog.println(priority, TAG, msg); 6324 EventLogTags.writePmCriticalInfo(msg); 6325 try { 6326 File fname = getSettingsProblemFile(); 6327 FileOutputStream out = new FileOutputStream(fname, true); 6328 PrintWriter pw = new FastPrintWriter(out); 6329 SimpleDateFormat formatter = new SimpleDateFormat(); 6330 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6331 pw.println(dateString + ": " + msg); 6332 pw.close(); 6333 FileUtils.setPermissions( 6334 fname.toString(), 6335 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6336 -1, -1); 6337 } catch (java.io.IOException e) { 6338 } 6339 } 6340 6341 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6342 int parseFlags) throws PackageManagerException { 6343 if (ps != null 6344 && ps.codePath.equals(srcFile) 6345 && ps.timeStamp == srcFile.lastModified() 6346 && !isCompatSignatureUpdateNeeded(pkg) 6347 && !isRecoverSignatureUpdateNeeded(pkg)) { 6348 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6349 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6350 ArraySet<PublicKey> signingKs; 6351 synchronized (mPackages) { 6352 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6353 } 6354 if (ps.signatures.mSignatures != null 6355 && ps.signatures.mSignatures.length != 0 6356 && signingKs != null) { 6357 // Optimization: reuse the existing cached certificates 6358 // if the package appears to be unchanged. 6359 pkg.mSignatures = ps.signatures.mSignatures; 6360 pkg.mSigningKeys = signingKs; 6361 return; 6362 } 6363 6364 Slog.w(TAG, "PackageSetting for " + ps.name 6365 + " is missing signatures. Collecting certs again to recover them."); 6366 } else { 6367 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6368 } 6369 6370 try { 6371 PackageParser.collectCertificates(pkg, parseFlags); 6372 } catch (PackageParserException e) { 6373 throw PackageManagerException.from(e); 6374 } 6375 } 6376 6377 /** 6378 * Traces a package scan. 6379 * @see #scanPackageLI(File, int, int, long, UserHandle) 6380 */ 6381 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6382 long currentTime, UserHandle user) throws PackageManagerException { 6383 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6384 try { 6385 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6386 } finally { 6387 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6388 } 6389 } 6390 6391 /** 6392 * Scans a package and returns the newly parsed package. 6393 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6394 */ 6395 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6396 long currentTime, UserHandle user) throws PackageManagerException { 6397 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6398 parseFlags |= mDefParseFlags; 6399 PackageParser pp = new PackageParser(); 6400 pp.setSeparateProcesses(mSeparateProcesses); 6401 pp.setOnlyCoreApps(mOnlyCore); 6402 pp.setDisplayMetrics(mMetrics); 6403 6404 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6405 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6406 } 6407 6408 final PackageParser.Package pkg; 6409 try { 6410 pkg = pp.parsePackage(scanFile, parseFlags); 6411 } catch (PackageParserException e) { 6412 throw PackageManagerException.from(e); 6413 } 6414 6415 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6416 } 6417 6418 /** 6419 * Scans a package and returns the newly parsed package. 6420 * @throws PackageManagerException on a parse error. 6421 */ 6422 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6423 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6424 throws PackageManagerException { 6425 // If the package has children and this is the first dive in the function 6426 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6427 // packages (parent and children) would be successfully scanned before the 6428 // actual scan since scanning mutates internal state and we want to atomically 6429 // install the package and its children. 6430 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6431 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6432 scanFlags |= SCAN_CHECK_ONLY; 6433 } 6434 } else { 6435 scanFlags &= ~SCAN_CHECK_ONLY; 6436 } 6437 6438 // Scan the parent 6439 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags, 6440 scanFlags, currentTime, user); 6441 6442 // Scan the children 6443 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6444 for (int i = 0; i < childCount; i++) { 6445 PackageParser.Package childPackage = pkg.childPackages.get(i); 6446 scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags, 6447 currentTime, user); 6448 } 6449 6450 6451 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6452 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6453 } 6454 6455 return scannedPkg; 6456 } 6457 6458 /** 6459 * Scans a package and returns the newly parsed package. 6460 * @throws PackageManagerException on a parse error. 6461 */ 6462 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6463 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6464 throws PackageManagerException { 6465 PackageSetting ps = null; 6466 PackageSetting updatedPkg; 6467 // reader 6468 synchronized (mPackages) { 6469 // Look to see if we already know about this package. 6470 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6471 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6472 // This package has been renamed to its original name. Let's 6473 // use that. 6474 ps = mSettings.peekPackageLPr(oldName); 6475 } 6476 // If there was no original package, see one for the real package name. 6477 if (ps == null) { 6478 ps = mSettings.peekPackageLPr(pkg.packageName); 6479 } 6480 // Check to see if this package could be hiding/updating a system 6481 // package. Must look for it either under the original or real 6482 // package name depending on our state. 6483 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6484 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6485 6486 // If this is a package we don't know about on the system partition, we 6487 // may need to remove disabled child packages on the system partition 6488 // or may need to not add child packages if the parent apk is updated 6489 // on the data partition and no longer defines this child package. 6490 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6491 // If this is a parent package for an updated system app and this system 6492 // app got an OTA update which no longer defines some of the child packages 6493 // we have to prune them from the disabled system packages. 6494 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6495 if (disabledPs != null) { 6496 final int scannedChildCount = (pkg.childPackages != null) 6497 ? pkg.childPackages.size() : 0; 6498 final int disabledChildCount = disabledPs.childPackageNames != null 6499 ? disabledPs.childPackageNames.size() : 0; 6500 for (int i = 0; i < disabledChildCount; i++) { 6501 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6502 boolean disabledPackageAvailable = false; 6503 for (int j = 0; j < scannedChildCount; j++) { 6504 PackageParser.Package childPkg = pkg.childPackages.get(j); 6505 if (childPkg.packageName.equals(disabledChildPackageName)) { 6506 disabledPackageAvailable = true; 6507 break; 6508 } 6509 } 6510 if (!disabledPackageAvailable) { 6511 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6512 } 6513 } 6514 } 6515 } 6516 } 6517 6518 boolean updatedPkgBetter = false; 6519 // First check if this is a system package that may involve an update 6520 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6521 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6522 // it needs to drop FLAG_PRIVILEGED. 6523 if (locationIsPrivileged(scanFile)) { 6524 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6525 } else { 6526 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6527 } 6528 6529 if (ps != null && !ps.codePath.equals(scanFile)) { 6530 // The path has changed from what was last scanned... check the 6531 // version of the new path against what we have stored to determine 6532 // what to do. 6533 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6534 if (pkg.mVersionCode <= ps.versionCode) { 6535 // The system package has been updated and the code path does not match 6536 // Ignore entry. Skip it. 6537 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6538 + " ignored: updated version " + ps.versionCode 6539 + " better than this " + pkg.mVersionCode); 6540 if (!updatedPkg.codePath.equals(scanFile)) { 6541 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6542 + ps.name + " changing from " + updatedPkg.codePathString 6543 + " to " + scanFile); 6544 updatedPkg.codePath = scanFile; 6545 updatedPkg.codePathString = scanFile.toString(); 6546 updatedPkg.resourcePath = scanFile; 6547 updatedPkg.resourcePathString = scanFile.toString(); 6548 } 6549 updatedPkg.pkg = pkg; 6550 updatedPkg.versionCode = pkg.mVersionCode; 6551 6552 // Update the disabled system child packages to point to the package too. 6553 final int childCount = updatedPkg.childPackageNames != null 6554 ? updatedPkg.childPackageNames.size() : 0; 6555 for (int i = 0; i < childCount; i++) { 6556 String childPackageName = updatedPkg.childPackageNames.get(i); 6557 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6558 childPackageName); 6559 if (updatedChildPkg != null) { 6560 updatedChildPkg.pkg = pkg; 6561 updatedChildPkg.versionCode = pkg.mVersionCode; 6562 } 6563 } 6564 6565 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6566 + scanFile + " ignored: updated version " + ps.versionCode 6567 + " better than this " + pkg.mVersionCode); 6568 } else { 6569 // The current app on the system partition is better than 6570 // what we have updated to on the data partition; switch 6571 // back to the system partition version. 6572 // At this point, its safely assumed that package installation for 6573 // apps in system partition will go through. If not there won't be a working 6574 // version of the app 6575 // writer 6576 synchronized (mPackages) { 6577 // Just remove the loaded entries from package lists. 6578 mPackages.remove(ps.name); 6579 } 6580 6581 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6582 + " reverting from " + ps.codePathString 6583 + ": new version " + pkg.mVersionCode 6584 + " better than installed " + ps.versionCode); 6585 6586 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6587 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6588 synchronized (mInstallLock) { 6589 args.cleanUpResourcesLI(); 6590 } 6591 synchronized (mPackages) { 6592 mSettings.enableSystemPackageLPw(ps.name); 6593 } 6594 updatedPkgBetter = true; 6595 } 6596 } 6597 } 6598 6599 if (updatedPkg != null) { 6600 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6601 // initially 6602 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6603 6604 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6605 // flag set initially 6606 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6607 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6608 } 6609 } 6610 6611 // Verify certificates against what was last scanned 6612 collectCertificatesLI(ps, pkg, scanFile, parseFlags); 6613 6614 /* 6615 * A new system app appeared, but we already had a non-system one of the 6616 * same name installed earlier. 6617 */ 6618 boolean shouldHideSystemApp = false; 6619 if (updatedPkg == null && ps != null 6620 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6621 /* 6622 * Check to make sure the signatures match first. If they don't, 6623 * wipe the installed application and its data. 6624 */ 6625 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6626 != PackageManager.SIGNATURE_MATCH) { 6627 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6628 + " signatures don't match existing userdata copy; removing"); 6629 deletePackageLI(pkg.packageName, null, true, null, 0, null, false, null); 6630 ps = null; 6631 } else { 6632 /* 6633 * If the newly-added system app is an older version than the 6634 * already installed version, hide it. It will be scanned later 6635 * and re-added like an update. 6636 */ 6637 if (pkg.mVersionCode <= ps.versionCode) { 6638 shouldHideSystemApp = true; 6639 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6640 + " but new version " + pkg.mVersionCode + " better than installed " 6641 + ps.versionCode + "; hiding system"); 6642 } else { 6643 /* 6644 * The newly found system app is a newer version that the 6645 * one previously installed. Simply remove the 6646 * already-installed application and replace it with our own 6647 * while keeping the application data. 6648 */ 6649 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6650 + " reverting from " + ps.codePathString + ": new version " 6651 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6652 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6653 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6654 synchronized (mInstallLock) { 6655 args.cleanUpResourcesLI(); 6656 } 6657 } 6658 } 6659 } 6660 6661 // The apk is forward locked (not public) if its code and resources 6662 // are kept in different files. (except for app in either system or 6663 // vendor path). 6664 // TODO grab this value from PackageSettings 6665 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6666 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6667 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6668 } 6669 } 6670 6671 // TODO: extend to support forward-locked splits 6672 String resourcePath = null; 6673 String baseResourcePath = null; 6674 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6675 if (ps != null && ps.resourcePathString != null) { 6676 resourcePath = ps.resourcePathString; 6677 baseResourcePath = ps.resourcePathString; 6678 } else { 6679 // Should not happen at all. Just log an error. 6680 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6681 } 6682 } else { 6683 resourcePath = pkg.codePath; 6684 baseResourcePath = pkg.baseCodePath; 6685 } 6686 6687 // Set application objects path explicitly. 6688 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 6689 pkg.setApplicationInfoCodePath(pkg.codePath); 6690 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 6691 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 6692 pkg.setApplicationInfoResourcePath(resourcePath); 6693 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 6694 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 6695 6696 // Note that we invoke the following method only if we are about to unpack an application 6697 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6698 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6699 6700 /* 6701 * If the system app should be overridden by a previously installed 6702 * data, hide the system app now and let the /data/app scan pick it up 6703 * again. 6704 */ 6705 if (shouldHideSystemApp) { 6706 synchronized (mPackages) { 6707 mSettings.disableSystemPackageLPw(pkg.packageName, true); 6708 } 6709 } 6710 6711 return scannedPkg; 6712 } 6713 6714 private static String fixProcessName(String defProcessName, 6715 String processName, int uid) { 6716 if (processName == null) { 6717 return defProcessName; 6718 } 6719 return processName; 6720 } 6721 6722 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6723 throws PackageManagerException { 6724 if (pkgSetting.signatures.mSignatures != null) { 6725 // Already existing package. Make sure signatures match 6726 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6727 == PackageManager.SIGNATURE_MATCH; 6728 if (!match) { 6729 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6730 == PackageManager.SIGNATURE_MATCH; 6731 } 6732 if (!match) { 6733 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6734 == PackageManager.SIGNATURE_MATCH; 6735 } 6736 if (!match) { 6737 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6738 + pkg.packageName + " signatures do not match the " 6739 + "previously installed version; ignoring!"); 6740 } 6741 } 6742 6743 // Check for shared user signatures 6744 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6745 // Already existing package. Make sure signatures match 6746 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6747 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6748 if (!match) { 6749 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6750 == PackageManager.SIGNATURE_MATCH; 6751 } 6752 if (!match) { 6753 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6754 == PackageManager.SIGNATURE_MATCH; 6755 } 6756 if (!match) { 6757 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6758 "Package " + pkg.packageName 6759 + " has no signatures that match those in shared user " 6760 + pkgSetting.sharedUser.name + "; ignoring!"); 6761 } 6762 } 6763 } 6764 6765 /** 6766 * Enforces that only the system UID or root's UID can call a method exposed 6767 * via Binder. 6768 * 6769 * @param message used as message if SecurityException is thrown 6770 * @throws SecurityException if the caller is not system or root 6771 */ 6772 private static final void enforceSystemOrRoot(String message) { 6773 final int uid = Binder.getCallingUid(); 6774 if (uid != Process.SYSTEM_UID && uid != 0) { 6775 throw new SecurityException(message); 6776 } 6777 } 6778 6779 @Override 6780 public void performFstrimIfNeeded() { 6781 enforceSystemOrRoot("Only the system can request fstrim"); 6782 6783 // Before everything else, see whether we need to fstrim. 6784 try { 6785 IMountService ms = PackageHelper.getMountService(); 6786 if (ms != null) { 6787 final boolean isUpgrade = isUpgrade(); 6788 boolean doTrim = isUpgrade; 6789 if (doTrim) { 6790 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6791 } else { 6792 final long interval = android.provider.Settings.Global.getLong( 6793 mContext.getContentResolver(), 6794 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6795 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6796 if (interval > 0) { 6797 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6798 if (timeSinceLast > interval) { 6799 doTrim = true; 6800 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6801 + "; running immediately"); 6802 } 6803 } 6804 } 6805 if (doTrim) { 6806 if (!isFirstBoot()) { 6807 try { 6808 ActivityManagerNative.getDefault().showBootMessage( 6809 mContext.getResources().getString( 6810 R.string.android_upgrading_fstrim), true); 6811 } catch (RemoteException e) { 6812 } 6813 } 6814 ms.runMaintenance(); 6815 } 6816 } else { 6817 Slog.e(TAG, "Mount service unavailable!"); 6818 } 6819 } catch (RemoteException e) { 6820 // Can't happen; MountService is local 6821 } 6822 } 6823 6824 @Override 6825 public void extractPackagesIfNeeded() { 6826 enforceSystemOrRoot("Only the system can request package extraction"); 6827 6828 // Extract pacakges only if profile-guided compilation is enabled because 6829 // otherwise BackgroundDexOptService will not dexopt them later. 6830 if (mUseJitProfiles) { 6831 List<PackageParser.Package> pkgs; 6832 synchronized (mPackages) { 6833 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 6834 } 6835 for (PackageParser.Package pkg : pkgs) { 6836 if (PackageDexOptimizer.canOptimizePackage(pkg)) { 6837 performDexOpt(pkg.packageName, null /* instructionSet */, 6838 false /* useProfiles */, true /* extractOnly */, false /* force */); 6839 } 6840 } 6841 } 6842 } 6843 6844 @Override 6845 public void notifyPackageUse(String packageName) { 6846 synchronized (mPackages) { 6847 PackageParser.Package p = mPackages.get(packageName); 6848 if (p == null) { 6849 return; 6850 } 6851 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6852 } 6853 } 6854 6855 // TODO: this is not used nor needed. Delete it. 6856 @Override 6857 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6858 return performDexOptTraced(packageName, instructionSet, false /* useProfiles */, 6859 false /* extractOnly */, false /* force */); 6860 } 6861 6862 @Override 6863 public boolean performDexOpt(String packageName, String instructionSet, boolean useProfiles, 6864 boolean extractOnly, boolean force) { 6865 return performDexOptTraced(packageName, instructionSet, useProfiles, extractOnly, force); 6866 } 6867 6868 private boolean performDexOptTraced(String packageName, String instructionSet, 6869 boolean useProfiles, boolean extractOnly, boolean force) { 6870 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6871 try { 6872 return performDexOptInternal(packageName, instructionSet, useProfiles, extractOnly, 6873 force); 6874 } finally { 6875 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6876 } 6877 } 6878 6879 private boolean performDexOptInternal(String packageName, String instructionSet, 6880 boolean useProfiles, boolean extractOnly, boolean force) { 6881 PackageParser.Package p; 6882 final String targetInstructionSet; 6883 synchronized (mPackages) { 6884 p = mPackages.get(packageName); 6885 if (p == null) { 6886 return false; 6887 } 6888 mPackageUsage.write(false); 6889 6890 targetInstructionSet = instructionSet != null ? instructionSet : 6891 getPrimaryInstructionSet(p.applicationInfo); 6892 if (!force && !useProfiles && p.mDexOptPerformed.contains(targetInstructionSet)) { 6893 // Skip only if we do not use profiles since they might trigger a recompilation. 6894 return false; 6895 } 6896 } 6897 long callingId = Binder.clearCallingIdentity(); 6898 try { 6899 synchronized (mInstallLock) { 6900 final String[] instructionSets = new String[] { targetInstructionSet }; 6901 int result = performDexOptInternalWithDependenciesLI(p, instructionSets, 6902 useProfiles, extractOnly, force); 6903 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6904 } 6905 } finally { 6906 Binder.restoreCallingIdentity(callingId); 6907 } 6908 } 6909 6910 public ArraySet<String> getOptimizablePackages() { 6911 ArraySet<String> pkgs = new ArraySet<String>(); 6912 synchronized (mPackages) { 6913 for (PackageParser.Package p : mPackages.values()) { 6914 if (PackageDexOptimizer.canOptimizePackage(p)) { 6915 pkgs.add(p.packageName); 6916 } 6917 } 6918 } 6919 return pkgs; 6920 } 6921 6922 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 6923 String instructionSets[], boolean useProfiles, boolean extractOnly, boolean force) { 6924 // Select the dex optimizer based on the force parameter. 6925 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 6926 // allocate an object here. 6927 PackageDexOptimizer pdo = force 6928 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 6929 : mPackageDexOptimizer; 6930 6931 // Optimize all dependencies first. Note: we ignore the return value and march on 6932 // on errors. 6933 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 6934 if (!deps.isEmpty()) { 6935 for (PackageParser.Package depPackage : deps) { 6936 // TODO: Analyze and investigate if we (should) profile libraries. 6937 // Currently this will do a full compilation of the library. 6938 pdo.performDexOpt(depPackage, instructionSets, false /* useProfiles */, 6939 false /* extractOnly */); 6940 } 6941 } 6942 6943 return pdo.performDexOpt(p, instructionSets, useProfiles, extractOnly); 6944 } 6945 6946 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 6947 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 6948 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 6949 Set<String> collectedNames = new HashSet<>(); 6950 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 6951 6952 retValue.remove(p); 6953 6954 return retValue; 6955 } else { 6956 return Collections.emptyList(); 6957 } 6958 } 6959 6960 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 6961 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 6962 if (!collectedNames.contains(p.packageName)) { 6963 collectedNames.add(p.packageName); 6964 collected.add(p); 6965 6966 if (p.usesLibraries != null) { 6967 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 6968 } 6969 if (p.usesOptionalLibraries != null) { 6970 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 6971 collectedNames); 6972 } 6973 } 6974 } 6975 6976 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 6977 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 6978 for (String libName : libs) { 6979 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 6980 if (libPkg != null) { 6981 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 6982 } 6983 } 6984 } 6985 6986 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 6987 synchronized (mPackages) { 6988 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 6989 if (lib != null && lib.apk != null) { 6990 return mPackages.get(lib.apk); 6991 } 6992 } 6993 return null; 6994 } 6995 6996 public void shutdown() { 6997 mPackageUsage.write(true); 6998 } 6999 7000 @Override 7001 public void forceDexOpt(String packageName) { 7002 enforceSystemOrRoot("forceDexOpt"); 7003 7004 PackageParser.Package pkg; 7005 synchronized (mPackages) { 7006 pkg = mPackages.get(packageName); 7007 if (pkg == null) { 7008 throw new IllegalArgumentException("Unknown package: " + packageName); 7009 } 7010 } 7011 7012 synchronized (mInstallLock) { 7013 final String[] instructionSets = new String[] { 7014 getPrimaryInstructionSet(pkg.applicationInfo) }; 7015 7016 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7017 7018 // Whoever is calling forceDexOpt wants a fully compiled package. 7019 // Don't use profiles since that may cause compilation to be skipped. 7020 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7021 false /* useProfiles */, false /* extractOnly */, true /* force */); 7022 7023 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7024 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7025 throw new IllegalStateException("Failed to dexopt: " + res); 7026 } 7027 } 7028 } 7029 7030 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7031 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7032 Slog.w(TAG, "Unable to update from " + oldPkg.name 7033 + " to " + newPkg.packageName 7034 + ": old package not in system partition"); 7035 return false; 7036 } else if (mPackages.get(oldPkg.name) != null) { 7037 Slog.w(TAG, "Unable to update from " + oldPkg.name 7038 + " to " + newPkg.packageName 7039 + ": old package still exists"); 7040 return false; 7041 } 7042 return true; 7043 } 7044 7045 private boolean removeDataDirsLI(String volumeUuid, String packageName) { 7046 // TODO: triage flags as part of 26466827 7047 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7048 7049 boolean res = true; 7050 final int[] users = sUserManager.getUserIds(); 7051 for (int user : users) { 7052 try { 7053 mInstaller.destroyAppData(volumeUuid, packageName, user, flags); 7054 } catch (InstallerException e) { 7055 Slog.w(TAG, "Failed to delete data directory", e); 7056 res = false; 7057 } 7058 } 7059 return res; 7060 } 7061 7062 void removeCodePathLI(File codePath) { 7063 if (codePath.isDirectory()) { 7064 try { 7065 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7066 } catch (InstallerException e) { 7067 Slog.w(TAG, "Failed to remove code path", e); 7068 } 7069 } else { 7070 codePath.delete(); 7071 } 7072 } 7073 7074 void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) { 7075 try { 7076 mInstaller.destroyAppData(volumeUuid, packageName, userId, flags); 7077 } catch (InstallerException e) { 7078 Slog.w(TAG, "Failed to destroy app data", e); 7079 } 7080 } 7081 7082 void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags, 7083 int appId, String seinfo) { 7084 try { 7085 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo); 7086 } catch (InstallerException e) { 7087 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 7088 } 7089 } 7090 7091 private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 7092 final PackageParser.Package pkg; 7093 synchronized (mPackages) { 7094 pkg = mPackages.get(packageName); 7095 } 7096 if (pkg == null) { 7097 Slog.w(TAG, "Failed to delete code cache directory. No package: " + packageName); 7098 return; 7099 } 7100 deleteCodeCacheDirsLI(pkg); 7101 } 7102 7103 private void deleteCodeCacheDirsLI(PackageParser.Package pkg) { 7104 // TODO: triage flags as part of 26466827 7105 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7106 7107 int[] users = sUserManager.getUserIds(); 7108 int res = 0; 7109 for (int user : users) { 7110 // Remove the parent code cache 7111 try { 7112 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, user, 7113 flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7114 } catch (InstallerException e) { 7115 Slog.w(TAG, "Failed to delete code cache directory", e); 7116 } 7117 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7118 for (int i = 0; i < childCount; i++) { 7119 PackageParser.Package childPkg = pkg.childPackages.get(i); 7120 // Remove the child code cache 7121 try { 7122 mInstaller.clearAppData(childPkg.volumeUuid, childPkg.packageName, 7123 user, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7124 } catch (InstallerException e) { 7125 Slog.w(TAG, "Failed to delete code cache directory", e); 7126 } 7127 } 7128 } 7129 } 7130 7131 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7132 long lastUpdateTime) { 7133 // Set parent install/update time 7134 PackageSetting ps = (PackageSetting) pkg.mExtras; 7135 if (ps != null) { 7136 ps.firstInstallTime = firstInstallTime; 7137 ps.lastUpdateTime = lastUpdateTime; 7138 } 7139 // Set children install/update time 7140 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7141 for (int i = 0; i < childCount; i++) { 7142 PackageParser.Package childPkg = pkg.childPackages.get(i); 7143 ps = (PackageSetting) childPkg.mExtras; 7144 if (ps != null) { 7145 ps.firstInstallTime = firstInstallTime; 7146 ps.lastUpdateTime = lastUpdateTime; 7147 } 7148 } 7149 } 7150 7151 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7152 PackageParser.Package changingLib) { 7153 if (file.path != null) { 7154 usesLibraryFiles.add(file.path); 7155 return; 7156 } 7157 PackageParser.Package p = mPackages.get(file.apk); 7158 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7159 // If we are doing this while in the middle of updating a library apk, 7160 // then we need to make sure to use that new apk for determining the 7161 // dependencies here. (We haven't yet finished committing the new apk 7162 // to the package manager state.) 7163 if (p == null || p.packageName.equals(changingLib.packageName)) { 7164 p = changingLib; 7165 } 7166 } 7167 if (p != null) { 7168 usesLibraryFiles.addAll(p.getAllCodePaths()); 7169 } 7170 } 7171 7172 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7173 PackageParser.Package changingLib) throws PackageManagerException { 7174 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7175 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7176 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7177 for (int i=0; i<N; i++) { 7178 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7179 if (file == null) { 7180 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7181 "Package " + pkg.packageName + " requires unavailable shared library " 7182 + pkg.usesLibraries.get(i) + "; failing!"); 7183 } 7184 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7185 } 7186 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7187 for (int i=0; i<N; i++) { 7188 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7189 if (file == null) { 7190 Slog.w(TAG, "Package " + pkg.packageName 7191 + " desires unavailable shared library " 7192 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7193 } else { 7194 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7195 } 7196 } 7197 N = usesLibraryFiles.size(); 7198 if (N > 0) { 7199 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7200 } else { 7201 pkg.usesLibraryFiles = null; 7202 } 7203 } 7204 } 7205 7206 private static boolean hasString(List<String> list, List<String> which) { 7207 if (list == null) { 7208 return false; 7209 } 7210 for (int i=list.size()-1; i>=0; i--) { 7211 for (int j=which.size()-1; j>=0; j--) { 7212 if (which.get(j).equals(list.get(i))) { 7213 return true; 7214 } 7215 } 7216 } 7217 return false; 7218 } 7219 7220 private void updateAllSharedLibrariesLPw() { 7221 for (PackageParser.Package pkg : mPackages.values()) { 7222 try { 7223 updateSharedLibrariesLPw(pkg, null); 7224 } catch (PackageManagerException e) { 7225 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7226 } 7227 } 7228 } 7229 7230 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7231 PackageParser.Package changingPkg) { 7232 ArrayList<PackageParser.Package> res = null; 7233 for (PackageParser.Package pkg : mPackages.values()) { 7234 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7235 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7236 if (res == null) { 7237 res = new ArrayList<PackageParser.Package>(); 7238 } 7239 res.add(pkg); 7240 try { 7241 updateSharedLibrariesLPw(pkg, changingPkg); 7242 } catch (PackageManagerException e) { 7243 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7244 } 7245 } 7246 } 7247 return res; 7248 } 7249 7250 /** 7251 * Derive the value of the {@code cpuAbiOverride} based on the provided 7252 * value and an optional stored value from the package settings. 7253 */ 7254 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7255 String cpuAbiOverride = null; 7256 7257 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7258 cpuAbiOverride = null; 7259 } else if (abiOverride != null) { 7260 cpuAbiOverride = abiOverride; 7261 } else if (settings != null) { 7262 cpuAbiOverride = settings.cpuAbiOverrideString; 7263 } 7264 7265 return cpuAbiOverride; 7266 } 7267 7268 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 7269 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7270 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7271 // If the package has children and this is the first dive in the function 7272 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7273 // whether all packages (parent and children) would be successfully scanned 7274 // before the actual scan since scanning mutates internal state and we want 7275 // to atomically install the package and its children. 7276 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7277 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7278 scanFlags |= SCAN_CHECK_ONLY; 7279 } 7280 } else { 7281 scanFlags &= ~SCAN_CHECK_ONLY; 7282 } 7283 7284 final PackageParser.Package scannedPkg; 7285 try { 7286 // Scan the parent 7287 scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 7288 // Scan the children 7289 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7290 for (int i = 0; i < childCount; i++) { 7291 PackageParser.Package childPkg = pkg.childPackages.get(i); 7292 scanPackageLI(childPkg, parseFlags, 7293 scanFlags, currentTime, user); 7294 } 7295 } finally { 7296 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7297 } 7298 7299 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7300 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 7301 } 7302 7303 return scannedPkg; 7304 } 7305 7306 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 7307 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7308 boolean success = false; 7309 try { 7310 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 7311 currentTime, user); 7312 success = true; 7313 return res; 7314 } finally { 7315 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7316 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 7317 } 7318 } 7319 } 7320 7321 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 7322 int scanFlags, long currentTime, UserHandle user) 7323 throws PackageManagerException { 7324 final File scanFile = new File(pkg.codePath); 7325 if (pkg.applicationInfo.getCodePath() == null || 7326 pkg.applicationInfo.getResourcePath() == null) { 7327 // Bail out. The resource and code paths haven't been set. 7328 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7329 "Code and resource paths haven't been set correctly"); 7330 } 7331 7332 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7333 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7334 } else { 7335 // Only allow system apps to be flagged as core apps. 7336 pkg.coreApp = false; 7337 } 7338 7339 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7340 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7341 } 7342 7343 if (mCustomResolverComponentName != null && 7344 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7345 setUpCustomResolverActivity(pkg); 7346 } 7347 7348 if (pkg.packageName.equals("android")) { 7349 synchronized (mPackages) { 7350 if (mAndroidApplication != null) { 7351 Slog.w(TAG, "*************************************************"); 7352 Slog.w(TAG, "Core android package being redefined. Skipping."); 7353 Slog.w(TAG, " file=" + scanFile); 7354 Slog.w(TAG, "*************************************************"); 7355 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7356 "Core android package being redefined. Skipping."); 7357 } 7358 7359 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7360 // Set up information for our fall-back user intent resolution activity. 7361 mPlatformPackage = pkg; 7362 pkg.mVersionCode = mSdkVersion; 7363 mAndroidApplication = pkg.applicationInfo; 7364 7365 if (!mResolverReplaced) { 7366 mResolveActivity.applicationInfo = mAndroidApplication; 7367 mResolveActivity.name = ResolverActivity.class.getName(); 7368 mResolveActivity.packageName = mAndroidApplication.packageName; 7369 mResolveActivity.processName = "system:ui"; 7370 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7371 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7372 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7373 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7374 mResolveActivity.exported = true; 7375 mResolveActivity.enabled = true; 7376 mResolveInfo.activityInfo = mResolveActivity; 7377 mResolveInfo.priority = 0; 7378 mResolveInfo.preferredOrder = 0; 7379 mResolveInfo.match = 0; 7380 mResolveComponentName = new ComponentName( 7381 mAndroidApplication.packageName, mResolveActivity.name); 7382 } 7383 } 7384 } 7385 } 7386 7387 if (DEBUG_PACKAGE_SCANNING) { 7388 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7389 Log.d(TAG, "Scanning package " + pkg.packageName); 7390 } 7391 7392 synchronized (mPackages) { 7393 if (mPackages.containsKey(pkg.packageName) 7394 || mSharedLibraries.containsKey(pkg.packageName)) { 7395 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7396 "Application package " + pkg.packageName 7397 + " already installed. Skipping duplicate."); 7398 } 7399 7400 // If we're only installing presumed-existing packages, require that the 7401 // scanned APK is both already known and at the path previously established 7402 // for it. Previously unknown packages we pick up normally, but if we have an 7403 // a priori expectation about this package's install presence, enforce it. 7404 // With a singular exception for new system packages. When an OTA contains 7405 // a new system package, we allow the codepath to change from a system location 7406 // to the user-installed location. If we don't allow this change, any newer, 7407 // user-installed version of the application will be ignored. 7408 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7409 if (mExpectingBetter.containsKey(pkg.packageName)) { 7410 logCriticalInfo(Log.WARN, 7411 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7412 } else { 7413 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7414 if (known != null) { 7415 if (DEBUG_PACKAGE_SCANNING) { 7416 Log.d(TAG, "Examining " + pkg.codePath 7417 + " and requiring known paths " + known.codePathString 7418 + " & " + known.resourcePathString); 7419 } 7420 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7421 || !pkg.applicationInfo.getResourcePath().equals( 7422 known.resourcePathString)) { 7423 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7424 "Application package " + pkg.packageName 7425 + " found at " + pkg.applicationInfo.getCodePath() 7426 + " but expected at " + known.codePathString 7427 + "; ignoring."); 7428 } 7429 } 7430 } 7431 } 7432 } 7433 7434 // Initialize package source and resource directories 7435 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7436 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7437 7438 SharedUserSetting suid = null; 7439 PackageSetting pkgSetting = null; 7440 7441 if (!isSystemApp(pkg)) { 7442 // Only system apps can use these features. 7443 pkg.mOriginalPackages = null; 7444 pkg.mRealPackage = null; 7445 pkg.mAdoptPermissions = null; 7446 } 7447 7448 // Getting the package setting may have a side-effect, so if we 7449 // are only checking if scan would succeed, stash a copy of the 7450 // old setting to restore at the end. 7451 PackageSetting nonMutatedPs = null; 7452 7453 // writer 7454 synchronized (mPackages) { 7455 if (pkg.mSharedUserId != null) { 7456 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7457 if (suid == null) { 7458 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7459 "Creating application package " + pkg.packageName 7460 + " for shared user failed"); 7461 } 7462 if (DEBUG_PACKAGE_SCANNING) { 7463 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7464 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7465 + "): packages=" + suid.packages); 7466 } 7467 } 7468 7469 // Check if we are renaming from an original package name. 7470 PackageSetting origPackage = null; 7471 String realName = null; 7472 if (pkg.mOriginalPackages != null) { 7473 // This package may need to be renamed to a previously 7474 // installed name. Let's check on that... 7475 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7476 if (pkg.mOriginalPackages.contains(renamed)) { 7477 // This package had originally been installed as the 7478 // original name, and we have already taken care of 7479 // transitioning to the new one. Just update the new 7480 // one to continue using the old name. 7481 realName = pkg.mRealPackage; 7482 if (!pkg.packageName.equals(renamed)) { 7483 // Callers into this function may have already taken 7484 // care of renaming the package; only do it here if 7485 // it is not already done. 7486 pkg.setPackageName(renamed); 7487 } 7488 7489 } else { 7490 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7491 if ((origPackage = mSettings.peekPackageLPr( 7492 pkg.mOriginalPackages.get(i))) != null) { 7493 // We do have the package already installed under its 7494 // original name... should we use it? 7495 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7496 // New package is not compatible with original. 7497 origPackage = null; 7498 continue; 7499 } else if (origPackage.sharedUser != null) { 7500 // Make sure uid is compatible between packages. 7501 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7502 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7503 + " to " + pkg.packageName + ": old uid " 7504 + origPackage.sharedUser.name 7505 + " differs from " + pkg.mSharedUserId); 7506 origPackage = null; 7507 continue; 7508 } 7509 } else { 7510 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7511 + pkg.packageName + " to old name " + origPackage.name); 7512 } 7513 break; 7514 } 7515 } 7516 } 7517 } 7518 7519 if (mTransferedPackages.contains(pkg.packageName)) { 7520 Slog.w(TAG, "Package " + pkg.packageName 7521 + " was transferred to another, but its .apk remains"); 7522 } 7523 7524 // See comments in nonMutatedPs declaration 7525 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7526 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 7527 if (foundPs != null) { 7528 nonMutatedPs = new PackageSetting(foundPs); 7529 } 7530 } 7531 7532 // Just create the setting, don't add it yet. For already existing packages 7533 // the PkgSetting exists already and doesn't have to be created. 7534 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7535 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7536 pkg.applicationInfo.primaryCpuAbi, 7537 pkg.applicationInfo.secondaryCpuAbi, 7538 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7539 user, false); 7540 if (pkgSetting == null) { 7541 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7542 "Creating application package " + pkg.packageName + " failed"); 7543 } 7544 7545 if (pkgSetting.origPackage != null) { 7546 // If we are first transitioning from an original package, 7547 // fix up the new package's name now. We need to do this after 7548 // looking up the package under its new name, so getPackageLP 7549 // can take care of fiddling things correctly. 7550 pkg.setPackageName(origPackage.name); 7551 7552 // File a report about this. 7553 String msg = "New package " + pkgSetting.realName 7554 + " renamed to replace old package " + pkgSetting.name; 7555 reportSettingsProblem(Log.WARN, msg); 7556 7557 // Make a note of it. 7558 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7559 mTransferedPackages.add(origPackage.name); 7560 } 7561 7562 // No longer need to retain this. 7563 pkgSetting.origPackage = null; 7564 } 7565 7566 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 7567 // Make a note of it. 7568 mTransferedPackages.add(pkg.packageName); 7569 } 7570 7571 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7572 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7573 } 7574 7575 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7576 // Check all shared libraries and map to their actual file path. 7577 // We only do this here for apps not on a system dir, because those 7578 // are the only ones that can fail an install due to this. We 7579 // will take care of the system apps by updating all of their 7580 // library paths after the scan is done. 7581 updateSharedLibrariesLPw(pkg, null); 7582 } 7583 7584 if (mFoundPolicyFile) { 7585 SELinuxMMAC.assignSeinfoValue(pkg); 7586 } 7587 7588 pkg.applicationInfo.uid = pkgSetting.appId; 7589 pkg.mExtras = pkgSetting; 7590 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7591 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7592 // We just determined the app is signed correctly, so bring 7593 // over the latest parsed certs. 7594 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7595 } else { 7596 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7597 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7598 "Package " + pkg.packageName + " upgrade keys do not match the " 7599 + "previously installed version"); 7600 } else { 7601 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7602 String msg = "System package " + pkg.packageName 7603 + " signature changed; retaining data."; 7604 reportSettingsProblem(Log.WARN, msg); 7605 } 7606 } 7607 } else { 7608 try { 7609 verifySignaturesLP(pkgSetting, pkg); 7610 // We just determined the app is signed correctly, so bring 7611 // over the latest parsed certs. 7612 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7613 } catch (PackageManagerException e) { 7614 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7615 throw e; 7616 } 7617 // The signature has changed, but this package is in the system 7618 // image... let's recover! 7619 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7620 // However... if this package is part of a shared user, but it 7621 // doesn't match the signature of the shared user, let's fail. 7622 // What this means is that you can't change the signatures 7623 // associated with an overall shared user, which doesn't seem all 7624 // that unreasonable. 7625 if (pkgSetting.sharedUser != null) { 7626 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7627 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7628 throw new PackageManagerException( 7629 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7630 "Signature mismatch for shared user: " 7631 + pkgSetting.sharedUser); 7632 } 7633 } 7634 // File a report about this. 7635 String msg = "System package " + pkg.packageName 7636 + " signature changed; retaining data."; 7637 reportSettingsProblem(Log.WARN, msg); 7638 } 7639 } 7640 // Verify that this new package doesn't have any content providers 7641 // that conflict with existing packages. Only do this if the 7642 // package isn't already installed, since we don't want to break 7643 // things that are installed. 7644 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7645 final int N = pkg.providers.size(); 7646 int i; 7647 for (i=0; i<N; i++) { 7648 PackageParser.Provider p = pkg.providers.get(i); 7649 if (p.info.authority != null) { 7650 String names[] = p.info.authority.split(";"); 7651 for (int j = 0; j < names.length; j++) { 7652 if (mProvidersByAuthority.containsKey(names[j])) { 7653 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7654 final String otherPackageName = 7655 ((other != null && other.getComponentName() != null) ? 7656 other.getComponentName().getPackageName() : "?"); 7657 throw new PackageManagerException( 7658 INSTALL_FAILED_CONFLICTING_PROVIDER, 7659 "Can't install because provider name " + names[j] 7660 + " (in package " + pkg.applicationInfo.packageName 7661 + ") is already used by " + otherPackageName); 7662 } 7663 } 7664 } 7665 } 7666 } 7667 7668 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 7669 // This package wants to adopt ownership of permissions from 7670 // another package. 7671 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7672 final String origName = pkg.mAdoptPermissions.get(i); 7673 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7674 if (orig != null) { 7675 if (verifyPackageUpdateLPr(orig, pkg)) { 7676 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7677 + pkg.packageName); 7678 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7679 } 7680 } 7681 } 7682 } 7683 } 7684 7685 final String pkgName = pkg.packageName; 7686 7687 final long scanFileTime = scanFile.lastModified(); 7688 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7689 pkg.applicationInfo.processName = fixProcessName( 7690 pkg.applicationInfo.packageName, 7691 pkg.applicationInfo.processName, 7692 pkg.applicationInfo.uid); 7693 7694 if (pkg != mPlatformPackage) { 7695 // Get all of our default paths setup 7696 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7697 } 7698 7699 final String path = scanFile.getPath(); 7700 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7701 7702 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7703 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7704 7705 // Some system apps still use directory structure for native libraries 7706 // in which case we might end up not detecting abi solely based on apk 7707 // structure. Try to detect abi based on directory structure. 7708 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7709 pkg.applicationInfo.primaryCpuAbi == null) { 7710 setBundledAppAbisAndRoots(pkg, pkgSetting); 7711 setNativeLibraryPaths(pkg); 7712 } 7713 7714 } else { 7715 if ((scanFlags & SCAN_MOVE) != 0) { 7716 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7717 // but we already have this packages package info in the PackageSetting. We just 7718 // use that and derive the native library path based on the new codepath. 7719 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7720 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7721 } 7722 7723 // Set native library paths again. For moves, the path will be updated based on the 7724 // ABIs we've determined above. For non-moves, the path will be updated based on the 7725 // ABIs we determined during compilation, but the path will depend on the final 7726 // package path (after the rename away from the stage path). 7727 setNativeLibraryPaths(pkg); 7728 } 7729 7730 // This is a special case for the "system" package, where the ABI is 7731 // dictated by the zygote configuration (and init.rc). We should keep track 7732 // of this ABI so that we can deal with "normal" applications that run under 7733 // the same UID correctly. 7734 if (mPlatformPackage == pkg) { 7735 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7736 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7737 } 7738 7739 // If there's a mismatch between the abi-override in the package setting 7740 // and the abiOverride specified for the install. Warn about this because we 7741 // would've already compiled the app without taking the package setting into 7742 // account. 7743 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7744 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7745 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7746 " for package " + pkg.packageName); 7747 } 7748 } 7749 7750 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7751 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7752 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7753 7754 // Copy the derived override back to the parsed package, so that we can 7755 // update the package settings accordingly. 7756 pkg.cpuAbiOverride = cpuAbiOverride; 7757 7758 if (DEBUG_ABI_SELECTION) { 7759 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7760 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7761 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7762 } 7763 7764 // Push the derived path down into PackageSettings so we know what to 7765 // clean up at uninstall time. 7766 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7767 7768 if (DEBUG_ABI_SELECTION) { 7769 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7770 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7771 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7772 } 7773 7774 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7775 // We don't do this here during boot because we can do it all 7776 // at once after scanning all existing packages. 7777 // 7778 // We also do this *before* we perform dexopt on this package, so that 7779 // we can avoid redundant dexopts, and also to make sure we've got the 7780 // code and package path correct. 7781 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7782 pkg, true /* boot complete */); 7783 } 7784 7785 if (mFactoryTest && pkg.requestedPermissions.contains( 7786 android.Manifest.permission.FACTORY_TEST)) { 7787 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7788 } 7789 7790 ArrayList<PackageParser.Package> clientLibPkgs = null; 7791 7792 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7793 if (nonMutatedPs != null) { 7794 synchronized (mPackages) { 7795 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 7796 } 7797 } 7798 return pkg; 7799 } 7800 7801 // Only privileged apps and updated privileged apps can add child packages. 7802 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 7803 if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) { 7804 throw new PackageManagerException("Only privileged apps and updated " 7805 + "privileged apps can add child packages. Ignoring package " 7806 + pkg.packageName); 7807 } 7808 final int childCount = pkg.childPackages.size(); 7809 for (int i = 0; i < childCount; i++) { 7810 PackageParser.Package childPkg = pkg.childPackages.get(i); 7811 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 7812 childPkg.packageName)) { 7813 throw new PackageManagerException("Cannot override a child package of " 7814 + "another disabled system app. Ignoring package " + pkg.packageName); 7815 } 7816 } 7817 } 7818 7819 // writer 7820 synchronized (mPackages) { 7821 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7822 // Only system apps can add new shared libraries. 7823 if (pkg.libraryNames != null) { 7824 for (int i=0; i<pkg.libraryNames.size(); i++) { 7825 String name = pkg.libraryNames.get(i); 7826 boolean allowed = false; 7827 if (pkg.isUpdatedSystemApp()) { 7828 // New library entries can only be added through the 7829 // system image. This is important to get rid of a lot 7830 // of nasty edge cases: for example if we allowed a non- 7831 // system update of the app to add a library, then uninstalling 7832 // the update would make the library go away, and assumptions 7833 // we made such as through app install filtering would now 7834 // have allowed apps on the device which aren't compatible 7835 // with it. Better to just have the restriction here, be 7836 // conservative, and create many fewer cases that can negatively 7837 // impact the user experience. 7838 final PackageSetting sysPs = mSettings 7839 .getDisabledSystemPkgLPr(pkg.packageName); 7840 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7841 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7842 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7843 allowed = true; 7844 break; 7845 } 7846 } 7847 } 7848 } else { 7849 allowed = true; 7850 } 7851 if (allowed) { 7852 if (!mSharedLibraries.containsKey(name)) { 7853 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7854 } else if (!name.equals(pkg.packageName)) { 7855 Slog.w(TAG, "Package " + pkg.packageName + " library " 7856 + name + " already exists; skipping"); 7857 } 7858 } else { 7859 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7860 + name + " that is not declared on system image; skipping"); 7861 } 7862 } 7863 if ((scanFlags & SCAN_BOOTING) == 0) { 7864 // If we are not booting, we need to update any applications 7865 // that are clients of our shared library. If we are booting, 7866 // this will all be done once the scan is complete. 7867 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7868 } 7869 } 7870 } 7871 } 7872 7873 // Request the ActivityManager to kill the process(only for existing packages) 7874 // so that we do not end up in a confused state while the user is still using the older 7875 // version of the application while the new one gets installed. 7876 if ((scanFlags & SCAN_REPLACING) != 0) { 7877 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7878 7879 killApplication(pkg.applicationInfo.packageName, 7880 pkg.applicationInfo.uid, "replace pkg"); 7881 7882 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7883 } 7884 7885 // Also need to kill any apps that are dependent on the library. 7886 if (clientLibPkgs != null) { 7887 for (int i=0; i<clientLibPkgs.size(); i++) { 7888 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7889 killApplication(clientPkg.applicationInfo.packageName, 7890 clientPkg.applicationInfo.uid, "update lib"); 7891 } 7892 } 7893 7894 // Make sure we're not adding any bogus keyset info 7895 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7896 ksms.assertScannedPackageValid(pkg); 7897 7898 // writer 7899 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7900 7901 boolean createIdmapFailed = false; 7902 synchronized (mPackages) { 7903 // We don't expect installation to fail beyond this point 7904 7905 // Add the new setting to mSettings 7906 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7907 // Add the new setting to mPackages 7908 mPackages.put(pkg.applicationInfo.packageName, pkg); 7909 // Make sure we don't accidentally delete its data. 7910 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7911 while (iter.hasNext()) { 7912 PackageCleanItem item = iter.next(); 7913 if (pkgName.equals(item.packageName)) { 7914 iter.remove(); 7915 } 7916 } 7917 7918 // Take care of first install / last update times. 7919 if (currentTime != 0) { 7920 if (pkgSetting.firstInstallTime == 0) { 7921 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7922 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7923 pkgSetting.lastUpdateTime = currentTime; 7924 } 7925 } else if (pkgSetting.firstInstallTime == 0) { 7926 // We need *something*. Take time time stamp of the file. 7927 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7928 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7929 if (scanFileTime != pkgSetting.timeStamp) { 7930 // A package on the system image has changed; consider this 7931 // to be an update. 7932 pkgSetting.lastUpdateTime = scanFileTime; 7933 } 7934 } 7935 7936 // Add the package's KeySets to the global KeySetManagerService 7937 ksms.addScannedPackageLPw(pkg); 7938 7939 int N = pkg.providers.size(); 7940 StringBuilder r = null; 7941 int i; 7942 for (i=0; i<N; i++) { 7943 PackageParser.Provider p = pkg.providers.get(i); 7944 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7945 p.info.processName, pkg.applicationInfo.uid); 7946 mProviders.addProvider(p); 7947 p.syncable = p.info.isSyncable; 7948 if (p.info.authority != null) { 7949 String names[] = p.info.authority.split(";"); 7950 p.info.authority = null; 7951 for (int j = 0; j < names.length; j++) { 7952 if (j == 1 && p.syncable) { 7953 // We only want the first authority for a provider to possibly be 7954 // syncable, so if we already added this provider using a different 7955 // authority clear the syncable flag. We copy the provider before 7956 // changing it because the mProviders object contains a reference 7957 // to a provider that we don't want to change. 7958 // Only do this for the second authority since the resulting provider 7959 // object can be the same for all future authorities for this provider. 7960 p = new PackageParser.Provider(p); 7961 p.syncable = false; 7962 } 7963 if (!mProvidersByAuthority.containsKey(names[j])) { 7964 mProvidersByAuthority.put(names[j], p); 7965 if (p.info.authority == null) { 7966 p.info.authority = names[j]; 7967 } else { 7968 p.info.authority = p.info.authority + ";" + names[j]; 7969 } 7970 if (DEBUG_PACKAGE_SCANNING) { 7971 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7972 Log.d(TAG, "Registered content provider: " + names[j] 7973 + ", className = " + p.info.name + ", isSyncable = " 7974 + p.info.isSyncable); 7975 } 7976 } else { 7977 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7978 Slog.w(TAG, "Skipping provider name " + names[j] + 7979 " (in package " + pkg.applicationInfo.packageName + 7980 "): name already used by " 7981 + ((other != null && other.getComponentName() != null) 7982 ? other.getComponentName().getPackageName() : "?")); 7983 } 7984 } 7985 } 7986 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7987 if (r == null) { 7988 r = new StringBuilder(256); 7989 } else { 7990 r.append(' '); 7991 } 7992 r.append(p.info.name); 7993 } 7994 } 7995 if (r != null) { 7996 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7997 } 7998 7999 N = pkg.services.size(); 8000 r = null; 8001 for (i=0; i<N; i++) { 8002 PackageParser.Service s = pkg.services.get(i); 8003 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8004 s.info.processName, pkg.applicationInfo.uid); 8005 mServices.addService(s); 8006 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8007 if (r == null) { 8008 r = new StringBuilder(256); 8009 } else { 8010 r.append(' '); 8011 } 8012 r.append(s.info.name); 8013 } 8014 } 8015 if (r != null) { 8016 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8017 } 8018 8019 N = pkg.receivers.size(); 8020 r = null; 8021 for (i=0; i<N; i++) { 8022 PackageParser.Activity a = pkg.receivers.get(i); 8023 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8024 a.info.processName, pkg.applicationInfo.uid); 8025 mReceivers.addActivity(a, "receiver"); 8026 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8027 if (r == null) { 8028 r = new StringBuilder(256); 8029 } else { 8030 r.append(' '); 8031 } 8032 r.append(a.info.name); 8033 } 8034 } 8035 if (r != null) { 8036 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8037 } 8038 8039 N = pkg.activities.size(); 8040 r = null; 8041 for (i=0; i<N; i++) { 8042 PackageParser.Activity a = pkg.activities.get(i); 8043 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8044 a.info.processName, pkg.applicationInfo.uid); 8045 mActivities.addActivity(a, "activity"); 8046 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8047 if (r == null) { 8048 r = new StringBuilder(256); 8049 } else { 8050 r.append(' '); 8051 } 8052 r.append(a.info.name); 8053 } 8054 } 8055 if (r != null) { 8056 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8057 } 8058 8059 N = pkg.permissionGroups.size(); 8060 r = null; 8061 for (i=0; i<N; i++) { 8062 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8063 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8064 if (cur == null) { 8065 mPermissionGroups.put(pg.info.name, pg); 8066 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8067 if (r == null) { 8068 r = new StringBuilder(256); 8069 } else { 8070 r.append(' '); 8071 } 8072 r.append(pg.info.name); 8073 } 8074 } else { 8075 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8076 + pg.info.packageName + " ignored: original from " 8077 + cur.info.packageName); 8078 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8079 if (r == null) { 8080 r = new StringBuilder(256); 8081 } else { 8082 r.append(' '); 8083 } 8084 r.append("DUP:"); 8085 r.append(pg.info.name); 8086 } 8087 } 8088 } 8089 if (r != null) { 8090 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8091 } 8092 8093 N = pkg.permissions.size(); 8094 r = null; 8095 for (i=0; i<N; i++) { 8096 PackageParser.Permission p = pkg.permissions.get(i); 8097 8098 // Assume by default that we did not install this permission into the system. 8099 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8100 8101 // Now that permission groups have a special meaning, we ignore permission 8102 // groups for legacy apps to prevent unexpected behavior. In particular, 8103 // permissions for one app being granted to someone just becase they happen 8104 // to be in a group defined by another app (before this had no implications). 8105 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8106 p.group = mPermissionGroups.get(p.info.group); 8107 // Warn for a permission in an unknown group. 8108 if (p.info.group != null && p.group == null) { 8109 Slog.w(TAG, "Permission " + p.info.name + " from package " 8110 + p.info.packageName + " in an unknown group " + p.info.group); 8111 } 8112 } 8113 8114 ArrayMap<String, BasePermission> permissionMap = 8115 p.tree ? mSettings.mPermissionTrees 8116 : mSettings.mPermissions; 8117 BasePermission bp = permissionMap.get(p.info.name); 8118 8119 // Allow system apps to redefine non-system permissions 8120 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8121 final boolean currentOwnerIsSystem = (bp.perm != null 8122 && isSystemApp(bp.perm.owner)); 8123 if (isSystemApp(p.owner)) { 8124 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8125 // It's a built-in permission and no owner, take ownership now 8126 bp.packageSetting = pkgSetting; 8127 bp.perm = p; 8128 bp.uid = pkg.applicationInfo.uid; 8129 bp.sourcePackage = p.info.packageName; 8130 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8131 } else if (!currentOwnerIsSystem) { 8132 String msg = "New decl " + p.owner + " of permission " 8133 + p.info.name + " is system; overriding " + bp.sourcePackage; 8134 reportSettingsProblem(Log.WARN, msg); 8135 bp = null; 8136 } 8137 } 8138 } 8139 8140 if (bp == null) { 8141 bp = new BasePermission(p.info.name, p.info.packageName, 8142 BasePermission.TYPE_NORMAL); 8143 permissionMap.put(p.info.name, bp); 8144 } 8145 8146 if (bp.perm == null) { 8147 if (bp.sourcePackage == null 8148 || bp.sourcePackage.equals(p.info.packageName)) { 8149 BasePermission tree = findPermissionTreeLP(p.info.name); 8150 if (tree == null 8151 || tree.sourcePackage.equals(p.info.packageName)) { 8152 bp.packageSetting = pkgSetting; 8153 bp.perm = p; 8154 bp.uid = pkg.applicationInfo.uid; 8155 bp.sourcePackage = p.info.packageName; 8156 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8157 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8158 if (r == null) { 8159 r = new StringBuilder(256); 8160 } else { 8161 r.append(' '); 8162 } 8163 r.append(p.info.name); 8164 } 8165 } else { 8166 Slog.w(TAG, "Permission " + p.info.name + " from package " 8167 + p.info.packageName + " ignored: base tree " 8168 + tree.name + " is from package " 8169 + tree.sourcePackage); 8170 } 8171 } else { 8172 Slog.w(TAG, "Permission " + p.info.name + " from package " 8173 + p.info.packageName + " ignored: original from " 8174 + bp.sourcePackage); 8175 } 8176 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8177 if (r == null) { 8178 r = new StringBuilder(256); 8179 } else { 8180 r.append(' '); 8181 } 8182 r.append("DUP:"); 8183 r.append(p.info.name); 8184 } 8185 if (bp.perm == p) { 8186 bp.protectionLevel = p.info.protectionLevel; 8187 } 8188 } 8189 8190 if (r != null) { 8191 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8192 } 8193 8194 N = pkg.instrumentation.size(); 8195 r = null; 8196 for (i=0; i<N; i++) { 8197 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8198 a.info.packageName = pkg.applicationInfo.packageName; 8199 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8200 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8201 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8202 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8203 a.info.dataDir = pkg.applicationInfo.dataDir; 8204 a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir; 8205 a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir; 8206 8207 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8208 // need other information about the application, like the ABI and what not ? 8209 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8210 mInstrumentation.put(a.getComponentName(), a); 8211 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8212 if (r == null) { 8213 r = new StringBuilder(256); 8214 } else { 8215 r.append(' '); 8216 } 8217 r.append(a.info.name); 8218 } 8219 } 8220 if (r != null) { 8221 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8222 } 8223 8224 if (pkg.protectedBroadcasts != null) { 8225 N = pkg.protectedBroadcasts.size(); 8226 for (i=0; i<N; i++) { 8227 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8228 } 8229 } 8230 8231 pkgSetting.setTimeStamp(scanFileTime); 8232 8233 // Create idmap files for pairs of (packages, overlay packages). 8234 // Note: "android", ie framework-res.apk, is handled by native layers. 8235 if (pkg.mOverlayTarget != null) { 8236 // This is an overlay package. 8237 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8238 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8239 mOverlays.put(pkg.mOverlayTarget, 8240 new ArrayMap<String, PackageParser.Package>()); 8241 } 8242 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8243 map.put(pkg.packageName, pkg); 8244 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8245 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8246 createIdmapFailed = true; 8247 } 8248 } 8249 } else if (mOverlays.containsKey(pkg.packageName) && 8250 !pkg.packageName.equals("android")) { 8251 // This is a regular package, with one or more known overlay packages. 8252 createIdmapsForPackageLI(pkg); 8253 } 8254 } 8255 8256 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8257 8258 if (createIdmapFailed) { 8259 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8260 "scanPackageLI failed to createIdmap"); 8261 } 8262 return pkg; 8263 } 8264 8265 /** 8266 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8267 * is derived purely on the basis of the contents of {@code scanFile} and 8268 * {@code cpuAbiOverride}. 8269 * 8270 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8271 */ 8272 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8273 String cpuAbiOverride, boolean extractLibs) 8274 throws PackageManagerException { 8275 // TODO: We can probably be smarter about this stuff. For installed apps, 8276 // we can calculate this information at install time once and for all. For 8277 // system apps, we can probably assume that this information doesn't change 8278 // after the first boot scan. As things stand, we do lots of unnecessary work. 8279 8280 // Give ourselves some initial paths; we'll come back for another 8281 // pass once we've determined ABI below. 8282 setNativeLibraryPaths(pkg); 8283 8284 // We would never need to extract libs for forward-locked and external packages, 8285 // since the container service will do it for us. We shouldn't attempt to 8286 // extract libs from system app when it was not updated. 8287 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8288 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8289 extractLibs = false; 8290 } 8291 8292 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8293 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8294 8295 NativeLibraryHelper.Handle handle = null; 8296 try { 8297 handle = NativeLibraryHelper.Handle.create(pkg); 8298 // TODO(multiArch): This can be null for apps that didn't go through the 8299 // usual installation process. We can calculate it again, like we 8300 // do during install time. 8301 // 8302 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8303 // unnecessary. 8304 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8305 8306 // Null out the abis so that they can be recalculated. 8307 pkg.applicationInfo.primaryCpuAbi = null; 8308 pkg.applicationInfo.secondaryCpuAbi = null; 8309 if (isMultiArch(pkg.applicationInfo)) { 8310 // Warn if we've set an abiOverride for multi-lib packages.. 8311 // By definition, we need to copy both 32 and 64 bit libraries for 8312 // such packages. 8313 if (pkg.cpuAbiOverride != null 8314 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8315 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8316 } 8317 8318 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8319 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8320 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8321 if (extractLibs) { 8322 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8323 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8324 useIsaSpecificSubdirs); 8325 } else { 8326 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8327 } 8328 } 8329 8330 maybeThrowExceptionForMultiArchCopy( 8331 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8332 8333 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8334 if (extractLibs) { 8335 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8336 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8337 useIsaSpecificSubdirs); 8338 } else { 8339 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8340 } 8341 } 8342 8343 maybeThrowExceptionForMultiArchCopy( 8344 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8345 8346 if (abi64 >= 0) { 8347 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8348 } 8349 8350 if (abi32 >= 0) { 8351 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8352 if (abi64 >= 0) { 8353 if (cpuAbiOverride == null && pkg.use32bitAbi) { 8354 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8355 pkg.applicationInfo.primaryCpuAbi = abi; 8356 } else { 8357 pkg.applicationInfo.secondaryCpuAbi = abi; 8358 } 8359 } else { 8360 pkg.applicationInfo.primaryCpuAbi = abi; 8361 } 8362 } 8363 8364 } else { 8365 String[] abiList = (cpuAbiOverride != null) ? 8366 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8367 8368 // Enable gross and lame hacks for apps that are built with old 8369 // SDK tools. We must scan their APKs for renderscript bitcode and 8370 // not launch them if it's present. Don't bother checking on devices 8371 // that don't have 64 bit support. 8372 boolean needsRenderScriptOverride = false; 8373 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8374 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8375 abiList = Build.SUPPORTED_32_BIT_ABIS; 8376 needsRenderScriptOverride = true; 8377 } 8378 8379 final int copyRet; 8380 if (extractLibs) { 8381 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8382 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8383 } else { 8384 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8385 } 8386 8387 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8388 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8389 "Error unpackaging native libs for app, errorCode=" + copyRet); 8390 } 8391 8392 if (copyRet >= 0) { 8393 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8394 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8395 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8396 } else if (needsRenderScriptOverride) { 8397 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8398 } 8399 } 8400 } catch (IOException ioe) { 8401 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8402 } finally { 8403 IoUtils.closeQuietly(handle); 8404 } 8405 8406 // Now that we've calculated the ABIs and determined if it's an internal app, 8407 // we will go ahead and populate the nativeLibraryPath. 8408 setNativeLibraryPaths(pkg); 8409 } 8410 8411 /** 8412 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8413 * i.e, so that all packages can be run inside a single process if required. 8414 * 8415 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8416 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8417 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8418 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8419 * updating a package that belongs to a shared user. 8420 * 8421 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8422 * adds unnecessary complexity. 8423 */ 8424 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8425 PackageParser.Package scannedPackage, boolean bootComplete) { 8426 String requiredInstructionSet = null; 8427 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8428 requiredInstructionSet = VMRuntime.getInstructionSet( 8429 scannedPackage.applicationInfo.primaryCpuAbi); 8430 } 8431 8432 PackageSetting requirer = null; 8433 for (PackageSetting ps : packagesForUser) { 8434 // If packagesForUser contains scannedPackage, we skip it. This will happen 8435 // when scannedPackage is an update of an existing package. Without this check, 8436 // we will never be able to change the ABI of any package belonging to a shared 8437 // user, even if it's compatible with other packages. 8438 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8439 if (ps.primaryCpuAbiString == null) { 8440 continue; 8441 } 8442 8443 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8444 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8445 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8446 // this but there's not much we can do. 8447 String errorMessage = "Instruction set mismatch, " 8448 + ((requirer == null) ? "[caller]" : requirer) 8449 + " requires " + requiredInstructionSet + " whereas " + ps 8450 + " requires " + instructionSet; 8451 Slog.w(TAG, errorMessage); 8452 } 8453 8454 if (requiredInstructionSet == null) { 8455 requiredInstructionSet = instructionSet; 8456 requirer = ps; 8457 } 8458 } 8459 } 8460 8461 if (requiredInstructionSet != null) { 8462 String adjustedAbi; 8463 if (requirer != null) { 8464 // requirer != null implies that either scannedPackage was null or that scannedPackage 8465 // did not require an ABI, in which case we have to adjust scannedPackage to match 8466 // the ABI of the set (which is the same as requirer's ABI) 8467 adjustedAbi = requirer.primaryCpuAbiString; 8468 if (scannedPackage != null) { 8469 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8470 } 8471 } else { 8472 // requirer == null implies that we're updating all ABIs in the set to 8473 // match scannedPackage. 8474 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8475 } 8476 8477 for (PackageSetting ps : packagesForUser) { 8478 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8479 if (ps.primaryCpuAbiString != null) { 8480 continue; 8481 } 8482 8483 ps.primaryCpuAbiString = adjustedAbi; 8484 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8485 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8486 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8487 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8488 + " (requirer=" 8489 + (requirer == null ? "null" : requirer.pkg.packageName) 8490 + ", scannedPackage=" 8491 + (scannedPackage != null ? scannedPackage.packageName : "null") 8492 + ")"); 8493 try { 8494 mInstaller.rmdex(ps.codePathString, 8495 getDexCodeInstructionSet(getPreferredInstructionSet())); 8496 } catch (InstallerException ignored) { 8497 } 8498 } 8499 } 8500 } 8501 } 8502 } 8503 8504 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8505 synchronized (mPackages) { 8506 mResolverReplaced = true; 8507 // Set up information for custom user intent resolution activity. 8508 mResolveActivity.applicationInfo = pkg.applicationInfo; 8509 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8510 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8511 mResolveActivity.processName = pkg.applicationInfo.packageName; 8512 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8513 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8514 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8515 mResolveActivity.theme = 0; 8516 mResolveActivity.exported = true; 8517 mResolveActivity.enabled = true; 8518 mResolveInfo.activityInfo = mResolveActivity; 8519 mResolveInfo.priority = 0; 8520 mResolveInfo.preferredOrder = 0; 8521 mResolveInfo.match = 0; 8522 mResolveComponentName = mCustomResolverComponentName; 8523 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8524 mResolveComponentName); 8525 } 8526 } 8527 8528 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8529 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8530 8531 // Set up information for ephemeral installer activity 8532 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8533 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8534 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8535 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8536 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8537 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8538 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8539 mEphemeralInstallerActivity.theme = 0; 8540 mEphemeralInstallerActivity.exported = true; 8541 mEphemeralInstallerActivity.enabled = true; 8542 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8543 mEphemeralInstallerInfo.priority = 0; 8544 mEphemeralInstallerInfo.preferredOrder = 0; 8545 mEphemeralInstallerInfo.match = 0; 8546 8547 if (DEBUG_EPHEMERAL) { 8548 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8549 } 8550 } 8551 8552 private static String calculateBundledApkRoot(final String codePathString) { 8553 final File codePath = new File(codePathString); 8554 final File codeRoot; 8555 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8556 codeRoot = Environment.getRootDirectory(); 8557 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8558 codeRoot = Environment.getOemDirectory(); 8559 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8560 codeRoot = Environment.getVendorDirectory(); 8561 } else { 8562 // Unrecognized code path; take its top real segment as the apk root: 8563 // e.g. /something/app/blah.apk => /something 8564 try { 8565 File f = codePath.getCanonicalFile(); 8566 File parent = f.getParentFile(); // non-null because codePath is a file 8567 File tmp; 8568 while ((tmp = parent.getParentFile()) != null) { 8569 f = parent; 8570 parent = tmp; 8571 } 8572 codeRoot = f; 8573 Slog.w(TAG, "Unrecognized code path " 8574 + codePath + " - using " + codeRoot); 8575 } catch (IOException e) { 8576 // Can't canonicalize the code path -- shenanigans? 8577 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8578 return Environment.getRootDirectory().getPath(); 8579 } 8580 } 8581 return codeRoot.getPath(); 8582 } 8583 8584 /** 8585 * Derive and set the location of native libraries for the given package, 8586 * which varies depending on where and how the package was installed. 8587 */ 8588 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8589 final ApplicationInfo info = pkg.applicationInfo; 8590 final String codePath = pkg.codePath; 8591 final File codeFile = new File(codePath); 8592 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8593 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8594 8595 info.nativeLibraryRootDir = null; 8596 info.nativeLibraryRootRequiresIsa = false; 8597 info.nativeLibraryDir = null; 8598 info.secondaryNativeLibraryDir = null; 8599 8600 if (isApkFile(codeFile)) { 8601 // Monolithic install 8602 if (bundledApp) { 8603 // If "/system/lib64/apkname" exists, assume that is the per-package 8604 // native library directory to use; otherwise use "/system/lib/apkname". 8605 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8606 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8607 getPrimaryInstructionSet(info)); 8608 8609 // This is a bundled system app so choose the path based on the ABI. 8610 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8611 // is just the default path. 8612 final String apkName = deriveCodePathName(codePath); 8613 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8614 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8615 apkName).getAbsolutePath(); 8616 8617 if (info.secondaryCpuAbi != null) { 8618 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8619 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8620 secondaryLibDir, apkName).getAbsolutePath(); 8621 } 8622 } else if (asecApp) { 8623 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8624 .getAbsolutePath(); 8625 } else { 8626 final String apkName = deriveCodePathName(codePath); 8627 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8628 .getAbsolutePath(); 8629 } 8630 8631 info.nativeLibraryRootRequiresIsa = false; 8632 info.nativeLibraryDir = info.nativeLibraryRootDir; 8633 } else { 8634 // Cluster install 8635 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8636 info.nativeLibraryRootRequiresIsa = true; 8637 8638 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8639 getPrimaryInstructionSet(info)).getAbsolutePath(); 8640 8641 if (info.secondaryCpuAbi != null) { 8642 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8643 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8644 } 8645 } 8646 } 8647 8648 /** 8649 * Calculate the abis and roots for a bundled app. These can uniquely 8650 * be determined from the contents of the system partition, i.e whether 8651 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8652 * of this information, and instead assume that the system was built 8653 * sensibly. 8654 */ 8655 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8656 PackageSetting pkgSetting) { 8657 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8658 8659 // If "/system/lib64/apkname" exists, assume that is the per-package 8660 // native library directory to use; otherwise use "/system/lib/apkname". 8661 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8662 setBundledAppAbi(pkg, apkRoot, apkName); 8663 // pkgSetting might be null during rescan following uninstall of updates 8664 // to a bundled app, so accommodate that possibility. The settings in 8665 // that case will be established later from the parsed package. 8666 // 8667 // If the settings aren't null, sync them up with what we've just derived. 8668 // note that apkRoot isn't stored in the package settings. 8669 if (pkgSetting != null) { 8670 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8671 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8672 } 8673 } 8674 8675 /** 8676 * Deduces the ABI of a bundled app and sets the relevant fields on the 8677 * parsed pkg object. 8678 * 8679 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8680 * under which system libraries are installed. 8681 * @param apkName the name of the installed package. 8682 */ 8683 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8684 final File codeFile = new File(pkg.codePath); 8685 8686 final boolean has64BitLibs; 8687 final boolean has32BitLibs; 8688 if (isApkFile(codeFile)) { 8689 // Monolithic install 8690 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8691 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8692 } else { 8693 // Cluster install 8694 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8695 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8696 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8697 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8698 has64BitLibs = (new File(rootDir, isa)).exists(); 8699 } else { 8700 has64BitLibs = false; 8701 } 8702 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8703 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8704 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8705 has32BitLibs = (new File(rootDir, isa)).exists(); 8706 } else { 8707 has32BitLibs = false; 8708 } 8709 } 8710 8711 if (has64BitLibs && !has32BitLibs) { 8712 // The package has 64 bit libs, but not 32 bit libs. Its primary 8713 // ABI should be 64 bit. We can safely assume here that the bundled 8714 // native libraries correspond to the most preferred ABI in the list. 8715 8716 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8717 pkg.applicationInfo.secondaryCpuAbi = null; 8718 } else if (has32BitLibs && !has64BitLibs) { 8719 // The package has 32 bit libs but not 64 bit libs. Its primary 8720 // ABI should be 32 bit. 8721 8722 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8723 pkg.applicationInfo.secondaryCpuAbi = null; 8724 } else if (has32BitLibs && has64BitLibs) { 8725 // The application has both 64 and 32 bit bundled libraries. We check 8726 // here that the app declares multiArch support, and warn if it doesn't. 8727 // 8728 // We will be lenient here and record both ABIs. The primary will be the 8729 // ABI that's higher on the list, i.e, a device that's configured to prefer 8730 // 64 bit apps will see a 64 bit primary ABI, 8731 8732 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8733 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 8734 } 8735 8736 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8737 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8738 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8739 } else { 8740 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8741 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8742 } 8743 } else { 8744 pkg.applicationInfo.primaryCpuAbi = null; 8745 pkg.applicationInfo.secondaryCpuAbi = null; 8746 } 8747 } 8748 8749 private void killPackage(PackageParser.Package pkg, String reason) { 8750 // Kill the parent package 8751 killApplication(pkg.packageName, pkg.applicationInfo.uid, reason); 8752 // Kill the child packages 8753 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8754 for (int i = 0; i < childCount; i++) { 8755 PackageParser.Package childPkg = pkg.childPackages.get(i); 8756 killApplication(childPkg.packageName, childPkg.applicationInfo.uid, reason); 8757 } 8758 } 8759 8760 private void killApplication(String pkgName, int appId, String reason) { 8761 // Request the ActivityManager to kill the process(only for existing packages) 8762 // so that we do not end up in a confused state while the user is still using the older 8763 // version of the application while the new one gets installed. 8764 IActivityManager am = ActivityManagerNative.getDefault(); 8765 if (am != null) { 8766 try { 8767 am.killApplicationWithAppId(pkgName, appId, reason); 8768 } catch (RemoteException e) { 8769 } 8770 } 8771 } 8772 8773 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 8774 // Remove the parent package setting 8775 PackageSetting ps = (PackageSetting) pkg.mExtras; 8776 if (ps != null) { 8777 removePackageLI(ps, chatty); 8778 } 8779 // Remove the child package setting 8780 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8781 for (int i = 0; i < childCount; i++) { 8782 PackageParser.Package childPkg = pkg.childPackages.get(i); 8783 ps = (PackageSetting) childPkg.mExtras; 8784 if (ps != null) { 8785 removePackageLI(ps, chatty); 8786 } 8787 } 8788 } 8789 8790 void removePackageLI(PackageSetting ps, boolean chatty) { 8791 if (DEBUG_INSTALL) { 8792 if (chatty) 8793 Log.d(TAG, "Removing package " + ps.name); 8794 } 8795 8796 // writer 8797 synchronized (mPackages) { 8798 mPackages.remove(ps.name); 8799 final PackageParser.Package pkg = ps.pkg; 8800 if (pkg != null) { 8801 cleanPackageDataStructuresLILPw(pkg, chatty); 8802 } 8803 } 8804 } 8805 8806 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8807 if (DEBUG_INSTALL) { 8808 if (chatty) 8809 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8810 } 8811 8812 // writer 8813 synchronized (mPackages) { 8814 // Remove the parent package 8815 mPackages.remove(pkg.applicationInfo.packageName); 8816 cleanPackageDataStructuresLILPw(pkg, chatty); 8817 8818 // Remove the child packages 8819 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8820 for (int i = 0; i < childCount; i++) { 8821 PackageParser.Package childPkg = pkg.childPackages.get(i); 8822 mPackages.remove(childPkg.applicationInfo.packageName); 8823 cleanPackageDataStructuresLILPw(childPkg, chatty); 8824 } 8825 } 8826 } 8827 8828 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8829 int N = pkg.providers.size(); 8830 StringBuilder r = null; 8831 int i; 8832 for (i=0; i<N; i++) { 8833 PackageParser.Provider p = pkg.providers.get(i); 8834 mProviders.removeProvider(p); 8835 if (p.info.authority == null) { 8836 8837 /* There was another ContentProvider with this authority when 8838 * this app was installed so this authority is null, 8839 * Ignore it as we don't have to unregister the provider. 8840 */ 8841 continue; 8842 } 8843 String names[] = p.info.authority.split(";"); 8844 for (int j = 0; j < names.length; j++) { 8845 if (mProvidersByAuthority.get(names[j]) == p) { 8846 mProvidersByAuthority.remove(names[j]); 8847 if (DEBUG_REMOVE) { 8848 if (chatty) 8849 Log.d(TAG, "Unregistered content provider: " + names[j] 8850 + ", className = " + p.info.name + ", isSyncable = " 8851 + p.info.isSyncable); 8852 } 8853 } 8854 } 8855 if (DEBUG_REMOVE && chatty) { 8856 if (r == null) { 8857 r = new StringBuilder(256); 8858 } else { 8859 r.append(' '); 8860 } 8861 r.append(p.info.name); 8862 } 8863 } 8864 if (r != null) { 8865 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8866 } 8867 8868 N = pkg.services.size(); 8869 r = null; 8870 for (i=0; i<N; i++) { 8871 PackageParser.Service s = pkg.services.get(i); 8872 mServices.removeService(s); 8873 if (chatty) { 8874 if (r == null) { 8875 r = new StringBuilder(256); 8876 } else { 8877 r.append(' '); 8878 } 8879 r.append(s.info.name); 8880 } 8881 } 8882 if (r != null) { 8883 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8884 } 8885 8886 N = pkg.receivers.size(); 8887 r = null; 8888 for (i=0; i<N; i++) { 8889 PackageParser.Activity a = pkg.receivers.get(i); 8890 mReceivers.removeActivity(a, "receiver"); 8891 if (DEBUG_REMOVE && chatty) { 8892 if (r == null) { 8893 r = new StringBuilder(256); 8894 } else { 8895 r.append(' '); 8896 } 8897 r.append(a.info.name); 8898 } 8899 } 8900 if (r != null) { 8901 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8902 } 8903 8904 N = pkg.activities.size(); 8905 r = null; 8906 for (i=0; i<N; i++) { 8907 PackageParser.Activity a = pkg.activities.get(i); 8908 mActivities.removeActivity(a, "activity"); 8909 if (DEBUG_REMOVE && chatty) { 8910 if (r == null) { 8911 r = new StringBuilder(256); 8912 } else { 8913 r.append(' '); 8914 } 8915 r.append(a.info.name); 8916 } 8917 } 8918 if (r != null) { 8919 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8920 } 8921 8922 N = pkg.permissions.size(); 8923 r = null; 8924 for (i=0; i<N; i++) { 8925 PackageParser.Permission p = pkg.permissions.get(i); 8926 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8927 if (bp == null) { 8928 bp = mSettings.mPermissionTrees.get(p.info.name); 8929 } 8930 if (bp != null && bp.perm == p) { 8931 bp.perm = null; 8932 if (DEBUG_REMOVE && chatty) { 8933 if (r == null) { 8934 r = new StringBuilder(256); 8935 } else { 8936 r.append(' '); 8937 } 8938 r.append(p.info.name); 8939 } 8940 } 8941 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8942 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 8943 if (appOpPkgs != null) { 8944 appOpPkgs.remove(pkg.packageName); 8945 } 8946 } 8947 } 8948 if (r != null) { 8949 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8950 } 8951 8952 N = pkg.requestedPermissions.size(); 8953 r = null; 8954 for (i=0; i<N; i++) { 8955 String perm = pkg.requestedPermissions.get(i); 8956 BasePermission bp = mSettings.mPermissions.get(perm); 8957 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8958 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 8959 if (appOpPkgs != null) { 8960 appOpPkgs.remove(pkg.packageName); 8961 if (appOpPkgs.isEmpty()) { 8962 mAppOpPermissionPackages.remove(perm); 8963 } 8964 } 8965 } 8966 } 8967 if (r != null) { 8968 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8969 } 8970 8971 N = pkg.instrumentation.size(); 8972 r = null; 8973 for (i=0; i<N; i++) { 8974 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8975 mInstrumentation.remove(a.getComponentName()); 8976 if (DEBUG_REMOVE && chatty) { 8977 if (r == null) { 8978 r = new StringBuilder(256); 8979 } else { 8980 r.append(' '); 8981 } 8982 r.append(a.info.name); 8983 } 8984 } 8985 if (r != null) { 8986 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8987 } 8988 8989 r = null; 8990 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8991 // Only system apps can hold shared libraries. 8992 if (pkg.libraryNames != null) { 8993 for (i=0; i<pkg.libraryNames.size(); i++) { 8994 String name = pkg.libraryNames.get(i); 8995 SharedLibraryEntry cur = mSharedLibraries.get(name); 8996 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8997 mSharedLibraries.remove(name); 8998 if (DEBUG_REMOVE && chatty) { 8999 if (r == null) { 9000 r = new StringBuilder(256); 9001 } else { 9002 r.append(' '); 9003 } 9004 r.append(name); 9005 } 9006 } 9007 } 9008 } 9009 } 9010 if (r != null) { 9011 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9012 } 9013 } 9014 9015 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9016 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9017 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9018 return true; 9019 } 9020 } 9021 return false; 9022 } 9023 9024 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9025 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9026 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9027 9028 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9029 // Update the parent permissions 9030 updatePermissionsLPw(pkg.packageName, pkg, flags); 9031 // Update the child permissions 9032 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9033 for (int i = 0; i < childCount; i++) { 9034 PackageParser.Package childPkg = pkg.childPackages.get(i); 9035 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9036 } 9037 } 9038 9039 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9040 int flags) { 9041 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9042 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9043 } 9044 9045 private void updatePermissionsLPw(String changingPkg, 9046 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9047 // Make sure there are no dangling permission trees. 9048 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9049 while (it.hasNext()) { 9050 final BasePermission bp = it.next(); 9051 if (bp.packageSetting == null) { 9052 // We may not yet have parsed the package, so just see if 9053 // we still know about its settings. 9054 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9055 } 9056 if (bp.packageSetting == null) { 9057 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9058 + " from package " + bp.sourcePackage); 9059 it.remove(); 9060 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9061 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9062 Slog.i(TAG, "Removing old permission tree: " + bp.name 9063 + " from package " + bp.sourcePackage); 9064 flags |= UPDATE_PERMISSIONS_ALL; 9065 it.remove(); 9066 } 9067 } 9068 } 9069 9070 // Make sure all dynamic permissions have been assigned to a package, 9071 // and make sure there are no dangling permissions. 9072 it = mSettings.mPermissions.values().iterator(); 9073 while (it.hasNext()) { 9074 final BasePermission bp = it.next(); 9075 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9076 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9077 + bp.name + " pkg=" + bp.sourcePackage 9078 + " info=" + bp.pendingInfo); 9079 if (bp.packageSetting == null && bp.pendingInfo != null) { 9080 final BasePermission tree = findPermissionTreeLP(bp.name); 9081 if (tree != null && tree.perm != null) { 9082 bp.packageSetting = tree.packageSetting; 9083 bp.perm = new PackageParser.Permission(tree.perm.owner, 9084 new PermissionInfo(bp.pendingInfo)); 9085 bp.perm.info.packageName = tree.perm.info.packageName; 9086 bp.perm.info.name = bp.name; 9087 bp.uid = tree.uid; 9088 } 9089 } 9090 } 9091 if (bp.packageSetting == null) { 9092 // We may not yet have parsed the package, so just see if 9093 // we still know about its settings. 9094 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9095 } 9096 if (bp.packageSetting == null) { 9097 Slog.w(TAG, "Removing dangling permission: " + bp.name 9098 + " from package " + bp.sourcePackage); 9099 it.remove(); 9100 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9101 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9102 Slog.i(TAG, "Removing old permission: " + bp.name 9103 + " from package " + bp.sourcePackage); 9104 flags |= UPDATE_PERMISSIONS_ALL; 9105 it.remove(); 9106 } 9107 } 9108 } 9109 9110 // Now update the permissions for all packages, in particular 9111 // replace the granted permissions of the system packages. 9112 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9113 for (PackageParser.Package pkg : mPackages.values()) { 9114 if (pkg != pkgInfo) { 9115 // Only replace for packages on requested volume 9116 final String volumeUuid = getVolumeUuidForPackage(pkg); 9117 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9118 && Objects.equals(replaceVolumeUuid, volumeUuid); 9119 grantPermissionsLPw(pkg, replace, changingPkg); 9120 } 9121 } 9122 } 9123 9124 if (pkgInfo != null) { 9125 // Only replace for packages on requested volume 9126 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9127 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9128 && Objects.equals(replaceVolumeUuid, volumeUuid); 9129 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9130 } 9131 } 9132 9133 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9134 String packageOfInterest) { 9135 // IMPORTANT: There are two types of permissions: install and runtime. 9136 // Install time permissions are granted when the app is installed to 9137 // all device users and users added in the future. Runtime permissions 9138 // are granted at runtime explicitly to specific users. Normal and signature 9139 // protected permissions are install time permissions. Dangerous permissions 9140 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9141 // otherwise they are runtime permissions. This function does not manage 9142 // runtime permissions except for the case an app targeting Lollipop MR1 9143 // being upgraded to target a newer SDK, in which case dangerous permissions 9144 // are transformed from install time to runtime ones. 9145 9146 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9147 if (ps == null) { 9148 return; 9149 } 9150 9151 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9152 9153 PermissionsState permissionsState = ps.getPermissionsState(); 9154 PermissionsState origPermissions = permissionsState; 9155 9156 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9157 9158 boolean runtimePermissionsRevoked = false; 9159 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9160 9161 boolean changedInstallPermission = false; 9162 9163 if (replace) { 9164 ps.installPermissionsFixed = false; 9165 if (!ps.isSharedUser()) { 9166 origPermissions = new PermissionsState(permissionsState); 9167 permissionsState.reset(); 9168 } else { 9169 // We need to know only about runtime permission changes since the 9170 // calling code always writes the install permissions state but 9171 // the runtime ones are written only if changed. The only cases of 9172 // changed runtime permissions here are promotion of an install to 9173 // runtime and revocation of a runtime from a shared user. 9174 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9175 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9176 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9177 runtimePermissionsRevoked = true; 9178 } 9179 } 9180 } 9181 9182 permissionsState.setGlobalGids(mGlobalGids); 9183 9184 final int N = pkg.requestedPermissions.size(); 9185 for (int i=0; i<N; i++) { 9186 final String name = pkg.requestedPermissions.get(i); 9187 final BasePermission bp = mSettings.mPermissions.get(name); 9188 9189 if (DEBUG_INSTALL) { 9190 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9191 } 9192 9193 if (bp == null || bp.packageSetting == null) { 9194 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9195 Slog.w(TAG, "Unknown permission " + name 9196 + " in package " + pkg.packageName); 9197 } 9198 continue; 9199 } 9200 9201 final String perm = bp.name; 9202 boolean allowedSig = false; 9203 int grant = GRANT_DENIED; 9204 9205 // Keep track of app op permissions. 9206 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9207 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9208 if (pkgs == null) { 9209 pkgs = new ArraySet<>(); 9210 mAppOpPermissionPackages.put(bp.name, pkgs); 9211 } 9212 pkgs.add(pkg.packageName); 9213 } 9214 9215 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9216 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9217 >= Build.VERSION_CODES.M; 9218 switch (level) { 9219 case PermissionInfo.PROTECTION_NORMAL: { 9220 // For all apps normal permissions are install time ones. 9221 grant = GRANT_INSTALL; 9222 } break; 9223 9224 case PermissionInfo.PROTECTION_DANGEROUS: { 9225 // If a permission review is required for legacy apps we represent 9226 // their permissions as always granted runtime ones since we need 9227 // to keep the review required permission flag per user while an 9228 // install permission's state is shared across all users. 9229 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9230 // For legacy apps dangerous permissions are install time ones. 9231 grant = GRANT_INSTALL; 9232 } else if (origPermissions.hasInstallPermission(bp.name)) { 9233 // For legacy apps that became modern, install becomes runtime. 9234 grant = GRANT_UPGRADE; 9235 } else if (mPromoteSystemApps 9236 && isSystemApp(ps) 9237 && mExistingSystemPackages.contains(ps.name)) { 9238 // For legacy system apps, install becomes runtime. 9239 // We cannot check hasInstallPermission() for system apps since those 9240 // permissions were granted implicitly and not persisted pre-M. 9241 grant = GRANT_UPGRADE; 9242 } else { 9243 // For modern apps keep runtime permissions unchanged. 9244 grant = GRANT_RUNTIME; 9245 } 9246 } break; 9247 9248 case PermissionInfo.PROTECTION_SIGNATURE: { 9249 // For all apps signature permissions are install time ones. 9250 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9251 if (allowedSig) { 9252 grant = GRANT_INSTALL; 9253 } 9254 } break; 9255 } 9256 9257 if (DEBUG_INSTALL) { 9258 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9259 } 9260 9261 if (grant != GRANT_DENIED) { 9262 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9263 // If this is an existing, non-system package, then 9264 // we can't add any new permissions to it. 9265 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9266 // Except... if this is a permission that was added 9267 // to the platform (note: need to only do this when 9268 // updating the platform). 9269 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9270 grant = GRANT_DENIED; 9271 } 9272 } 9273 } 9274 9275 switch (grant) { 9276 case GRANT_INSTALL: { 9277 // Revoke this as runtime permission to handle the case of 9278 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 9279 for (int userId : UserManagerService.getInstance().getUserIds()) { 9280 if (origPermissions.getRuntimePermissionState( 9281 bp.name, userId) != null) { 9282 // Revoke the runtime permission and clear the flags. 9283 origPermissions.revokeRuntimePermission(bp, userId); 9284 origPermissions.updatePermissionFlags(bp, userId, 9285 PackageManager.MASK_PERMISSION_FLAGS, 0); 9286 // If we revoked a permission permission, we have to write. 9287 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9288 changedRuntimePermissionUserIds, userId); 9289 } 9290 } 9291 // Grant an install permission. 9292 if (permissionsState.grantInstallPermission(bp) != 9293 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9294 changedInstallPermission = true; 9295 } 9296 } break; 9297 9298 case GRANT_RUNTIME: { 9299 // Grant previously granted runtime permissions. 9300 for (int userId : UserManagerService.getInstance().getUserIds()) { 9301 PermissionState permissionState = origPermissions 9302 .getRuntimePermissionState(bp.name, userId); 9303 int flags = permissionState != null 9304 ? permissionState.getFlags() : 0; 9305 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9306 if (permissionsState.grantRuntimePermission(bp, userId) == 9307 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9308 // If we cannot put the permission as it was, we have to write. 9309 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9310 changedRuntimePermissionUserIds, userId); 9311 } 9312 // If the app supports runtime permissions no need for a review. 9313 if (Build.PERMISSIONS_REVIEW_REQUIRED 9314 && appSupportsRuntimePermissions 9315 && (flags & PackageManager 9316 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9317 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9318 // Since we changed the flags, we have to write. 9319 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9320 changedRuntimePermissionUserIds, userId); 9321 } 9322 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9323 && !appSupportsRuntimePermissions) { 9324 // For legacy apps that need a permission review, every new 9325 // runtime permission is granted but it is pending a review. 9326 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9327 permissionsState.grantRuntimePermission(bp, userId); 9328 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9329 // We changed the permission and flags, hence have to write. 9330 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9331 changedRuntimePermissionUserIds, userId); 9332 } 9333 } 9334 // Propagate the permission flags. 9335 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9336 } 9337 } break; 9338 9339 case GRANT_UPGRADE: { 9340 // Grant runtime permissions for a previously held install permission. 9341 PermissionState permissionState = origPermissions 9342 .getInstallPermissionState(bp.name); 9343 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9344 9345 if (origPermissions.revokeInstallPermission(bp) 9346 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9347 // We will be transferring the permission flags, so clear them. 9348 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9349 PackageManager.MASK_PERMISSION_FLAGS, 0); 9350 changedInstallPermission = true; 9351 } 9352 9353 // If the permission is not to be promoted to runtime we ignore it and 9354 // also its other flags as they are not applicable to install permissions. 9355 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9356 for (int userId : currentUserIds) { 9357 if (permissionsState.grantRuntimePermission(bp, userId) != 9358 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9359 // Transfer the permission flags. 9360 permissionsState.updatePermissionFlags(bp, userId, 9361 flags, flags); 9362 // If we granted the permission, we have to write. 9363 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9364 changedRuntimePermissionUserIds, userId); 9365 } 9366 } 9367 } 9368 } break; 9369 9370 default: { 9371 if (packageOfInterest == null 9372 || packageOfInterest.equals(pkg.packageName)) { 9373 Slog.w(TAG, "Not granting permission " + perm 9374 + " to package " + pkg.packageName 9375 + " because it was previously installed without"); 9376 } 9377 } break; 9378 } 9379 } else { 9380 if (permissionsState.revokeInstallPermission(bp) != 9381 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9382 // Also drop the permission flags. 9383 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9384 PackageManager.MASK_PERMISSION_FLAGS, 0); 9385 changedInstallPermission = true; 9386 Slog.i(TAG, "Un-granting permission " + perm 9387 + " from package " + pkg.packageName 9388 + " (protectionLevel=" + bp.protectionLevel 9389 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9390 + ")"); 9391 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9392 // Don't print warning for app op permissions, since it is fine for them 9393 // not to be granted, there is a UI for the user to decide. 9394 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9395 Slog.w(TAG, "Not granting permission " + perm 9396 + " to package " + pkg.packageName 9397 + " (protectionLevel=" + bp.protectionLevel 9398 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9399 + ")"); 9400 } 9401 } 9402 } 9403 } 9404 9405 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9406 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9407 // This is the first that we have heard about this package, so the 9408 // permissions we have now selected are fixed until explicitly 9409 // changed. 9410 ps.installPermissionsFixed = true; 9411 } 9412 9413 // Persist the runtime permissions state for users with changes. If permissions 9414 // were revoked because no app in the shared user declares them we have to 9415 // write synchronously to avoid losing runtime permissions state. 9416 for (int userId : changedRuntimePermissionUserIds) { 9417 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9418 } 9419 9420 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9421 } 9422 9423 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9424 boolean allowed = false; 9425 final int NP = PackageParser.NEW_PERMISSIONS.length; 9426 for (int ip=0; ip<NP; ip++) { 9427 final PackageParser.NewPermissionInfo npi 9428 = PackageParser.NEW_PERMISSIONS[ip]; 9429 if (npi.name.equals(perm) 9430 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9431 allowed = true; 9432 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9433 + pkg.packageName); 9434 break; 9435 } 9436 } 9437 return allowed; 9438 } 9439 9440 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9441 BasePermission bp, PermissionsState origPermissions) { 9442 boolean allowed; 9443 allowed = (compareSignatures( 9444 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9445 == PackageManager.SIGNATURE_MATCH) 9446 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9447 == PackageManager.SIGNATURE_MATCH); 9448 if (!allowed && (bp.protectionLevel 9449 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9450 if (isSystemApp(pkg)) { 9451 // For updated system applications, a system permission 9452 // is granted only if it had been defined by the original application. 9453 if (pkg.isUpdatedSystemApp()) { 9454 final PackageSetting sysPs = mSettings 9455 .getDisabledSystemPkgLPr(pkg.packageName); 9456 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9457 // If the original was granted this permission, we take 9458 // that grant decision as read and propagate it to the 9459 // update. 9460 if (sysPs.isPrivileged()) { 9461 allowed = true; 9462 } 9463 } else { 9464 // The system apk may have been updated with an older 9465 // version of the one on the data partition, but which 9466 // granted a new system permission that it didn't have 9467 // before. In this case we do want to allow the app to 9468 // now get the new permission if the ancestral apk is 9469 // privileged to get it. 9470 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9471 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9472 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9473 allowed = true; 9474 break; 9475 } 9476 } 9477 } 9478 // Also if a privileged parent package on the system image or any of 9479 // its children requested a privileged permission, the updated child 9480 // packages can also get the permission. 9481 if (pkg.parentPackage != null) { 9482 final PackageSetting disabledSysParentPs = mSettings 9483 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 9484 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 9485 && disabledSysParentPs.isPrivileged()) { 9486 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 9487 allowed = true; 9488 } else if (disabledSysParentPs.pkg.childPackages != null) { 9489 final int count = disabledSysParentPs.pkg.childPackages.size(); 9490 for (int i = 0; i < count; i++) { 9491 PackageParser.Package disabledSysChildPkg = 9492 disabledSysParentPs.pkg.childPackages.get(i); 9493 if (isPackageRequestingPermission(disabledSysChildPkg, 9494 perm)) { 9495 allowed = true; 9496 break; 9497 } 9498 } 9499 } 9500 } 9501 } 9502 } 9503 } else { 9504 allowed = isPrivilegedApp(pkg); 9505 } 9506 } 9507 } 9508 if (!allowed) { 9509 if (!allowed && (bp.protectionLevel 9510 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9511 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9512 // If this was a previously normal/dangerous permission that got moved 9513 // to a system permission as part of the runtime permission redesign, then 9514 // we still want to blindly grant it to old apps. 9515 allowed = true; 9516 } 9517 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9518 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9519 // If this permission is to be granted to the system installer and 9520 // this app is an installer, then it gets the permission. 9521 allowed = true; 9522 } 9523 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9524 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9525 // If this permission is to be granted to the system verifier and 9526 // this app is a verifier, then it gets the permission. 9527 allowed = true; 9528 } 9529 if (!allowed && (bp.protectionLevel 9530 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9531 && isSystemApp(pkg)) { 9532 // Any pre-installed system app is allowed to get this permission. 9533 allowed = true; 9534 } 9535 if (!allowed && (bp.protectionLevel 9536 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9537 // For development permissions, a development permission 9538 // is granted only if it was already granted. 9539 allowed = origPermissions.hasInstallPermission(perm); 9540 } 9541 } 9542 return allowed; 9543 } 9544 9545 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 9546 final int permCount = pkg.requestedPermissions.size(); 9547 for (int j = 0; j < permCount; j++) { 9548 String requestedPermission = pkg.requestedPermissions.get(j); 9549 if (permission.equals(requestedPermission)) { 9550 return true; 9551 } 9552 } 9553 return false; 9554 } 9555 9556 final class ActivityIntentResolver 9557 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9558 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9559 boolean defaultOnly, int userId) { 9560 if (!sUserManager.exists(userId)) return null; 9561 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9562 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9563 } 9564 9565 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9566 int userId) { 9567 if (!sUserManager.exists(userId)) return null; 9568 mFlags = flags; 9569 return super.queryIntent(intent, resolvedType, 9570 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9571 } 9572 9573 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9574 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9575 if (!sUserManager.exists(userId)) return null; 9576 if (packageActivities == null) { 9577 return null; 9578 } 9579 mFlags = flags; 9580 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9581 final int N = packageActivities.size(); 9582 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9583 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9584 9585 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9586 for (int i = 0; i < N; ++i) { 9587 intentFilters = packageActivities.get(i).intents; 9588 if (intentFilters != null && intentFilters.size() > 0) { 9589 PackageParser.ActivityIntentInfo[] array = 9590 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9591 intentFilters.toArray(array); 9592 listCut.add(array); 9593 } 9594 } 9595 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9596 } 9597 9598 public final void addActivity(PackageParser.Activity a, String type) { 9599 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 9600 mActivities.put(a.getComponentName(), a); 9601 if (DEBUG_SHOW_INFO) 9602 Log.v( 9603 TAG, " " + type + " " + 9604 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 9605 if (DEBUG_SHOW_INFO) 9606 Log.v(TAG, " Class=" + a.info.name); 9607 final int NI = a.intents.size(); 9608 for (int j=0; j<NI; j++) { 9609 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9610 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 9611 intent.setPriority(0); 9612 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 9613 + a.className + " with priority > 0, forcing to 0"); 9614 } 9615 if (DEBUG_SHOW_INFO) { 9616 Log.v(TAG, " IntentFilter:"); 9617 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9618 } 9619 if (!intent.debugCheck()) { 9620 Log.w(TAG, "==> For Activity " + a.info.name); 9621 } 9622 addFilter(intent); 9623 } 9624 } 9625 9626 public final void removeActivity(PackageParser.Activity a, String type) { 9627 mActivities.remove(a.getComponentName()); 9628 if (DEBUG_SHOW_INFO) { 9629 Log.v(TAG, " " + type + " " 9630 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 9631 : a.info.name) + ":"); 9632 Log.v(TAG, " Class=" + a.info.name); 9633 } 9634 final int NI = a.intents.size(); 9635 for (int j=0; j<NI; j++) { 9636 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9637 if (DEBUG_SHOW_INFO) { 9638 Log.v(TAG, " IntentFilter:"); 9639 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9640 } 9641 removeFilter(intent); 9642 } 9643 } 9644 9645 @Override 9646 protected boolean allowFilterResult( 9647 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 9648 ActivityInfo filterAi = filter.activity.info; 9649 for (int i=dest.size()-1; i>=0; i--) { 9650 ActivityInfo destAi = dest.get(i).activityInfo; 9651 if (destAi.name == filterAi.name 9652 && destAi.packageName == filterAi.packageName) { 9653 return false; 9654 } 9655 } 9656 return true; 9657 } 9658 9659 @Override 9660 protected ActivityIntentInfo[] newArray(int size) { 9661 return new ActivityIntentInfo[size]; 9662 } 9663 9664 @Override 9665 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 9666 if (!sUserManager.exists(userId)) return true; 9667 PackageParser.Package p = filter.activity.owner; 9668 if (p != null) { 9669 PackageSetting ps = (PackageSetting)p.mExtras; 9670 if (ps != null) { 9671 // System apps are never considered stopped for purposes of 9672 // filtering, because there may be no way for the user to 9673 // actually re-launch them. 9674 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 9675 && ps.getStopped(userId); 9676 } 9677 } 9678 return false; 9679 } 9680 9681 @Override 9682 protected boolean isPackageForFilter(String packageName, 9683 PackageParser.ActivityIntentInfo info) { 9684 return packageName.equals(info.activity.owner.packageName); 9685 } 9686 9687 @Override 9688 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 9689 int match, int userId) { 9690 if (!sUserManager.exists(userId)) return null; 9691 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 9692 return null; 9693 } 9694 final PackageParser.Activity activity = info.activity; 9695 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 9696 if (ps == null) { 9697 return null; 9698 } 9699 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 9700 ps.readUserState(userId), userId); 9701 if (ai == null) { 9702 return null; 9703 } 9704 final ResolveInfo res = new ResolveInfo(); 9705 res.activityInfo = ai; 9706 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9707 res.filter = info; 9708 } 9709 if (info != null) { 9710 res.handleAllWebDataURI = info.handleAllWebDataURI(); 9711 } 9712 res.priority = info.getPriority(); 9713 res.preferredOrder = activity.owner.mPreferredOrder; 9714 //System.out.println("Result: " + res.activityInfo.className + 9715 // " = " + res.priority); 9716 res.match = match; 9717 res.isDefault = info.hasDefault; 9718 res.labelRes = info.labelRes; 9719 res.nonLocalizedLabel = info.nonLocalizedLabel; 9720 if (userNeedsBadging(userId)) { 9721 res.noResourceId = true; 9722 } else { 9723 res.icon = info.icon; 9724 } 9725 res.iconResourceId = info.icon; 9726 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9727 return res; 9728 } 9729 9730 @Override 9731 protected void sortResults(List<ResolveInfo> results) { 9732 Collections.sort(results, mResolvePrioritySorter); 9733 } 9734 9735 @Override 9736 protected void dumpFilter(PrintWriter out, String prefix, 9737 PackageParser.ActivityIntentInfo filter) { 9738 out.print(prefix); out.print( 9739 Integer.toHexString(System.identityHashCode(filter.activity))); 9740 out.print(' '); 9741 filter.activity.printComponentShortName(out); 9742 out.print(" filter "); 9743 out.println(Integer.toHexString(System.identityHashCode(filter))); 9744 } 9745 9746 @Override 9747 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9748 return filter.activity; 9749 } 9750 9751 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9752 PackageParser.Activity activity = (PackageParser.Activity)label; 9753 out.print(prefix); out.print( 9754 Integer.toHexString(System.identityHashCode(activity))); 9755 out.print(' '); 9756 activity.printComponentShortName(out); 9757 if (count > 1) { 9758 out.print(" ("); out.print(count); out.print(" filters)"); 9759 } 9760 out.println(); 9761 } 9762 9763// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9764// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9765// final List<ResolveInfo> retList = Lists.newArrayList(); 9766// while (i.hasNext()) { 9767// final ResolveInfo resolveInfo = i.next(); 9768// if (isEnabledLP(resolveInfo.activityInfo)) { 9769// retList.add(resolveInfo); 9770// } 9771// } 9772// return retList; 9773// } 9774 9775 // Keys are String (activity class name), values are Activity. 9776 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9777 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9778 private int mFlags; 9779 } 9780 9781 private final class ServiceIntentResolver 9782 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9783 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9784 boolean defaultOnly, int userId) { 9785 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9786 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9787 } 9788 9789 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9790 int userId) { 9791 if (!sUserManager.exists(userId)) return null; 9792 mFlags = flags; 9793 return super.queryIntent(intent, resolvedType, 9794 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9795 } 9796 9797 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9798 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9799 if (!sUserManager.exists(userId)) return null; 9800 if (packageServices == null) { 9801 return null; 9802 } 9803 mFlags = flags; 9804 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9805 final int N = packageServices.size(); 9806 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9807 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9808 9809 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9810 for (int i = 0; i < N; ++i) { 9811 intentFilters = packageServices.get(i).intents; 9812 if (intentFilters != null && intentFilters.size() > 0) { 9813 PackageParser.ServiceIntentInfo[] array = 9814 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9815 intentFilters.toArray(array); 9816 listCut.add(array); 9817 } 9818 } 9819 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9820 } 9821 9822 public final void addService(PackageParser.Service s) { 9823 mServices.put(s.getComponentName(), s); 9824 if (DEBUG_SHOW_INFO) { 9825 Log.v(TAG, " " 9826 + (s.info.nonLocalizedLabel != null 9827 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9828 Log.v(TAG, " Class=" + s.info.name); 9829 } 9830 final int NI = s.intents.size(); 9831 int j; 9832 for (j=0; j<NI; j++) { 9833 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9834 if (DEBUG_SHOW_INFO) { 9835 Log.v(TAG, " IntentFilter:"); 9836 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9837 } 9838 if (!intent.debugCheck()) { 9839 Log.w(TAG, "==> For Service " + s.info.name); 9840 } 9841 addFilter(intent); 9842 } 9843 } 9844 9845 public final void removeService(PackageParser.Service s) { 9846 mServices.remove(s.getComponentName()); 9847 if (DEBUG_SHOW_INFO) { 9848 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9849 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9850 Log.v(TAG, " Class=" + s.info.name); 9851 } 9852 final int NI = s.intents.size(); 9853 int j; 9854 for (j=0; j<NI; j++) { 9855 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9856 if (DEBUG_SHOW_INFO) { 9857 Log.v(TAG, " IntentFilter:"); 9858 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9859 } 9860 removeFilter(intent); 9861 } 9862 } 9863 9864 @Override 9865 protected boolean allowFilterResult( 9866 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9867 ServiceInfo filterSi = filter.service.info; 9868 for (int i=dest.size()-1; i>=0; i--) { 9869 ServiceInfo destAi = dest.get(i).serviceInfo; 9870 if (destAi.name == filterSi.name 9871 && destAi.packageName == filterSi.packageName) { 9872 return false; 9873 } 9874 } 9875 return true; 9876 } 9877 9878 @Override 9879 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9880 return new PackageParser.ServiceIntentInfo[size]; 9881 } 9882 9883 @Override 9884 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9885 if (!sUserManager.exists(userId)) return true; 9886 PackageParser.Package p = filter.service.owner; 9887 if (p != null) { 9888 PackageSetting ps = (PackageSetting)p.mExtras; 9889 if (ps != null) { 9890 // System apps are never considered stopped for purposes of 9891 // filtering, because there may be no way for the user to 9892 // actually re-launch them. 9893 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9894 && ps.getStopped(userId); 9895 } 9896 } 9897 return false; 9898 } 9899 9900 @Override 9901 protected boolean isPackageForFilter(String packageName, 9902 PackageParser.ServiceIntentInfo info) { 9903 return packageName.equals(info.service.owner.packageName); 9904 } 9905 9906 @Override 9907 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9908 int match, int userId) { 9909 if (!sUserManager.exists(userId)) return null; 9910 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9911 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 9912 return null; 9913 } 9914 final PackageParser.Service service = info.service; 9915 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9916 if (ps == null) { 9917 return null; 9918 } 9919 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9920 ps.readUserState(userId), userId); 9921 if (si == null) { 9922 return null; 9923 } 9924 final ResolveInfo res = new ResolveInfo(); 9925 res.serviceInfo = si; 9926 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9927 res.filter = filter; 9928 } 9929 res.priority = info.getPriority(); 9930 res.preferredOrder = service.owner.mPreferredOrder; 9931 res.match = match; 9932 res.isDefault = info.hasDefault; 9933 res.labelRes = info.labelRes; 9934 res.nonLocalizedLabel = info.nonLocalizedLabel; 9935 res.icon = info.icon; 9936 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9937 return res; 9938 } 9939 9940 @Override 9941 protected void sortResults(List<ResolveInfo> results) { 9942 Collections.sort(results, mResolvePrioritySorter); 9943 } 9944 9945 @Override 9946 protected void dumpFilter(PrintWriter out, String prefix, 9947 PackageParser.ServiceIntentInfo filter) { 9948 out.print(prefix); out.print( 9949 Integer.toHexString(System.identityHashCode(filter.service))); 9950 out.print(' '); 9951 filter.service.printComponentShortName(out); 9952 out.print(" filter "); 9953 out.println(Integer.toHexString(System.identityHashCode(filter))); 9954 } 9955 9956 @Override 9957 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9958 return filter.service; 9959 } 9960 9961 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9962 PackageParser.Service service = (PackageParser.Service)label; 9963 out.print(prefix); out.print( 9964 Integer.toHexString(System.identityHashCode(service))); 9965 out.print(' '); 9966 service.printComponentShortName(out); 9967 if (count > 1) { 9968 out.print(" ("); out.print(count); out.print(" filters)"); 9969 } 9970 out.println(); 9971 } 9972 9973// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9974// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9975// final List<ResolveInfo> retList = Lists.newArrayList(); 9976// while (i.hasNext()) { 9977// final ResolveInfo resolveInfo = (ResolveInfo) i; 9978// if (isEnabledLP(resolveInfo.serviceInfo)) { 9979// retList.add(resolveInfo); 9980// } 9981// } 9982// return retList; 9983// } 9984 9985 // Keys are String (activity class name), values are Activity. 9986 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9987 = new ArrayMap<ComponentName, PackageParser.Service>(); 9988 private int mFlags; 9989 }; 9990 9991 private final class ProviderIntentResolver 9992 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9993 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9994 boolean defaultOnly, int userId) { 9995 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9996 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9997 } 9998 9999 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10000 int userId) { 10001 if (!sUserManager.exists(userId)) 10002 return null; 10003 mFlags = flags; 10004 return super.queryIntent(intent, resolvedType, 10005 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10006 } 10007 10008 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10009 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10010 if (!sUserManager.exists(userId)) 10011 return null; 10012 if (packageProviders == null) { 10013 return null; 10014 } 10015 mFlags = flags; 10016 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10017 final int N = packageProviders.size(); 10018 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10019 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10020 10021 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10022 for (int i = 0; i < N; ++i) { 10023 intentFilters = packageProviders.get(i).intents; 10024 if (intentFilters != null && intentFilters.size() > 0) { 10025 PackageParser.ProviderIntentInfo[] array = 10026 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10027 intentFilters.toArray(array); 10028 listCut.add(array); 10029 } 10030 } 10031 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10032 } 10033 10034 public final void addProvider(PackageParser.Provider p) { 10035 if (mProviders.containsKey(p.getComponentName())) { 10036 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10037 return; 10038 } 10039 10040 mProviders.put(p.getComponentName(), p); 10041 if (DEBUG_SHOW_INFO) { 10042 Log.v(TAG, " " 10043 + (p.info.nonLocalizedLabel != null 10044 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10045 Log.v(TAG, " Class=" + p.info.name); 10046 } 10047 final int NI = p.intents.size(); 10048 int j; 10049 for (j = 0; j < NI; j++) { 10050 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10051 if (DEBUG_SHOW_INFO) { 10052 Log.v(TAG, " IntentFilter:"); 10053 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10054 } 10055 if (!intent.debugCheck()) { 10056 Log.w(TAG, "==> For Provider " + p.info.name); 10057 } 10058 addFilter(intent); 10059 } 10060 } 10061 10062 public final void removeProvider(PackageParser.Provider p) { 10063 mProviders.remove(p.getComponentName()); 10064 if (DEBUG_SHOW_INFO) { 10065 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10066 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10067 Log.v(TAG, " Class=" + p.info.name); 10068 } 10069 final int NI = p.intents.size(); 10070 int j; 10071 for (j = 0; j < NI; j++) { 10072 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10073 if (DEBUG_SHOW_INFO) { 10074 Log.v(TAG, " IntentFilter:"); 10075 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10076 } 10077 removeFilter(intent); 10078 } 10079 } 10080 10081 @Override 10082 protected boolean allowFilterResult( 10083 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10084 ProviderInfo filterPi = filter.provider.info; 10085 for (int i = dest.size() - 1; i >= 0; i--) { 10086 ProviderInfo destPi = dest.get(i).providerInfo; 10087 if (destPi.name == filterPi.name 10088 && destPi.packageName == filterPi.packageName) { 10089 return false; 10090 } 10091 } 10092 return true; 10093 } 10094 10095 @Override 10096 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10097 return new PackageParser.ProviderIntentInfo[size]; 10098 } 10099 10100 @Override 10101 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10102 if (!sUserManager.exists(userId)) 10103 return true; 10104 PackageParser.Package p = filter.provider.owner; 10105 if (p != null) { 10106 PackageSetting ps = (PackageSetting) p.mExtras; 10107 if (ps != null) { 10108 // System apps are never considered stopped for purposes of 10109 // filtering, because there may be no way for the user to 10110 // actually re-launch them. 10111 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10112 && ps.getStopped(userId); 10113 } 10114 } 10115 return false; 10116 } 10117 10118 @Override 10119 protected boolean isPackageForFilter(String packageName, 10120 PackageParser.ProviderIntentInfo info) { 10121 return packageName.equals(info.provider.owner.packageName); 10122 } 10123 10124 @Override 10125 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10126 int match, int userId) { 10127 if (!sUserManager.exists(userId)) 10128 return null; 10129 final PackageParser.ProviderIntentInfo info = filter; 10130 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10131 return null; 10132 } 10133 final PackageParser.Provider provider = info.provider; 10134 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10135 if (ps == null) { 10136 return null; 10137 } 10138 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10139 ps.readUserState(userId), userId); 10140 if (pi == null) { 10141 return null; 10142 } 10143 final ResolveInfo res = new ResolveInfo(); 10144 res.providerInfo = pi; 10145 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10146 res.filter = filter; 10147 } 10148 res.priority = info.getPriority(); 10149 res.preferredOrder = provider.owner.mPreferredOrder; 10150 res.match = match; 10151 res.isDefault = info.hasDefault; 10152 res.labelRes = info.labelRes; 10153 res.nonLocalizedLabel = info.nonLocalizedLabel; 10154 res.icon = info.icon; 10155 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10156 return res; 10157 } 10158 10159 @Override 10160 protected void sortResults(List<ResolveInfo> results) { 10161 Collections.sort(results, mResolvePrioritySorter); 10162 } 10163 10164 @Override 10165 protected void dumpFilter(PrintWriter out, String prefix, 10166 PackageParser.ProviderIntentInfo filter) { 10167 out.print(prefix); 10168 out.print( 10169 Integer.toHexString(System.identityHashCode(filter.provider))); 10170 out.print(' '); 10171 filter.provider.printComponentShortName(out); 10172 out.print(" filter "); 10173 out.println(Integer.toHexString(System.identityHashCode(filter))); 10174 } 10175 10176 @Override 10177 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 10178 return filter.provider; 10179 } 10180 10181 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10182 PackageParser.Provider provider = (PackageParser.Provider)label; 10183 out.print(prefix); out.print( 10184 Integer.toHexString(System.identityHashCode(provider))); 10185 out.print(' '); 10186 provider.printComponentShortName(out); 10187 if (count > 1) { 10188 out.print(" ("); out.print(count); out.print(" filters)"); 10189 } 10190 out.println(); 10191 } 10192 10193 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 10194 = new ArrayMap<ComponentName, PackageParser.Provider>(); 10195 private int mFlags; 10196 } 10197 10198 private static final class EphemeralIntentResolver 10199 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 10200 @Override 10201 protected EphemeralResolveIntentInfo[] newArray(int size) { 10202 return new EphemeralResolveIntentInfo[size]; 10203 } 10204 10205 @Override 10206 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 10207 return true; 10208 } 10209 10210 @Override 10211 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 10212 int userId) { 10213 if (!sUserManager.exists(userId)) { 10214 return null; 10215 } 10216 return info.getEphemeralResolveInfo(); 10217 } 10218 } 10219 10220 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 10221 new Comparator<ResolveInfo>() { 10222 public int compare(ResolveInfo r1, ResolveInfo r2) { 10223 int v1 = r1.priority; 10224 int v2 = r2.priority; 10225 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 10226 if (v1 != v2) { 10227 return (v1 > v2) ? -1 : 1; 10228 } 10229 v1 = r1.preferredOrder; 10230 v2 = r2.preferredOrder; 10231 if (v1 != v2) { 10232 return (v1 > v2) ? -1 : 1; 10233 } 10234 if (r1.isDefault != r2.isDefault) { 10235 return r1.isDefault ? -1 : 1; 10236 } 10237 v1 = r1.match; 10238 v2 = r2.match; 10239 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 10240 if (v1 != v2) { 10241 return (v1 > v2) ? -1 : 1; 10242 } 10243 if (r1.system != r2.system) { 10244 return r1.system ? -1 : 1; 10245 } 10246 if (r1.activityInfo != null) { 10247 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 10248 } 10249 if (r1.serviceInfo != null) { 10250 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 10251 } 10252 if (r1.providerInfo != null) { 10253 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 10254 } 10255 return 0; 10256 } 10257 }; 10258 10259 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 10260 new Comparator<ProviderInfo>() { 10261 public int compare(ProviderInfo p1, ProviderInfo p2) { 10262 final int v1 = p1.initOrder; 10263 final int v2 = p2.initOrder; 10264 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 10265 } 10266 }; 10267 10268 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 10269 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 10270 final int[] userIds) { 10271 mHandler.post(new Runnable() { 10272 @Override 10273 public void run() { 10274 try { 10275 final IActivityManager am = ActivityManagerNative.getDefault(); 10276 if (am == null) return; 10277 final int[] resolvedUserIds; 10278 if (userIds == null) { 10279 resolvedUserIds = am.getRunningUserIds(); 10280 } else { 10281 resolvedUserIds = userIds; 10282 } 10283 for (int id : resolvedUserIds) { 10284 final Intent intent = new Intent(action, 10285 pkg != null ? Uri.fromParts("package", pkg, null) : null); 10286 if (extras != null) { 10287 intent.putExtras(extras); 10288 } 10289 if (targetPkg != null) { 10290 intent.setPackage(targetPkg); 10291 } 10292 // Modify the UID when posting to other users 10293 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 10294 if (uid > 0 && UserHandle.getUserId(uid) != id) { 10295 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 10296 intent.putExtra(Intent.EXTRA_UID, uid); 10297 } 10298 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 10299 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 10300 if (DEBUG_BROADCASTS) { 10301 RuntimeException here = new RuntimeException("here"); 10302 here.fillInStackTrace(); 10303 Slog.d(TAG, "Sending to user " + id + ": " 10304 + intent.toShortString(false, true, false, false) 10305 + " " + intent.getExtras(), here); 10306 } 10307 am.broadcastIntent(null, intent, null, finishedReceiver, 10308 0, null, null, null, android.app.AppOpsManager.OP_NONE, 10309 null, finishedReceiver != null, false, id); 10310 } 10311 } catch (RemoteException ex) { 10312 } 10313 } 10314 }); 10315 } 10316 10317 /** 10318 * Check if the external storage media is available. This is true if there 10319 * is a mounted external storage medium or if the external storage is 10320 * emulated. 10321 */ 10322 private boolean isExternalMediaAvailable() { 10323 return mMediaMounted || Environment.isExternalStorageEmulated(); 10324 } 10325 10326 @Override 10327 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 10328 // writer 10329 synchronized (mPackages) { 10330 if (!isExternalMediaAvailable()) { 10331 // If the external storage is no longer mounted at this point, 10332 // the caller may not have been able to delete all of this 10333 // packages files and can not delete any more. Bail. 10334 return null; 10335 } 10336 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 10337 if (lastPackage != null) { 10338 pkgs.remove(lastPackage); 10339 } 10340 if (pkgs.size() > 0) { 10341 return pkgs.get(0); 10342 } 10343 } 10344 return null; 10345 } 10346 10347 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 10348 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 10349 userId, andCode ? 1 : 0, packageName); 10350 if (mSystemReady) { 10351 msg.sendToTarget(); 10352 } else { 10353 if (mPostSystemReadyMessages == null) { 10354 mPostSystemReadyMessages = new ArrayList<>(); 10355 } 10356 mPostSystemReadyMessages.add(msg); 10357 } 10358 } 10359 10360 void startCleaningPackages() { 10361 // reader 10362 synchronized (mPackages) { 10363 if (!isExternalMediaAvailable()) { 10364 return; 10365 } 10366 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 10367 return; 10368 } 10369 } 10370 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 10371 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 10372 IActivityManager am = ActivityManagerNative.getDefault(); 10373 if (am != null) { 10374 try { 10375 am.startService(null, intent, null, mContext.getOpPackageName(), 10376 UserHandle.USER_SYSTEM); 10377 } catch (RemoteException e) { 10378 } 10379 } 10380 } 10381 10382 @Override 10383 public void installPackage(String originPath, IPackageInstallObserver2 observer, 10384 int installFlags, String installerPackageName, VerificationParams verificationParams, 10385 String packageAbiOverride) { 10386 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 10387 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 10388 } 10389 10390 @Override 10391 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 10392 int installFlags, String installerPackageName, VerificationParams verificationParams, 10393 String packageAbiOverride, int userId) { 10394 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 10395 10396 final int callingUid = Binder.getCallingUid(); 10397 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 10398 10399 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10400 try { 10401 if (observer != null) { 10402 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 10403 } 10404 } catch (RemoteException re) { 10405 } 10406 return; 10407 } 10408 10409 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 10410 installFlags |= PackageManager.INSTALL_FROM_ADB; 10411 10412 } else { 10413 // Caller holds INSTALL_PACKAGES permission, so we're less strict 10414 // about installerPackageName. 10415 10416 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 10417 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 10418 } 10419 10420 UserHandle user; 10421 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 10422 user = UserHandle.ALL; 10423 } else { 10424 user = new UserHandle(userId); 10425 } 10426 10427 // Only system components can circumvent runtime permissions when installing. 10428 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 10429 && mContext.checkCallingOrSelfPermission(Manifest.permission 10430 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 10431 throw new SecurityException("You need the " 10432 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 10433 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 10434 } 10435 10436 verificationParams.setInstallerUid(callingUid); 10437 10438 final File originFile = new File(originPath); 10439 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 10440 10441 final Message msg = mHandler.obtainMessage(INIT_COPY); 10442 final InstallParams params = new InstallParams(origin, null, observer, installFlags, 10443 installerPackageName, null, verificationParams, user, packageAbiOverride, null); 10444 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 10445 msg.obj = params; 10446 10447 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 10448 System.identityHashCode(msg.obj)); 10449 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10450 System.identityHashCode(msg.obj)); 10451 10452 mHandler.sendMessage(msg); 10453 } 10454 10455 void installStage(String packageName, File stagedDir, String stagedCid, 10456 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 10457 String installerPackageName, int installerUid, UserHandle user) { 10458 if (DEBUG_EPHEMERAL) { 10459 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10460 Slog.d(TAG, "Ephemeral install of " + packageName); 10461 } 10462 } 10463 final VerificationParams verifParams = new VerificationParams( 10464 null, sessionParams.originatingUri, sessionParams.referrerUri, 10465 sessionParams.originatingUid); 10466 verifParams.setInstallerUid(installerUid); 10467 10468 final OriginInfo origin; 10469 if (stagedDir != null) { 10470 origin = OriginInfo.fromStagedFile(stagedDir); 10471 } else { 10472 origin = OriginInfo.fromStagedContainer(stagedCid); 10473 } 10474 10475 final Message msg = mHandler.obtainMessage(INIT_COPY); 10476 final InstallParams params = new InstallParams(origin, null, observer, 10477 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 10478 verifParams, user, sessionParams.abiOverride, 10479 sessionParams.grantedRuntimePermissions); 10480 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 10481 msg.obj = params; 10482 10483 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 10484 System.identityHashCode(msg.obj)); 10485 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10486 System.identityHashCode(msg.obj)); 10487 10488 mHandler.sendMessage(msg); 10489 } 10490 10491 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 10492 int userId) { 10493 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 10494 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 10495 } 10496 10497 private void sendPackageAddedForUser(String packageName, boolean isSystem, 10498 int appId, int userId) { 10499 Bundle extras = new Bundle(1); 10500 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 10501 10502 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 10503 packageName, extras, 0, null, null, new int[] {userId}); 10504 try { 10505 IActivityManager am = ActivityManagerNative.getDefault(); 10506 if (isSystem && am.isUserRunning(userId, 0)) { 10507 // The just-installed/enabled app is bundled on the system, so presumed 10508 // to be able to run automatically without needing an explicit launch. 10509 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 10510 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 10511 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 10512 .setPackage(packageName); 10513 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 10514 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 10515 } 10516 } catch (RemoteException e) { 10517 // shouldn't happen 10518 Slog.w(TAG, "Unable to bootstrap installed package", e); 10519 } 10520 } 10521 10522 @Override 10523 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 10524 int userId) { 10525 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10526 PackageSetting pkgSetting; 10527 final int uid = Binder.getCallingUid(); 10528 enforceCrossUserPermission(uid, userId, true, true, 10529 "setApplicationHiddenSetting for user " + userId); 10530 10531 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 10532 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 10533 return false; 10534 } 10535 10536 long callingId = Binder.clearCallingIdentity(); 10537 try { 10538 boolean sendAdded = false; 10539 boolean sendRemoved = false; 10540 // writer 10541 synchronized (mPackages) { 10542 pkgSetting = mSettings.mPackages.get(packageName); 10543 if (pkgSetting == null) { 10544 return false; 10545 } 10546 if (pkgSetting.getHidden(userId) != hidden) { 10547 pkgSetting.setHidden(hidden, userId); 10548 mSettings.writePackageRestrictionsLPr(userId); 10549 if (hidden) { 10550 sendRemoved = true; 10551 } else { 10552 sendAdded = true; 10553 } 10554 } 10555 } 10556 if (sendAdded) { 10557 sendPackageAddedForUser(packageName, pkgSetting, userId); 10558 return true; 10559 } 10560 if (sendRemoved) { 10561 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 10562 "hiding pkg"); 10563 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 10564 return true; 10565 } 10566 } finally { 10567 Binder.restoreCallingIdentity(callingId); 10568 } 10569 return false; 10570 } 10571 10572 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 10573 int userId) { 10574 final PackageRemovedInfo info = new PackageRemovedInfo(); 10575 info.removedPackage = packageName; 10576 info.removedUsers = new int[] {userId}; 10577 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 10578 info.sendPackageRemovedBroadcasts(); 10579 } 10580 10581 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 10582 if (pkgList.length > 0) { 10583 Bundle extras = new Bundle(1); 10584 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 10585 10586 sendPackageBroadcast( 10587 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 10588 : Intent.ACTION_PACKAGES_UNSUSPENDED, 10589 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 10590 new int[] {userId}); 10591 } 10592 } 10593 10594 /** 10595 * Returns true if application is not found or there was an error. Otherwise it returns 10596 * the hidden state of the package for the given user. 10597 */ 10598 @Override 10599 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 10600 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10601 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 10602 false, "getApplicationHidden for user " + userId); 10603 PackageSetting pkgSetting; 10604 long callingId = Binder.clearCallingIdentity(); 10605 try { 10606 // writer 10607 synchronized (mPackages) { 10608 pkgSetting = mSettings.mPackages.get(packageName); 10609 if (pkgSetting == null) { 10610 return true; 10611 } 10612 return pkgSetting.getHidden(userId); 10613 } 10614 } finally { 10615 Binder.restoreCallingIdentity(callingId); 10616 } 10617 } 10618 10619 /** 10620 * @hide 10621 */ 10622 @Override 10623 public int installExistingPackageAsUser(String packageName, int userId) { 10624 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 10625 null); 10626 PackageSetting pkgSetting; 10627 final int uid = Binder.getCallingUid(); 10628 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 10629 + userId); 10630 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10631 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 10632 } 10633 10634 long callingId = Binder.clearCallingIdentity(); 10635 try { 10636 boolean installed = false; 10637 10638 // writer 10639 synchronized (mPackages) { 10640 pkgSetting = mSettings.mPackages.get(packageName); 10641 if (pkgSetting == null) { 10642 return PackageManager.INSTALL_FAILED_INVALID_URI; 10643 } 10644 if (!pkgSetting.getInstalled(userId)) { 10645 pkgSetting.setInstalled(true, userId); 10646 pkgSetting.setHidden(false, userId); 10647 mSettings.writePackageRestrictionsLPr(userId); 10648 if (pkgSetting.pkg != null) { 10649 prepareAppDataAfterInstall(pkgSetting.pkg); 10650 } 10651 installed = true; 10652 } 10653 } 10654 10655 if (installed) { 10656 sendPackageAddedForUser(packageName, pkgSetting, userId); 10657 } 10658 } finally { 10659 Binder.restoreCallingIdentity(callingId); 10660 } 10661 10662 return PackageManager.INSTALL_SUCCEEDED; 10663 } 10664 10665 boolean isUserRestricted(int userId, String restrictionKey) { 10666 Bundle restrictions = sUserManager.getUserRestrictions(userId); 10667 if (restrictions.getBoolean(restrictionKey, false)) { 10668 Log.w(TAG, "User is restricted: " + restrictionKey); 10669 return true; 10670 } 10671 return false; 10672 } 10673 10674 @Override 10675 public boolean setPackageSuspendedAsUser(String packageName, boolean suspended, int userId) { 10676 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10677 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true, 10678 "setPackageSuspended for user " + userId); 10679 10680 // TODO: investigate and add more restrictions for suspending crucial packages. 10681 if (isPackageDeviceAdmin(packageName, userId)) { 10682 Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName 10683 + "\": has active device admin"); 10684 return false; 10685 } 10686 10687 long callingId = Binder.clearCallingIdentity(); 10688 try { 10689 boolean changed = false; 10690 boolean success = false; 10691 int appId = -1; 10692 synchronized (mPackages) { 10693 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10694 if (pkgSetting != null) { 10695 if (pkgSetting.getSuspended(userId) != suspended) { 10696 pkgSetting.setSuspended(suspended, userId); 10697 mSettings.writePackageRestrictionsLPr(userId); 10698 appId = pkgSetting.appId; 10699 changed = true; 10700 } 10701 success = true; 10702 } 10703 } 10704 10705 if (changed) { 10706 sendPackagesSuspendedForUser(new String[]{packageName}, userId, suspended); 10707 if (suspended) { 10708 killApplication(packageName, UserHandle.getUid(userId, appId), 10709 "suspending package"); 10710 } 10711 } 10712 return success; 10713 } finally { 10714 Binder.restoreCallingIdentity(callingId); 10715 } 10716 } 10717 10718 @Override 10719 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 10720 mContext.enforceCallingOrSelfPermission( 10721 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10722 "Only package verification agents can verify applications"); 10723 10724 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10725 final PackageVerificationResponse response = new PackageVerificationResponse( 10726 verificationCode, Binder.getCallingUid()); 10727 msg.arg1 = id; 10728 msg.obj = response; 10729 mHandler.sendMessage(msg); 10730 } 10731 10732 @Override 10733 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 10734 long millisecondsToDelay) { 10735 mContext.enforceCallingOrSelfPermission( 10736 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10737 "Only package verification agents can extend verification timeouts"); 10738 10739 final PackageVerificationState state = mPendingVerification.get(id); 10740 final PackageVerificationResponse response = new PackageVerificationResponse( 10741 verificationCodeAtTimeout, Binder.getCallingUid()); 10742 10743 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 10744 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 10745 } 10746 if (millisecondsToDelay < 0) { 10747 millisecondsToDelay = 0; 10748 } 10749 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 10750 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 10751 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 10752 } 10753 10754 if ((state != null) && !state.timeoutExtended()) { 10755 state.extendTimeout(); 10756 10757 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10758 msg.arg1 = id; 10759 msg.obj = response; 10760 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 10761 } 10762 } 10763 10764 private void broadcastPackageVerified(int verificationId, Uri packageUri, 10765 int verificationCode, UserHandle user) { 10766 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 10767 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 10768 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10769 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10770 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 10771 10772 mContext.sendBroadcastAsUser(intent, user, 10773 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 10774 } 10775 10776 private ComponentName matchComponentForVerifier(String packageName, 10777 List<ResolveInfo> receivers) { 10778 ActivityInfo targetReceiver = null; 10779 10780 final int NR = receivers.size(); 10781 for (int i = 0; i < NR; i++) { 10782 final ResolveInfo info = receivers.get(i); 10783 if (info.activityInfo == null) { 10784 continue; 10785 } 10786 10787 if (packageName.equals(info.activityInfo.packageName)) { 10788 targetReceiver = info.activityInfo; 10789 break; 10790 } 10791 } 10792 10793 if (targetReceiver == null) { 10794 return null; 10795 } 10796 10797 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 10798 } 10799 10800 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 10801 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 10802 if (pkgInfo.verifiers.length == 0) { 10803 return null; 10804 } 10805 10806 final int N = pkgInfo.verifiers.length; 10807 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 10808 for (int i = 0; i < N; i++) { 10809 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 10810 10811 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 10812 receivers); 10813 if (comp == null) { 10814 continue; 10815 } 10816 10817 final int verifierUid = getUidForVerifier(verifierInfo); 10818 if (verifierUid == -1) { 10819 continue; 10820 } 10821 10822 if (DEBUG_VERIFY) { 10823 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 10824 + " with the correct signature"); 10825 } 10826 sufficientVerifiers.add(comp); 10827 verificationState.addSufficientVerifier(verifierUid); 10828 } 10829 10830 return sufficientVerifiers; 10831 } 10832 10833 private int getUidForVerifier(VerifierInfo verifierInfo) { 10834 synchronized (mPackages) { 10835 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 10836 if (pkg == null) { 10837 return -1; 10838 } else if (pkg.mSignatures.length != 1) { 10839 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10840 + " has more than one signature; ignoring"); 10841 return -1; 10842 } 10843 10844 /* 10845 * If the public key of the package's signature does not match 10846 * our expected public key, then this is a different package and 10847 * we should skip. 10848 */ 10849 10850 final byte[] expectedPublicKey; 10851 try { 10852 final Signature verifierSig = pkg.mSignatures[0]; 10853 final PublicKey publicKey = verifierSig.getPublicKey(); 10854 expectedPublicKey = publicKey.getEncoded(); 10855 } catch (CertificateException e) { 10856 return -1; 10857 } 10858 10859 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 10860 10861 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 10862 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10863 + " does not have the expected public key; ignoring"); 10864 return -1; 10865 } 10866 10867 return pkg.applicationInfo.uid; 10868 } 10869 } 10870 10871 @Override 10872 public void finishPackageInstall(int token) { 10873 enforceSystemOrRoot("Only the system is allowed to finish installs"); 10874 10875 if (DEBUG_INSTALL) { 10876 Slog.v(TAG, "BM finishing package install for " + token); 10877 } 10878 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10879 10880 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10881 mHandler.sendMessage(msg); 10882 } 10883 10884 /** 10885 * Get the verification agent timeout. 10886 * 10887 * @return verification timeout in milliseconds 10888 */ 10889 private long getVerificationTimeout() { 10890 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 10891 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 10892 DEFAULT_VERIFICATION_TIMEOUT); 10893 } 10894 10895 /** 10896 * Get the default verification agent response code. 10897 * 10898 * @return default verification response code 10899 */ 10900 private int getDefaultVerificationResponse() { 10901 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10902 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 10903 DEFAULT_VERIFICATION_RESPONSE); 10904 } 10905 10906 /** 10907 * Check whether or not package verification has been enabled. 10908 * 10909 * @return true if verification should be performed 10910 */ 10911 private boolean isVerificationEnabled(int userId, int installFlags) { 10912 if (!DEFAULT_VERIFY_ENABLE) { 10913 return false; 10914 } 10915 // Ephemeral apps don't get the full verification treatment 10916 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10917 if (DEBUG_EPHEMERAL) { 10918 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 10919 } 10920 return false; 10921 } 10922 10923 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 10924 10925 // Check if installing from ADB 10926 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 10927 // Do not run verification in a test harness environment 10928 if (ActivityManager.isRunningInTestHarness()) { 10929 return false; 10930 } 10931 if (ensureVerifyAppsEnabled) { 10932 return true; 10933 } 10934 // Check if the developer does not want package verification for ADB installs 10935 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10936 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 10937 return false; 10938 } 10939 } 10940 10941 if (ensureVerifyAppsEnabled) { 10942 return true; 10943 } 10944 10945 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10946 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 10947 } 10948 10949 @Override 10950 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 10951 throws RemoteException { 10952 mContext.enforceCallingOrSelfPermission( 10953 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 10954 "Only intentfilter verification agents can verify applications"); 10955 10956 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 10957 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 10958 Binder.getCallingUid(), verificationCode, failedDomains); 10959 msg.arg1 = id; 10960 msg.obj = response; 10961 mHandler.sendMessage(msg); 10962 } 10963 10964 @Override 10965 public int getIntentVerificationStatus(String packageName, int userId) { 10966 synchronized (mPackages) { 10967 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10968 } 10969 } 10970 10971 @Override 10972 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10973 mContext.enforceCallingOrSelfPermission( 10974 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10975 10976 boolean result = false; 10977 synchronized (mPackages) { 10978 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10979 } 10980 if (result) { 10981 scheduleWritePackageRestrictionsLocked(userId); 10982 } 10983 return result; 10984 } 10985 10986 @Override 10987 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10988 synchronized (mPackages) { 10989 return mSettings.getIntentFilterVerificationsLPr(packageName); 10990 } 10991 } 10992 10993 @Override 10994 public List<IntentFilter> getAllIntentFilters(String packageName) { 10995 if (TextUtils.isEmpty(packageName)) { 10996 return Collections.<IntentFilter>emptyList(); 10997 } 10998 synchronized (mPackages) { 10999 PackageParser.Package pkg = mPackages.get(packageName); 11000 if (pkg == null || pkg.activities == null) { 11001 return Collections.<IntentFilter>emptyList(); 11002 } 11003 final int count = pkg.activities.size(); 11004 ArrayList<IntentFilter> result = new ArrayList<>(); 11005 for (int n=0; n<count; n++) { 11006 PackageParser.Activity activity = pkg.activities.get(n); 11007 if (activity.intents != null && activity.intents.size() > 0) { 11008 result.addAll(activity.intents); 11009 } 11010 } 11011 return result; 11012 } 11013 } 11014 11015 @Override 11016 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11017 mContext.enforceCallingOrSelfPermission( 11018 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11019 11020 synchronized (mPackages) { 11021 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11022 if (packageName != null) { 11023 result |= updateIntentVerificationStatus(packageName, 11024 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11025 userId); 11026 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11027 packageName, userId); 11028 } 11029 return result; 11030 } 11031 } 11032 11033 @Override 11034 public String getDefaultBrowserPackageName(int userId) { 11035 synchronized (mPackages) { 11036 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11037 } 11038 } 11039 11040 /** 11041 * Get the "allow unknown sources" setting. 11042 * 11043 * @return the current "allow unknown sources" setting 11044 */ 11045 private int getUnknownSourcesSettings() { 11046 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11047 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 11048 -1); 11049 } 11050 11051 @Override 11052 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11053 final int uid = Binder.getCallingUid(); 11054 // writer 11055 synchronized (mPackages) { 11056 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11057 if (targetPackageSetting == null) { 11058 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11059 } 11060 11061 PackageSetting installerPackageSetting; 11062 if (installerPackageName != null) { 11063 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11064 if (installerPackageSetting == null) { 11065 throw new IllegalArgumentException("Unknown installer package: " 11066 + installerPackageName); 11067 } 11068 } else { 11069 installerPackageSetting = null; 11070 } 11071 11072 Signature[] callerSignature; 11073 Object obj = mSettings.getUserIdLPr(uid); 11074 if (obj != null) { 11075 if (obj instanceof SharedUserSetting) { 11076 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11077 } else if (obj instanceof PackageSetting) { 11078 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11079 } else { 11080 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11081 } 11082 } else { 11083 throw new SecurityException("Unknown calling UID: " + uid); 11084 } 11085 11086 // Verify: can't set installerPackageName to a package that is 11087 // not signed with the same cert as the caller. 11088 if (installerPackageSetting != null) { 11089 if (compareSignatures(callerSignature, 11090 installerPackageSetting.signatures.mSignatures) 11091 != PackageManager.SIGNATURE_MATCH) { 11092 throw new SecurityException( 11093 "Caller does not have same cert as new installer package " 11094 + installerPackageName); 11095 } 11096 } 11097 11098 // Verify: if target already has an installer package, it must 11099 // be signed with the same cert as the caller. 11100 if (targetPackageSetting.installerPackageName != null) { 11101 PackageSetting setting = mSettings.mPackages.get( 11102 targetPackageSetting.installerPackageName); 11103 // If the currently set package isn't valid, then it's always 11104 // okay to change it. 11105 if (setting != null) { 11106 if (compareSignatures(callerSignature, 11107 setting.signatures.mSignatures) 11108 != PackageManager.SIGNATURE_MATCH) { 11109 throw new SecurityException( 11110 "Caller does not have same cert as old installer package " 11111 + targetPackageSetting.installerPackageName); 11112 } 11113 } 11114 } 11115 11116 // Okay! 11117 targetPackageSetting.installerPackageName = installerPackageName; 11118 scheduleWriteSettingsLocked(); 11119 } 11120 } 11121 11122 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 11123 // Queue up an async operation since the package installation may take a little while. 11124 mHandler.post(new Runnable() { 11125 public void run() { 11126 mHandler.removeCallbacks(this); 11127 // Result object to be returned 11128 PackageInstalledInfo res = new PackageInstalledInfo(); 11129 res.setReturnCode(currentStatus); 11130 res.uid = -1; 11131 res.pkg = null; 11132 res.removedInfo = null; 11133 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11134 args.doPreInstall(res.returnCode); 11135 synchronized (mInstallLock) { 11136 installPackageTracedLI(args, res); 11137 } 11138 args.doPostInstall(res.returnCode, res.uid); 11139 } 11140 11141 // A restore should be performed at this point if (a) the install 11142 // succeeded, (b) the operation is not an update, and (c) the new 11143 // package has not opted out of backup participation. 11144 final boolean update = res.removedInfo != null 11145 && res.removedInfo.removedPackage != null; 11146 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 11147 boolean doRestore = !update 11148 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 11149 11150 // Set up the post-install work request bookkeeping. This will be used 11151 // and cleaned up by the post-install event handling regardless of whether 11152 // there's a restore pass performed. Token values are >= 1. 11153 int token; 11154 if (mNextInstallToken < 0) mNextInstallToken = 1; 11155 token = mNextInstallToken++; 11156 11157 PostInstallData data = new PostInstallData(args, res); 11158 mRunningInstalls.put(token, data); 11159 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 11160 11161 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 11162 // Pass responsibility to the Backup Manager. It will perform a 11163 // restore if appropriate, then pass responsibility back to the 11164 // Package Manager to run the post-install observer callbacks 11165 // and broadcasts. 11166 IBackupManager bm = IBackupManager.Stub.asInterface( 11167 ServiceManager.getService(Context.BACKUP_SERVICE)); 11168 if (bm != null) { 11169 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 11170 + " to BM for possible restore"); 11171 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11172 try { 11173 // TODO: http://b/22388012 11174 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 11175 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 11176 } else { 11177 doRestore = false; 11178 } 11179 } catch (RemoteException e) { 11180 // can't happen; the backup manager is local 11181 } catch (Exception e) { 11182 Slog.e(TAG, "Exception trying to enqueue restore", e); 11183 doRestore = false; 11184 } 11185 } else { 11186 Slog.e(TAG, "Backup Manager not found!"); 11187 doRestore = false; 11188 } 11189 } 11190 11191 if (!doRestore) { 11192 // No restore possible, or the Backup Manager was mysteriously not 11193 // available -- just fire the post-install work request directly. 11194 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 11195 11196 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 11197 11198 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11199 mHandler.sendMessage(msg); 11200 } 11201 } 11202 }); 11203 } 11204 11205 private abstract class HandlerParams { 11206 private static final int MAX_RETRIES = 4; 11207 11208 /** 11209 * Number of times startCopy() has been attempted and had a non-fatal 11210 * error. 11211 */ 11212 private int mRetries = 0; 11213 11214 /** User handle for the user requesting the information or installation. */ 11215 private final UserHandle mUser; 11216 String traceMethod; 11217 int traceCookie; 11218 11219 HandlerParams(UserHandle user) { 11220 mUser = user; 11221 } 11222 11223 UserHandle getUser() { 11224 return mUser; 11225 } 11226 11227 HandlerParams setTraceMethod(String traceMethod) { 11228 this.traceMethod = traceMethod; 11229 return this; 11230 } 11231 11232 HandlerParams setTraceCookie(int traceCookie) { 11233 this.traceCookie = traceCookie; 11234 return this; 11235 } 11236 11237 final boolean startCopy() { 11238 boolean res; 11239 try { 11240 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 11241 11242 if (++mRetries > MAX_RETRIES) { 11243 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 11244 mHandler.sendEmptyMessage(MCS_GIVE_UP); 11245 handleServiceError(); 11246 return false; 11247 } else { 11248 handleStartCopy(); 11249 res = true; 11250 } 11251 } catch (RemoteException e) { 11252 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 11253 mHandler.sendEmptyMessage(MCS_RECONNECT); 11254 res = false; 11255 } 11256 handleReturnCode(); 11257 return res; 11258 } 11259 11260 final void serviceError() { 11261 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 11262 handleServiceError(); 11263 handleReturnCode(); 11264 } 11265 11266 abstract void handleStartCopy() throws RemoteException; 11267 abstract void handleServiceError(); 11268 abstract void handleReturnCode(); 11269 } 11270 11271 class MeasureParams extends HandlerParams { 11272 private final PackageStats mStats; 11273 private boolean mSuccess; 11274 11275 private final IPackageStatsObserver mObserver; 11276 11277 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 11278 super(new UserHandle(stats.userHandle)); 11279 mObserver = observer; 11280 mStats = stats; 11281 } 11282 11283 @Override 11284 public String toString() { 11285 return "MeasureParams{" 11286 + Integer.toHexString(System.identityHashCode(this)) 11287 + " " + mStats.packageName + "}"; 11288 } 11289 11290 @Override 11291 void handleStartCopy() throws RemoteException { 11292 synchronized (mInstallLock) { 11293 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 11294 } 11295 11296 if (mSuccess) { 11297 final boolean mounted; 11298 if (Environment.isExternalStorageEmulated()) { 11299 mounted = true; 11300 } else { 11301 final String status = Environment.getExternalStorageState(); 11302 mounted = (Environment.MEDIA_MOUNTED.equals(status) 11303 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 11304 } 11305 11306 if (mounted) { 11307 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 11308 11309 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 11310 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 11311 11312 mStats.externalDataSize = calculateDirectorySize(mContainerService, 11313 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 11314 11315 // Always subtract cache size, since it's a subdirectory 11316 mStats.externalDataSize -= mStats.externalCacheSize; 11317 11318 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 11319 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 11320 11321 mStats.externalObbSize = calculateDirectorySize(mContainerService, 11322 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 11323 } 11324 } 11325 } 11326 11327 @Override 11328 void handleReturnCode() { 11329 if (mObserver != null) { 11330 try { 11331 mObserver.onGetStatsCompleted(mStats, mSuccess); 11332 } catch (RemoteException e) { 11333 Slog.i(TAG, "Observer no longer exists."); 11334 } 11335 } 11336 } 11337 11338 @Override 11339 void handleServiceError() { 11340 Slog.e(TAG, "Could not measure application " + mStats.packageName 11341 + " external storage"); 11342 } 11343 } 11344 11345 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 11346 throws RemoteException { 11347 long result = 0; 11348 for (File path : paths) { 11349 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 11350 } 11351 return result; 11352 } 11353 11354 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 11355 for (File path : paths) { 11356 try { 11357 mcs.clearDirectory(path.getAbsolutePath()); 11358 } catch (RemoteException e) { 11359 } 11360 } 11361 } 11362 11363 static class OriginInfo { 11364 /** 11365 * Location where install is coming from, before it has been 11366 * copied/renamed into place. This could be a single monolithic APK 11367 * file, or a cluster directory. This location may be untrusted. 11368 */ 11369 final File file; 11370 final String cid; 11371 11372 /** 11373 * Flag indicating that {@link #file} or {@link #cid} has already been 11374 * staged, meaning downstream users don't need to defensively copy the 11375 * contents. 11376 */ 11377 final boolean staged; 11378 11379 /** 11380 * Flag indicating that {@link #file} or {@link #cid} is an already 11381 * installed app that is being moved. 11382 */ 11383 final boolean existing; 11384 11385 final String resolvedPath; 11386 final File resolvedFile; 11387 11388 static OriginInfo fromNothing() { 11389 return new OriginInfo(null, null, false, false); 11390 } 11391 11392 static OriginInfo fromUntrustedFile(File file) { 11393 return new OriginInfo(file, null, false, false); 11394 } 11395 11396 static OriginInfo fromExistingFile(File file) { 11397 return new OriginInfo(file, null, false, true); 11398 } 11399 11400 static OriginInfo fromStagedFile(File file) { 11401 return new OriginInfo(file, null, true, false); 11402 } 11403 11404 static OriginInfo fromStagedContainer(String cid) { 11405 return new OriginInfo(null, cid, true, false); 11406 } 11407 11408 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 11409 this.file = file; 11410 this.cid = cid; 11411 this.staged = staged; 11412 this.existing = existing; 11413 11414 if (cid != null) { 11415 resolvedPath = PackageHelper.getSdDir(cid); 11416 resolvedFile = new File(resolvedPath); 11417 } else if (file != null) { 11418 resolvedPath = file.getAbsolutePath(); 11419 resolvedFile = file; 11420 } else { 11421 resolvedPath = null; 11422 resolvedFile = null; 11423 } 11424 } 11425 } 11426 11427 static class MoveInfo { 11428 final int moveId; 11429 final String fromUuid; 11430 final String toUuid; 11431 final String packageName; 11432 final String dataAppName; 11433 final int appId; 11434 final String seinfo; 11435 final int targetSdkVersion; 11436 11437 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 11438 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 11439 this.moveId = moveId; 11440 this.fromUuid = fromUuid; 11441 this.toUuid = toUuid; 11442 this.packageName = packageName; 11443 this.dataAppName = dataAppName; 11444 this.appId = appId; 11445 this.seinfo = seinfo; 11446 this.targetSdkVersion = targetSdkVersion; 11447 } 11448 } 11449 11450 class InstallParams extends HandlerParams { 11451 final OriginInfo origin; 11452 final MoveInfo move; 11453 final IPackageInstallObserver2 observer; 11454 int installFlags; 11455 final String installerPackageName; 11456 final String volumeUuid; 11457 final VerificationParams verificationParams; 11458 private InstallArgs mArgs; 11459 private int mRet; 11460 final String packageAbiOverride; 11461 final String[] grantedRuntimePermissions; 11462 11463 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11464 int installFlags, String installerPackageName, String volumeUuid, 11465 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 11466 String[] grantedPermissions) { 11467 super(user); 11468 this.origin = origin; 11469 this.move = move; 11470 this.observer = observer; 11471 this.installFlags = installFlags; 11472 this.installerPackageName = installerPackageName; 11473 this.volumeUuid = volumeUuid; 11474 this.verificationParams = verificationParams; 11475 this.packageAbiOverride = packageAbiOverride; 11476 this.grantedRuntimePermissions = grantedPermissions; 11477 } 11478 11479 @Override 11480 public String toString() { 11481 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 11482 + " file=" + origin.file + " cid=" + origin.cid + "}"; 11483 } 11484 11485 private int installLocationPolicy(PackageInfoLite pkgLite) { 11486 String packageName = pkgLite.packageName; 11487 int installLocation = pkgLite.installLocation; 11488 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11489 // reader 11490 synchronized (mPackages) { 11491 PackageParser.Package pkg = mPackages.get(packageName); 11492 if (pkg != null) { 11493 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11494 // Check for downgrading. 11495 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 11496 try { 11497 checkDowngrade(pkg, pkgLite); 11498 } catch (PackageManagerException e) { 11499 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 11500 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 11501 } 11502 } 11503 // Check for updated system application. 11504 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11505 if (onSd) { 11506 Slog.w(TAG, "Cannot install update to system app on sdcard"); 11507 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 11508 } 11509 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11510 } else { 11511 if (onSd) { 11512 // Install flag overrides everything. 11513 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11514 } 11515 // If current upgrade specifies particular preference 11516 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 11517 // Application explicitly specified internal. 11518 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11519 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 11520 // App explictly prefers external. Let policy decide 11521 } else { 11522 // Prefer previous location 11523 if (isExternal(pkg)) { 11524 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11525 } 11526 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11527 } 11528 } 11529 } else { 11530 // Invalid install. Return error code 11531 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 11532 } 11533 } 11534 } 11535 // All the special cases have been taken care of. 11536 // Return result based on recommended install location. 11537 if (onSd) { 11538 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11539 } 11540 return pkgLite.recommendedInstallLocation; 11541 } 11542 11543 /* 11544 * Invoke remote method to get package information and install 11545 * location values. Override install location based on default 11546 * policy if needed and then create install arguments based 11547 * on the install location. 11548 */ 11549 public void handleStartCopy() throws RemoteException { 11550 int ret = PackageManager.INSTALL_SUCCEEDED; 11551 11552 // If we're already staged, we've firmly committed to an install location 11553 if (origin.staged) { 11554 if (origin.file != null) { 11555 installFlags |= PackageManager.INSTALL_INTERNAL; 11556 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11557 } else if (origin.cid != null) { 11558 installFlags |= PackageManager.INSTALL_EXTERNAL; 11559 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11560 } else { 11561 throw new IllegalStateException("Invalid stage location"); 11562 } 11563 } 11564 11565 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11566 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 11567 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11568 PackageInfoLite pkgLite = null; 11569 11570 if (onInt && onSd) { 11571 // Check if both bits are set. 11572 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 11573 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11574 } else if (onSd && ephemeral) { 11575 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 11576 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11577 } else { 11578 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 11579 packageAbiOverride); 11580 11581 if (DEBUG_EPHEMERAL && ephemeral) { 11582 Slog.v(TAG, "pkgLite for install: " + pkgLite); 11583 } 11584 11585 /* 11586 * If we have too little free space, try to free cache 11587 * before giving up. 11588 */ 11589 if (!origin.staged && pkgLite.recommendedInstallLocation 11590 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11591 // TODO: focus freeing disk space on the target device 11592 final StorageManager storage = StorageManager.from(mContext); 11593 final long lowThreshold = storage.getStorageLowBytes( 11594 Environment.getDataDirectory()); 11595 11596 final long sizeBytes = mContainerService.calculateInstalledSize( 11597 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 11598 11599 try { 11600 mInstaller.freeCache(null, sizeBytes + lowThreshold); 11601 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 11602 installFlags, packageAbiOverride); 11603 } catch (InstallerException e) { 11604 Slog.w(TAG, "Failed to free cache", e); 11605 } 11606 11607 /* 11608 * The cache free must have deleted the file we 11609 * downloaded to install. 11610 * 11611 * TODO: fix the "freeCache" call to not delete 11612 * the file we care about. 11613 */ 11614 if (pkgLite.recommendedInstallLocation 11615 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11616 pkgLite.recommendedInstallLocation 11617 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 11618 } 11619 } 11620 } 11621 11622 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11623 int loc = pkgLite.recommendedInstallLocation; 11624 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 11625 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11626 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 11627 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 11628 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11629 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11630 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 11631 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 11632 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11633 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 11634 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 11635 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 11636 } else { 11637 // Override with defaults if needed. 11638 loc = installLocationPolicy(pkgLite); 11639 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 11640 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 11641 } else if (!onSd && !onInt) { 11642 // Override install location with flags 11643 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 11644 // Set the flag to install on external media. 11645 installFlags |= PackageManager.INSTALL_EXTERNAL; 11646 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11647 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 11648 if (DEBUG_EPHEMERAL) { 11649 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 11650 } 11651 installFlags |= PackageManager.INSTALL_EPHEMERAL; 11652 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 11653 |PackageManager.INSTALL_INTERNAL); 11654 } else { 11655 // Make sure the flag for installing on external 11656 // media is unset 11657 installFlags |= PackageManager.INSTALL_INTERNAL; 11658 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11659 } 11660 } 11661 } 11662 } 11663 11664 final InstallArgs args = createInstallArgs(this); 11665 mArgs = args; 11666 11667 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11668 // TODO: http://b/22976637 11669 // Apps installed for "all" users use the device owner to verify the app 11670 UserHandle verifierUser = getUser(); 11671 if (verifierUser == UserHandle.ALL) { 11672 verifierUser = UserHandle.SYSTEM; 11673 } 11674 11675 /* 11676 * Determine if we have any installed package verifiers. If we 11677 * do, then we'll defer to them to verify the packages. 11678 */ 11679 final int requiredUid = mRequiredVerifierPackage == null ? -1 11680 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 11681 verifierUser.getIdentifier()); 11682 if (!origin.existing && requiredUid != -1 11683 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 11684 final Intent verification = new Intent( 11685 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 11686 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 11687 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 11688 PACKAGE_MIME_TYPE); 11689 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11690 11691 // Query all live verifiers based on current user state 11692 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 11693 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 11694 11695 if (DEBUG_VERIFY) { 11696 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 11697 + verification.toString() + " with " + pkgLite.verifiers.length 11698 + " optional verifiers"); 11699 } 11700 11701 final int verificationId = mPendingVerificationToken++; 11702 11703 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11704 11705 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 11706 installerPackageName); 11707 11708 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 11709 installFlags); 11710 11711 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 11712 pkgLite.packageName); 11713 11714 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 11715 pkgLite.versionCode); 11716 11717 if (verificationParams != null) { 11718 if (verificationParams.getVerificationURI() != null) { 11719 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 11720 verificationParams.getVerificationURI()); 11721 } 11722 if (verificationParams.getOriginatingURI() != null) { 11723 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 11724 verificationParams.getOriginatingURI()); 11725 } 11726 if (verificationParams.getReferrer() != null) { 11727 verification.putExtra(Intent.EXTRA_REFERRER, 11728 verificationParams.getReferrer()); 11729 } 11730 if (verificationParams.getOriginatingUid() >= 0) { 11731 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 11732 verificationParams.getOriginatingUid()); 11733 } 11734 if (verificationParams.getInstallerUid() >= 0) { 11735 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 11736 verificationParams.getInstallerUid()); 11737 } 11738 } 11739 11740 final PackageVerificationState verificationState = new PackageVerificationState( 11741 requiredUid, args); 11742 11743 mPendingVerification.append(verificationId, verificationState); 11744 11745 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 11746 receivers, verificationState); 11747 11748 /* 11749 * If any sufficient verifiers were listed in the package 11750 * manifest, attempt to ask them. 11751 */ 11752 if (sufficientVerifiers != null) { 11753 final int N = sufficientVerifiers.size(); 11754 if (N == 0) { 11755 Slog.i(TAG, "Additional verifiers required, but none installed."); 11756 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 11757 } else { 11758 for (int i = 0; i < N; i++) { 11759 final ComponentName verifierComponent = sufficientVerifiers.get(i); 11760 11761 final Intent sufficientIntent = new Intent(verification); 11762 sufficientIntent.setComponent(verifierComponent); 11763 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 11764 } 11765 } 11766 } 11767 11768 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 11769 mRequiredVerifierPackage, receivers); 11770 if (ret == PackageManager.INSTALL_SUCCEEDED 11771 && mRequiredVerifierPackage != null) { 11772 Trace.asyncTraceBegin( 11773 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 11774 /* 11775 * Send the intent to the required verification agent, 11776 * but only start the verification timeout after the 11777 * target BroadcastReceivers have run. 11778 */ 11779 verification.setComponent(requiredVerifierComponent); 11780 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 11781 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11782 new BroadcastReceiver() { 11783 @Override 11784 public void onReceive(Context context, Intent intent) { 11785 final Message msg = mHandler 11786 .obtainMessage(CHECK_PENDING_VERIFICATION); 11787 msg.arg1 = verificationId; 11788 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 11789 } 11790 }, null, 0, null, null); 11791 11792 /* 11793 * We don't want the copy to proceed until verification 11794 * succeeds, so null out this field. 11795 */ 11796 mArgs = null; 11797 } 11798 } else { 11799 /* 11800 * No package verification is enabled, so immediately start 11801 * the remote call to initiate copy using temporary file. 11802 */ 11803 ret = args.copyApk(mContainerService, true); 11804 } 11805 } 11806 11807 mRet = ret; 11808 } 11809 11810 @Override 11811 void handleReturnCode() { 11812 // If mArgs is null, then MCS couldn't be reached. When it 11813 // reconnects, it will try again to install. At that point, this 11814 // will succeed. 11815 if (mArgs != null) { 11816 processPendingInstall(mArgs, mRet); 11817 } 11818 } 11819 11820 @Override 11821 void handleServiceError() { 11822 mArgs = createInstallArgs(this); 11823 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11824 } 11825 11826 public boolean isForwardLocked() { 11827 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11828 } 11829 } 11830 11831 /** 11832 * Used during creation of InstallArgs 11833 * 11834 * @param installFlags package installation flags 11835 * @return true if should be installed on external storage 11836 */ 11837 private static boolean installOnExternalAsec(int installFlags) { 11838 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 11839 return false; 11840 } 11841 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 11842 return true; 11843 } 11844 return false; 11845 } 11846 11847 /** 11848 * Used during creation of InstallArgs 11849 * 11850 * @param installFlags package installation flags 11851 * @return true if should be installed as forward locked 11852 */ 11853 private static boolean installForwardLocked(int installFlags) { 11854 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11855 } 11856 11857 private InstallArgs createInstallArgs(InstallParams params) { 11858 if (params.move != null) { 11859 return new MoveInstallArgs(params); 11860 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 11861 return new AsecInstallArgs(params); 11862 } else { 11863 return new FileInstallArgs(params); 11864 } 11865 } 11866 11867 /** 11868 * Create args that describe an existing installed package. Typically used 11869 * when cleaning up old installs, or used as a move source. 11870 */ 11871 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 11872 String resourcePath, String[] instructionSets) { 11873 final boolean isInAsec; 11874 if (installOnExternalAsec(installFlags)) { 11875 /* Apps on SD card are always in ASEC containers. */ 11876 isInAsec = true; 11877 } else if (installForwardLocked(installFlags) 11878 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 11879 /* 11880 * Forward-locked apps are only in ASEC containers if they're the 11881 * new style 11882 */ 11883 isInAsec = true; 11884 } else { 11885 isInAsec = false; 11886 } 11887 11888 if (isInAsec) { 11889 return new AsecInstallArgs(codePath, instructionSets, 11890 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 11891 } else { 11892 return new FileInstallArgs(codePath, resourcePath, instructionSets); 11893 } 11894 } 11895 11896 static abstract class InstallArgs { 11897 /** @see InstallParams#origin */ 11898 final OriginInfo origin; 11899 /** @see InstallParams#move */ 11900 final MoveInfo move; 11901 11902 final IPackageInstallObserver2 observer; 11903 // Always refers to PackageManager flags only 11904 final int installFlags; 11905 final String installerPackageName; 11906 final String volumeUuid; 11907 final UserHandle user; 11908 final String abiOverride; 11909 final String[] installGrantPermissions; 11910 /** If non-null, drop an async trace when the install completes */ 11911 final String traceMethod; 11912 final int traceCookie; 11913 11914 // The list of instruction sets supported by this app. This is currently 11915 // only used during the rmdex() phase to clean up resources. We can get rid of this 11916 // if we move dex files under the common app path. 11917 /* nullable */ String[] instructionSets; 11918 11919 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11920 int installFlags, String installerPackageName, String volumeUuid, 11921 UserHandle user, String[] instructionSets, 11922 String abiOverride, String[] installGrantPermissions, 11923 String traceMethod, int traceCookie) { 11924 this.origin = origin; 11925 this.move = move; 11926 this.installFlags = installFlags; 11927 this.observer = observer; 11928 this.installerPackageName = installerPackageName; 11929 this.volumeUuid = volumeUuid; 11930 this.user = user; 11931 this.instructionSets = instructionSets; 11932 this.abiOverride = abiOverride; 11933 this.installGrantPermissions = installGrantPermissions; 11934 this.traceMethod = traceMethod; 11935 this.traceCookie = traceCookie; 11936 } 11937 11938 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 11939 abstract int doPreInstall(int status); 11940 11941 /** 11942 * Rename package into final resting place. All paths on the given 11943 * scanned package should be updated to reflect the rename. 11944 */ 11945 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 11946 abstract int doPostInstall(int status, int uid); 11947 11948 /** @see PackageSettingBase#codePathString */ 11949 abstract String getCodePath(); 11950 /** @see PackageSettingBase#resourcePathString */ 11951 abstract String getResourcePath(); 11952 11953 // Need installer lock especially for dex file removal. 11954 abstract void cleanUpResourcesLI(); 11955 abstract boolean doPostDeleteLI(boolean delete); 11956 11957 /** 11958 * Called before the source arguments are copied. This is used mostly 11959 * for MoveParams when it needs to read the source file to put it in the 11960 * destination. 11961 */ 11962 int doPreCopy() { 11963 return PackageManager.INSTALL_SUCCEEDED; 11964 } 11965 11966 /** 11967 * Called after the source arguments are copied. This is used mostly for 11968 * MoveParams when it needs to read the source file to put it in the 11969 * destination. 11970 * 11971 * @return 11972 */ 11973 int doPostCopy(int uid) { 11974 return PackageManager.INSTALL_SUCCEEDED; 11975 } 11976 11977 protected boolean isFwdLocked() { 11978 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11979 } 11980 11981 protected boolean isExternalAsec() { 11982 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11983 } 11984 11985 protected boolean isEphemeral() { 11986 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11987 } 11988 11989 UserHandle getUser() { 11990 return user; 11991 } 11992 } 11993 11994 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 11995 if (!allCodePaths.isEmpty()) { 11996 if (instructionSets == null) { 11997 throw new IllegalStateException("instructionSet == null"); 11998 } 11999 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 12000 for (String codePath : allCodePaths) { 12001 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 12002 try { 12003 mInstaller.rmdex(codePath, dexCodeInstructionSet); 12004 } catch (InstallerException ignored) { 12005 } 12006 } 12007 } 12008 } 12009 } 12010 12011 /** 12012 * Logic to handle installation of non-ASEC applications, including copying 12013 * and renaming logic. 12014 */ 12015 class FileInstallArgs extends InstallArgs { 12016 private File codeFile; 12017 private File resourceFile; 12018 12019 // Example topology: 12020 // /data/app/com.example/base.apk 12021 // /data/app/com.example/split_foo.apk 12022 // /data/app/com.example/lib/arm/libfoo.so 12023 // /data/app/com.example/lib/arm64/libfoo.so 12024 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 12025 12026 /** New install */ 12027 FileInstallArgs(InstallParams params) { 12028 super(params.origin, params.move, params.observer, params.installFlags, 12029 params.installerPackageName, params.volumeUuid, 12030 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12031 params.grantedRuntimePermissions, 12032 params.traceMethod, params.traceCookie); 12033 if (isFwdLocked()) { 12034 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 12035 } 12036 } 12037 12038 /** Existing install */ 12039 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 12040 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 12041 null, null, null, 0); 12042 this.codeFile = (codePath != null) ? new File(codePath) : null; 12043 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 12044 } 12045 12046 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12047 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 12048 try { 12049 return doCopyApk(imcs, temp); 12050 } finally { 12051 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12052 } 12053 } 12054 12055 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12056 if (origin.staged) { 12057 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 12058 codeFile = origin.file; 12059 resourceFile = origin.file; 12060 return PackageManager.INSTALL_SUCCEEDED; 12061 } 12062 12063 try { 12064 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12065 final File tempDir = 12066 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 12067 codeFile = tempDir; 12068 resourceFile = tempDir; 12069 } catch (IOException e) { 12070 Slog.w(TAG, "Failed to create copy file: " + e); 12071 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12072 } 12073 12074 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 12075 @Override 12076 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 12077 if (!FileUtils.isValidExtFilename(name)) { 12078 throw new IllegalArgumentException("Invalid filename: " + name); 12079 } 12080 try { 12081 final File file = new File(codeFile, name); 12082 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 12083 O_RDWR | O_CREAT, 0644); 12084 Os.chmod(file.getAbsolutePath(), 0644); 12085 return new ParcelFileDescriptor(fd); 12086 } catch (ErrnoException e) { 12087 throw new RemoteException("Failed to open: " + e.getMessage()); 12088 } 12089 } 12090 }; 12091 12092 int ret = PackageManager.INSTALL_SUCCEEDED; 12093 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 12094 if (ret != PackageManager.INSTALL_SUCCEEDED) { 12095 Slog.e(TAG, "Failed to copy package"); 12096 return ret; 12097 } 12098 12099 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 12100 NativeLibraryHelper.Handle handle = null; 12101 try { 12102 handle = NativeLibraryHelper.Handle.create(codeFile); 12103 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 12104 abiOverride); 12105 } catch (IOException e) { 12106 Slog.e(TAG, "Copying native libraries failed", e); 12107 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12108 } finally { 12109 IoUtils.closeQuietly(handle); 12110 } 12111 12112 return ret; 12113 } 12114 12115 int doPreInstall(int status) { 12116 if (status != PackageManager.INSTALL_SUCCEEDED) { 12117 cleanUp(); 12118 } 12119 return status; 12120 } 12121 12122 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12123 if (status != PackageManager.INSTALL_SUCCEEDED) { 12124 cleanUp(); 12125 return false; 12126 } 12127 12128 final File targetDir = codeFile.getParentFile(); 12129 final File beforeCodeFile = codeFile; 12130 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 12131 12132 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 12133 try { 12134 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 12135 } catch (ErrnoException e) { 12136 Slog.w(TAG, "Failed to rename", e); 12137 return false; 12138 } 12139 12140 if (!SELinux.restoreconRecursive(afterCodeFile)) { 12141 Slog.w(TAG, "Failed to restorecon"); 12142 return false; 12143 } 12144 12145 // Reflect the rename internally 12146 codeFile = afterCodeFile; 12147 resourceFile = afterCodeFile; 12148 12149 // Reflect the rename in scanned details 12150 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12151 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12152 afterCodeFile, pkg.baseCodePath)); 12153 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12154 afterCodeFile, pkg.splitCodePaths)); 12155 12156 // Reflect the rename in app info 12157 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12158 pkg.setApplicationInfoCodePath(pkg.codePath); 12159 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12160 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12161 pkg.setApplicationInfoResourcePath(pkg.codePath); 12162 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12163 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12164 12165 return true; 12166 } 12167 12168 int doPostInstall(int status, int uid) { 12169 if (status != PackageManager.INSTALL_SUCCEEDED) { 12170 cleanUp(); 12171 } 12172 return status; 12173 } 12174 12175 @Override 12176 String getCodePath() { 12177 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12178 } 12179 12180 @Override 12181 String getResourcePath() { 12182 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12183 } 12184 12185 private boolean cleanUp() { 12186 if (codeFile == null || !codeFile.exists()) { 12187 return false; 12188 } 12189 12190 removeCodePathLI(codeFile); 12191 12192 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 12193 resourceFile.delete(); 12194 } 12195 12196 return true; 12197 } 12198 12199 void cleanUpResourcesLI() { 12200 // Try enumerating all code paths before deleting 12201 List<String> allCodePaths = Collections.EMPTY_LIST; 12202 if (codeFile != null && codeFile.exists()) { 12203 try { 12204 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12205 allCodePaths = pkg.getAllCodePaths(); 12206 } catch (PackageParserException e) { 12207 // Ignored; we tried our best 12208 } 12209 } 12210 12211 cleanUp(); 12212 removeDexFiles(allCodePaths, instructionSets); 12213 } 12214 12215 boolean doPostDeleteLI(boolean delete) { 12216 // XXX err, shouldn't we respect the delete flag? 12217 cleanUpResourcesLI(); 12218 return true; 12219 } 12220 } 12221 12222 private boolean isAsecExternal(String cid) { 12223 final String asecPath = PackageHelper.getSdFilesystem(cid); 12224 return !asecPath.startsWith(mAsecInternalPath); 12225 } 12226 12227 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 12228 PackageManagerException { 12229 if (copyRet < 0) { 12230 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 12231 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 12232 throw new PackageManagerException(copyRet, message); 12233 } 12234 } 12235 } 12236 12237 /** 12238 * Extract the MountService "container ID" from the full code path of an 12239 * .apk. 12240 */ 12241 static String cidFromCodePath(String fullCodePath) { 12242 int eidx = fullCodePath.lastIndexOf("/"); 12243 String subStr1 = fullCodePath.substring(0, eidx); 12244 int sidx = subStr1.lastIndexOf("/"); 12245 return subStr1.substring(sidx+1, eidx); 12246 } 12247 12248 /** 12249 * Logic to handle installation of ASEC applications, including copying and 12250 * renaming logic. 12251 */ 12252 class AsecInstallArgs extends InstallArgs { 12253 static final String RES_FILE_NAME = "pkg.apk"; 12254 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 12255 12256 String cid; 12257 String packagePath; 12258 String resourcePath; 12259 12260 /** New install */ 12261 AsecInstallArgs(InstallParams params) { 12262 super(params.origin, params.move, params.observer, params.installFlags, 12263 params.installerPackageName, params.volumeUuid, 12264 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12265 params.grantedRuntimePermissions, 12266 params.traceMethod, params.traceCookie); 12267 } 12268 12269 /** Existing install */ 12270 AsecInstallArgs(String fullCodePath, String[] instructionSets, 12271 boolean isExternal, boolean isForwardLocked) { 12272 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 12273 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12274 instructionSets, null, null, null, 0); 12275 // Hackily pretend we're still looking at a full code path 12276 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 12277 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 12278 } 12279 12280 // Extract cid from fullCodePath 12281 int eidx = fullCodePath.lastIndexOf("/"); 12282 String subStr1 = fullCodePath.substring(0, eidx); 12283 int sidx = subStr1.lastIndexOf("/"); 12284 cid = subStr1.substring(sidx+1, eidx); 12285 setMountPath(subStr1); 12286 } 12287 12288 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 12289 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 12290 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12291 instructionSets, null, null, null, 0); 12292 this.cid = cid; 12293 setMountPath(PackageHelper.getSdDir(cid)); 12294 } 12295 12296 void createCopyFile() { 12297 cid = mInstallerService.allocateExternalStageCidLegacy(); 12298 } 12299 12300 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12301 if (origin.staged && origin.cid != null) { 12302 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 12303 cid = origin.cid; 12304 setMountPath(PackageHelper.getSdDir(cid)); 12305 return PackageManager.INSTALL_SUCCEEDED; 12306 } 12307 12308 if (temp) { 12309 createCopyFile(); 12310 } else { 12311 /* 12312 * Pre-emptively destroy the container since it's destroyed if 12313 * copying fails due to it existing anyway. 12314 */ 12315 PackageHelper.destroySdDir(cid); 12316 } 12317 12318 final String newMountPath = imcs.copyPackageToContainer( 12319 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 12320 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 12321 12322 if (newMountPath != null) { 12323 setMountPath(newMountPath); 12324 return PackageManager.INSTALL_SUCCEEDED; 12325 } else { 12326 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12327 } 12328 } 12329 12330 @Override 12331 String getCodePath() { 12332 return packagePath; 12333 } 12334 12335 @Override 12336 String getResourcePath() { 12337 return resourcePath; 12338 } 12339 12340 int doPreInstall(int status) { 12341 if (status != PackageManager.INSTALL_SUCCEEDED) { 12342 // Destroy container 12343 PackageHelper.destroySdDir(cid); 12344 } else { 12345 boolean mounted = PackageHelper.isContainerMounted(cid); 12346 if (!mounted) { 12347 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 12348 Process.SYSTEM_UID); 12349 if (newMountPath != null) { 12350 setMountPath(newMountPath); 12351 } else { 12352 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12353 } 12354 } 12355 } 12356 return status; 12357 } 12358 12359 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12360 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 12361 String newMountPath = null; 12362 if (PackageHelper.isContainerMounted(cid)) { 12363 // Unmount the container 12364 if (!PackageHelper.unMountSdDir(cid)) { 12365 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 12366 return false; 12367 } 12368 } 12369 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 12370 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 12371 " which might be stale. Will try to clean up."); 12372 // Clean up the stale container and proceed to recreate. 12373 if (!PackageHelper.destroySdDir(newCacheId)) { 12374 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 12375 return false; 12376 } 12377 // Successfully cleaned up stale container. Try to rename again. 12378 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 12379 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 12380 + " inspite of cleaning it up."); 12381 return false; 12382 } 12383 } 12384 if (!PackageHelper.isContainerMounted(newCacheId)) { 12385 Slog.w(TAG, "Mounting container " + newCacheId); 12386 newMountPath = PackageHelper.mountSdDir(newCacheId, 12387 getEncryptKey(), Process.SYSTEM_UID); 12388 } else { 12389 newMountPath = PackageHelper.getSdDir(newCacheId); 12390 } 12391 if (newMountPath == null) { 12392 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 12393 return false; 12394 } 12395 Log.i(TAG, "Succesfully renamed " + cid + 12396 " to " + newCacheId + 12397 " at new path: " + newMountPath); 12398 cid = newCacheId; 12399 12400 final File beforeCodeFile = new File(packagePath); 12401 setMountPath(newMountPath); 12402 final File afterCodeFile = new File(packagePath); 12403 12404 // Reflect the rename in scanned details 12405 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12406 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12407 afterCodeFile, pkg.baseCodePath)); 12408 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12409 afterCodeFile, pkg.splitCodePaths)); 12410 12411 // Reflect the rename in app info 12412 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12413 pkg.setApplicationInfoCodePath(pkg.codePath); 12414 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12415 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12416 pkg.setApplicationInfoResourcePath(pkg.codePath); 12417 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12418 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12419 12420 return true; 12421 } 12422 12423 private void setMountPath(String mountPath) { 12424 final File mountFile = new File(mountPath); 12425 12426 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 12427 if (monolithicFile.exists()) { 12428 packagePath = monolithicFile.getAbsolutePath(); 12429 if (isFwdLocked()) { 12430 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 12431 } else { 12432 resourcePath = packagePath; 12433 } 12434 } else { 12435 packagePath = mountFile.getAbsolutePath(); 12436 resourcePath = packagePath; 12437 } 12438 } 12439 12440 int doPostInstall(int status, int uid) { 12441 if (status != PackageManager.INSTALL_SUCCEEDED) { 12442 cleanUp(); 12443 } else { 12444 final int groupOwner; 12445 final String protectedFile; 12446 if (isFwdLocked()) { 12447 groupOwner = UserHandle.getSharedAppGid(uid); 12448 protectedFile = RES_FILE_NAME; 12449 } else { 12450 groupOwner = -1; 12451 protectedFile = null; 12452 } 12453 12454 if (uid < Process.FIRST_APPLICATION_UID 12455 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 12456 Slog.e(TAG, "Failed to finalize " + cid); 12457 PackageHelper.destroySdDir(cid); 12458 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12459 } 12460 12461 boolean mounted = PackageHelper.isContainerMounted(cid); 12462 if (!mounted) { 12463 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 12464 } 12465 } 12466 return status; 12467 } 12468 12469 private void cleanUp() { 12470 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 12471 12472 // Destroy secure container 12473 PackageHelper.destroySdDir(cid); 12474 } 12475 12476 private List<String> getAllCodePaths() { 12477 final File codeFile = new File(getCodePath()); 12478 if (codeFile != null && codeFile.exists()) { 12479 try { 12480 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12481 return pkg.getAllCodePaths(); 12482 } catch (PackageParserException e) { 12483 // Ignored; we tried our best 12484 } 12485 } 12486 return Collections.EMPTY_LIST; 12487 } 12488 12489 void cleanUpResourcesLI() { 12490 // Enumerate all code paths before deleting 12491 cleanUpResourcesLI(getAllCodePaths()); 12492 } 12493 12494 private void cleanUpResourcesLI(List<String> allCodePaths) { 12495 cleanUp(); 12496 removeDexFiles(allCodePaths, instructionSets); 12497 } 12498 12499 String getPackageName() { 12500 return getAsecPackageName(cid); 12501 } 12502 12503 boolean doPostDeleteLI(boolean delete) { 12504 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 12505 final List<String> allCodePaths = getAllCodePaths(); 12506 boolean mounted = PackageHelper.isContainerMounted(cid); 12507 if (mounted) { 12508 // Unmount first 12509 if (PackageHelper.unMountSdDir(cid)) { 12510 mounted = false; 12511 } 12512 } 12513 if (!mounted && delete) { 12514 cleanUpResourcesLI(allCodePaths); 12515 } 12516 return !mounted; 12517 } 12518 12519 @Override 12520 int doPreCopy() { 12521 if (isFwdLocked()) { 12522 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 12523 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 12524 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12525 } 12526 } 12527 12528 return PackageManager.INSTALL_SUCCEEDED; 12529 } 12530 12531 @Override 12532 int doPostCopy(int uid) { 12533 if (isFwdLocked()) { 12534 if (uid < Process.FIRST_APPLICATION_UID 12535 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 12536 RES_FILE_NAME)) { 12537 Slog.e(TAG, "Failed to finalize " + cid); 12538 PackageHelper.destroySdDir(cid); 12539 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12540 } 12541 } 12542 12543 return PackageManager.INSTALL_SUCCEEDED; 12544 } 12545 } 12546 12547 /** 12548 * Logic to handle movement of existing installed applications. 12549 */ 12550 class MoveInstallArgs extends InstallArgs { 12551 private File codeFile; 12552 private File resourceFile; 12553 12554 /** New install */ 12555 MoveInstallArgs(InstallParams params) { 12556 super(params.origin, params.move, params.observer, params.installFlags, 12557 params.installerPackageName, params.volumeUuid, 12558 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12559 params.grantedRuntimePermissions, 12560 params.traceMethod, params.traceCookie); 12561 } 12562 12563 int copyApk(IMediaContainerService imcs, boolean temp) { 12564 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 12565 + move.fromUuid + " to " + move.toUuid); 12566 synchronized (mInstaller) { 12567 try { 12568 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 12569 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 12570 } catch (InstallerException e) { 12571 Slog.w(TAG, "Failed to move app", e); 12572 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12573 } 12574 } 12575 12576 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 12577 resourceFile = codeFile; 12578 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 12579 12580 return PackageManager.INSTALL_SUCCEEDED; 12581 } 12582 12583 int doPreInstall(int status) { 12584 if (status != PackageManager.INSTALL_SUCCEEDED) { 12585 cleanUp(move.toUuid); 12586 } 12587 return status; 12588 } 12589 12590 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12591 if (status != PackageManager.INSTALL_SUCCEEDED) { 12592 cleanUp(move.toUuid); 12593 return false; 12594 } 12595 12596 // Reflect the move in app info 12597 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12598 pkg.setApplicationInfoCodePath(pkg.codePath); 12599 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12600 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12601 pkg.setApplicationInfoResourcePath(pkg.codePath); 12602 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12603 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12604 12605 return true; 12606 } 12607 12608 int doPostInstall(int status, int uid) { 12609 if (status == PackageManager.INSTALL_SUCCEEDED) { 12610 cleanUp(move.fromUuid); 12611 } else { 12612 cleanUp(move.toUuid); 12613 } 12614 return status; 12615 } 12616 12617 @Override 12618 String getCodePath() { 12619 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12620 } 12621 12622 @Override 12623 String getResourcePath() { 12624 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12625 } 12626 12627 private boolean cleanUp(String volumeUuid) { 12628 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 12629 move.dataAppName); 12630 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 12631 synchronized (mInstallLock) { 12632 // Clean up both app data and code 12633 removeDataDirsLI(volumeUuid, move.packageName); 12634 removeCodePathLI(codeFile); 12635 } 12636 return true; 12637 } 12638 12639 void cleanUpResourcesLI() { 12640 throw new UnsupportedOperationException(); 12641 } 12642 12643 boolean doPostDeleteLI(boolean delete) { 12644 throw new UnsupportedOperationException(); 12645 } 12646 } 12647 12648 static String getAsecPackageName(String packageCid) { 12649 int idx = packageCid.lastIndexOf("-"); 12650 if (idx == -1) { 12651 return packageCid; 12652 } 12653 return packageCid.substring(0, idx); 12654 } 12655 12656 // Utility method used to create code paths based on package name and available index. 12657 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 12658 String idxStr = ""; 12659 int idx = 1; 12660 // Fall back to default value of idx=1 if prefix is not 12661 // part of oldCodePath 12662 if (oldCodePath != null) { 12663 String subStr = oldCodePath; 12664 // Drop the suffix right away 12665 if (suffix != null && subStr.endsWith(suffix)) { 12666 subStr = subStr.substring(0, subStr.length() - suffix.length()); 12667 } 12668 // If oldCodePath already contains prefix find out the 12669 // ending index to either increment or decrement. 12670 int sidx = subStr.lastIndexOf(prefix); 12671 if (sidx != -1) { 12672 subStr = subStr.substring(sidx + prefix.length()); 12673 if (subStr != null) { 12674 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 12675 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 12676 } 12677 try { 12678 idx = Integer.parseInt(subStr); 12679 if (idx <= 1) { 12680 idx++; 12681 } else { 12682 idx--; 12683 } 12684 } catch(NumberFormatException e) { 12685 } 12686 } 12687 } 12688 } 12689 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 12690 return prefix + idxStr; 12691 } 12692 12693 private File getNextCodePath(File targetDir, String packageName) { 12694 int suffix = 1; 12695 File result; 12696 do { 12697 result = new File(targetDir, packageName + "-" + suffix); 12698 suffix++; 12699 } while (result.exists()); 12700 return result; 12701 } 12702 12703 // Utility method that returns the relative package path with respect 12704 // to the installation directory. Like say for /data/data/com.test-1.apk 12705 // string com.test-1 is returned. 12706 static String deriveCodePathName(String codePath) { 12707 if (codePath == null) { 12708 return null; 12709 } 12710 final File codeFile = new File(codePath); 12711 final String name = codeFile.getName(); 12712 if (codeFile.isDirectory()) { 12713 return name; 12714 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 12715 final int lastDot = name.lastIndexOf('.'); 12716 return name.substring(0, lastDot); 12717 } else { 12718 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 12719 return null; 12720 } 12721 } 12722 12723 static class PackageInstalledInfo { 12724 String name; 12725 int uid; 12726 // The set of users that originally had this package installed. 12727 int[] origUsers; 12728 // The set of users that now have this package installed. 12729 int[] newUsers; 12730 PackageParser.Package pkg; 12731 int returnCode; 12732 String returnMsg; 12733 PackageRemovedInfo removedInfo; 12734 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 12735 12736 public void setError(int code, String msg) { 12737 setReturnCode(code); 12738 setReturnMessage(msg); 12739 Slog.w(TAG, msg); 12740 } 12741 12742 public void setError(String msg, PackageParserException e) { 12743 setReturnCode(e.error); 12744 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 12745 Slog.w(TAG, msg, e); 12746 } 12747 12748 public void setError(String msg, PackageManagerException e) { 12749 returnCode = e.error; 12750 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 12751 Slog.w(TAG, msg, e); 12752 } 12753 12754 public void setReturnCode(int returnCode) { 12755 this.returnCode = returnCode; 12756 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 12757 for (int i = 0; i < childCount; i++) { 12758 addedChildPackages.valueAt(i).returnCode = returnCode; 12759 } 12760 } 12761 12762 private void setReturnMessage(String returnMsg) { 12763 this.returnMsg = returnMsg; 12764 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 12765 for (int i = 0; i < childCount; i++) { 12766 addedChildPackages.valueAt(i).returnMsg = returnMsg; 12767 } 12768 } 12769 12770 // In some error cases we want to convey more info back to the observer 12771 String origPackage; 12772 String origPermission; 12773 } 12774 12775 /* 12776 * Install a non-existing package. 12777 */ 12778 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12779 UserHandle user, String installerPackageName, String volumeUuid, 12780 PackageInstalledInfo res) { 12781 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 12782 12783 // Remember this for later, in case we need to rollback this install 12784 String pkgName = pkg.packageName; 12785 12786 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 12787 12788 synchronized(mPackages) { 12789 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 12790 // A package with the same name is already installed, though 12791 // it has been renamed to an older name. The package we 12792 // are trying to install should be installed as an update to 12793 // the existing one, but that has not been requested, so bail. 12794 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12795 + " without first uninstalling package running as " 12796 + mSettings.mRenamedPackages.get(pkgName)); 12797 return; 12798 } 12799 if (mPackages.containsKey(pkgName)) { 12800 // Don't allow installation over an existing package with the same name. 12801 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12802 + " without first uninstalling."); 12803 return; 12804 } 12805 } 12806 12807 try { 12808 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 12809 System.currentTimeMillis(), user); 12810 12811 updateSettingsLI(newPackage, installerPackageName, null, res, user); 12812 12813 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12814 prepareAppDataAfterInstall(newPackage); 12815 12816 } else { 12817 // Remove package from internal structures, but keep around any 12818 // data that might have already existed 12819 deletePackageLI(pkgName, UserHandle.ALL, false, null, 12820 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 12821 } 12822 } catch (PackageManagerException e) { 12823 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12824 } 12825 12826 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12827 } 12828 12829 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 12830 // Can't rotate keys during boot or if sharedUser. 12831 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 12832 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 12833 return false; 12834 } 12835 // app is using upgradeKeySets; make sure all are valid 12836 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12837 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 12838 for (int i = 0; i < upgradeKeySets.length; i++) { 12839 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 12840 Slog.wtf(TAG, "Package " 12841 + (oldPs.name != null ? oldPs.name : "<null>") 12842 + " contains upgrade-key-set reference to unknown key-set: " 12843 + upgradeKeySets[i] 12844 + " reverting to signatures check."); 12845 return false; 12846 } 12847 } 12848 return true; 12849 } 12850 12851 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 12852 // Upgrade keysets are being used. Determine if new package has a superset of the 12853 // required keys. 12854 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 12855 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12856 for (int i = 0; i < upgradeKeySets.length; i++) { 12857 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 12858 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 12859 return true; 12860 } 12861 } 12862 return false; 12863 } 12864 12865 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12866 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 12867 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 12868 12869 final PackageParser.Package oldPackage; 12870 final String pkgName = pkg.packageName; 12871 final int[] allUsers; 12872 12873 // First find the old package info and check signatures 12874 synchronized(mPackages) { 12875 oldPackage = mPackages.get(pkgName); 12876 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 12877 if (isEphemeral && !oldIsEphemeral) { 12878 // can't downgrade from full to ephemeral 12879 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 12880 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 12881 return; 12882 } 12883 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 12884 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12885 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12886 if (!checkUpgradeKeySetLP(ps, pkg)) { 12887 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12888 "New package not signed by keys specified by upgrade-keysets: " 12889 + pkgName); 12890 return; 12891 } 12892 } else { 12893 // default to original signature matching 12894 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 12895 != PackageManager.SIGNATURE_MATCH) { 12896 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12897 "New package has a different signature: " + pkgName); 12898 return; 12899 } 12900 } 12901 12902 // In case of rollback, remember per-user/profile install state 12903 allUsers = sUserManager.getUserIds(); 12904 } 12905 12906 // Update what is removed 12907 res.removedInfo = new PackageRemovedInfo(); 12908 res.removedInfo.uid = oldPackage.applicationInfo.uid; 12909 res.removedInfo.removedPackage = oldPackage.packageName; 12910 res.removedInfo.isUpdate = true; 12911 final int childCount = (oldPackage.childPackages != null) 12912 ? oldPackage.childPackages.size() : 0; 12913 for (int i = 0; i < childCount; i++) { 12914 boolean childPackageUpdated = false; 12915 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 12916 if (res.addedChildPackages != null) { 12917 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 12918 if (childRes != null) { 12919 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 12920 childRes.removedInfo.removedPackage = childPkg.packageName; 12921 childRes.removedInfo.isUpdate = true; 12922 childPackageUpdated = true; 12923 } 12924 } 12925 if (!childPackageUpdated) { 12926 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 12927 childRemovedRes.removedPackage = childPkg.packageName; 12928 childRemovedRes.isUpdate = false; 12929 childRemovedRes.dataRemoved = true; 12930 synchronized (mPackages) { 12931 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 12932 if (childPs != null) { 12933 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 12934 } 12935 } 12936 if (res.removedInfo.removedChildPackages == null) { 12937 res.removedInfo.removedChildPackages = new ArrayMap<>(); 12938 } 12939 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 12940 } 12941 } 12942 12943 boolean sysPkg = (isSystemApp(oldPackage)); 12944 if (sysPkg) { 12945 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12946 user, allUsers, installerPackageName, res); 12947 } else { 12948 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12949 user, allUsers, installerPackageName, res); 12950 } 12951 } 12952 12953 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 12954 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12955 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 12956 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 12957 + deletedPackage); 12958 12959 String pkgName = deletedPackage.packageName; 12960 boolean deletedPkg = true; 12961 boolean addedPkg = false; 12962 12963 final long origUpdateTime = (pkg.mExtras != null) 12964 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 12965 12966 // First delete the existing package while retaining the data directory 12967 if (!deletePackageLI(pkgName, null, true, allUsers, PackageManager.DELETE_KEEP_DATA, 12968 res.removedInfo, true, pkg)) { 12969 // If the existing package wasn't successfully deleted 12970 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 12971 deletedPkg = false; 12972 } else { 12973 // Successfully deleted the old package; proceed with replace. 12974 12975 // If deleted package lived in a container, give users a chance to 12976 // relinquish resources before killing. 12977 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 12978 if (DEBUG_INSTALL) { 12979 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 12980 } 12981 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 12982 final ArrayList<String> pkgList = new ArrayList<String>(1); 12983 pkgList.add(deletedPackage.applicationInfo.packageName); 12984 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 12985 } 12986 12987 deleteCodeCacheDirsLI(pkg); 12988 12989 try { 12990 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 12991 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 12992 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 12993 prepareAppDataAfterInstall(newPackage); 12994 addedPkg = true; 12995 } catch (PackageManagerException e) { 12996 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12997 } 12998 } 12999 13000 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13001 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 13002 13003 // Revert all internal state mutations and added folders for the failed install 13004 if (addedPkg) { 13005 deletePackageLI(pkgName, null, true, allUsers, PackageManager.DELETE_KEEP_DATA, 13006 res.removedInfo, true, null); 13007 } 13008 13009 // Restore the old package 13010 if (deletedPkg) { 13011 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 13012 File restoreFile = new File(deletedPackage.codePath); 13013 // Parse old package 13014 boolean oldExternal = isExternal(deletedPackage); 13015 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 13016 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 13017 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 13018 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 13019 try { 13020 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 13021 null); 13022 } catch (PackageManagerException e) { 13023 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 13024 + e.getMessage()); 13025 return; 13026 } 13027 13028 synchronized (mPackages) { 13029 // Ensure the installer package name up to date 13030 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13031 13032 // Update permissions for restored package 13033 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13034 13035 mSettings.writeLPr(); 13036 } 13037 13038 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 13039 } 13040 } else { 13041 synchronized (mPackages) { 13042 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 13043 if (ps != null) { 13044 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 13045 if (res.removedInfo.removedChildPackages != null) { 13046 final int childCount = res.removedInfo.removedChildPackages.size(); 13047 // Iterate in reverse as we may modify the collection 13048 for (int i = childCount - 1; i >= 0; i--) { 13049 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 13050 if (res.addedChildPackages.containsKey(childPackageName)) { 13051 res.removedInfo.removedChildPackages.removeAt(i); 13052 } else { 13053 PackageRemovedInfo childInfo = res.removedInfo 13054 .removedChildPackages.valueAt(i); 13055 childInfo.removedForAllUsers = mPackages.get( 13056 childInfo.removedPackage) == null; 13057 } 13058 } 13059 } 13060 } 13061 } 13062 } 13063 } 13064 13065 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 13066 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13067 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13068 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 13069 + ", old=" + deletedPackage); 13070 13071 final boolean disabledSystem; 13072 13073 // Set the system/privileged flags as needed 13074 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 13075 if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 13076 != 0) { 13077 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13078 } 13079 13080 // Kill package processes including services, providers, etc. 13081 killPackage(deletedPackage, "replace sys pkg"); 13082 13083 // Remove existing system package 13084 removePackageLI(deletedPackage, true); 13085 13086 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 13087 if (!disabledSystem) { 13088 // We didn't need to disable the .apk as a current system package, 13089 // which means we are replacing another update that is already 13090 // installed. We need to make sure to delete the older one's .apk. 13091 res.removedInfo.args = createInstallArgsForExisting(0, 13092 deletedPackage.applicationInfo.getCodePath(), 13093 deletedPackage.applicationInfo.getResourcePath(), 13094 getAppDexInstructionSets(deletedPackage.applicationInfo)); 13095 } else { 13096 res.removedInfo.args = null; 13097 } 13098 13099 // Successfully disabled the old package. Now proceed with re-installation 13100 deleteCodeCacheDirsLI(pkg); 13101 13102 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13103 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 13104 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 13105 13106 PackageParser.Package newPackage = null; 13107 try { 13108 // Add the package to the internal data structures 13109 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 13110 13111 // Set the update and install times 13112 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 13113 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 13114 System.currentTimeMillis()); 13115 13116 // Check for shared user id changes 13117 String invalidPackageName = getParentOrChildPackageChangedSharedUser( 13118 deletedPackage, newPackage); 13119 if (invalidPackageName != null) { 13120 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13121 "Forbidding shared user change from " + deletedPkgSetting.sharedUser 13122 + " to " + invalidPackageName); 13123 } 13124 13125 // Update the package dynamic state if succeeded 13126 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13127 // Now that the install succeeded make sure we remove data 13128 // directories for any child package the update removed. 13129 final int deletedChildCount = (deletedPackage.childPackages != null) 13130 ? deletedPackage.childPackages.size() : 0; 13131 final int newChildCount = (newPackage.childPackages != null) 13132 ? newPackage.childPackages.size() : 0; 13133 for (int i = 0; i < deletedChildCount; i++) { 13134 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 13135 boolean childPackageDeleted = true; 13136 for (int j = 0; j < newChildCount; j++) { 13137 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 13138 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 13139 childPackageDeleted = false; 13140 break; 13141 } 13142 } 13143 if (childPackageDeleted) { 13144 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 13145 deletedChildPkg.packageName); 13146 if (ps != null && res.removedInfo.removedChildPackages != null) { 13147 PackageRemovedInfo removedChildRes = res.removedInfo 13148 .removedChildPackages.get(deletedChildPkg.packageName); 13149 removePackageDataLI(ps, allUsers, removedChildRes, 0, false); 13150 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 13151 } 13152 } 13153 } 13154 13155 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13156 prepareAppDataAfterInstall(newPackage); 13157 } 13158 } catch (PackageManagerException e) { 13159 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 13160 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13161 } 13162 13163 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13164 // Re installation failed. Restore old information 13165 // Remove new pkg information 13166 if (newPackage != null) { 13167 removeInstalledPackageLI(newPackage, true); 13168 } 13169 // Add back the old system package 13170 try { 13171 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 13172 } catch (PackageManagerException e) { 13173 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 13174 } 13175 13176 synchronized (mPackages) { 13177 if (disabledSystem) { 13178 enableSystemPackageLPw(deletedPackage); 13179 } 13180 13181 // Ensure the installer package name up to date 13182 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13183 13184 // Update permissions for restored package 13185 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13186 13187 mSettings.writeLPr(); 13188 } 13189 13190 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 13191 + " after failed upgrade"); 13192 } 13193 } 13194 13195 /** 13196 * Checks whether the parent or any of the child packages have a change shared 13197 * user. For a package to be a valid update the shred users of the parent and 13198 * the children should match. We may later support changing child shared users. 13199 * @param oldPkg The updated package. 13200 * @param newPkg The update package. 13201 * @return The shared user that change between the versions. 13202 */ 13203 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 13204 PackageParser.Package newPkg) { 13205 // Check parent shared user 13206 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 13207 return newPkg.packageName; 13208 } 13209 // Check child shared users 13210 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13211 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 13212 for (int i = 0; i < newChildCount; i++) { 13213 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 13214 // If this child was present, did it have the same shared user? 13215 for (int j = 0; j < oldChildCount; j++) { 13216 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 13217 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 13218 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 13219 return newChildPkg.packageName; 13220 } 13221 } 13222 } 13223 return null; 13224 } 13225 13226 private void removeNativeBinariesLI(PackageParser.Package pkg) { 13227 // Remove the lib path for the parent package 13228 PackageSetting ps = (PackageSetting) pkg.mExtras; 13229 if (ps != null) { 13230 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 13231 } 13232 // Remove the lib path for the child packages 13233 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13234 for (int i = 0; i < childCount; i++) { 13235 ps = (PackageSetting) pkg.childPackages.get(i).mExtras; 13236 if (ps != null) { 13237 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 13238 } 13239 } 13240 } 13241 13242 private void enableSystemPackageLPw(PackageParser.Package pkg) { 13243 // Enable the parent package 13244 mSettings.enableSystemPackageLPw(pkg.packageName); 13245 // Enable the child packages 13246 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13247 for (int i = 0; i < childCount; i++) { 13248 PackageParser.Package childPkg = pkg.childPackages.get(i); 13249 mSettings.enableSystemPackageLPw(childPkg.packageName); 13250 } 13251 } 13252 13253 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 13254 PackageParser.Package newPkg) { 13255 // Disable the parent package (parent always replaced) 13256 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 13257 // Disable the child packages 13258 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13259 for (int i = 0; i < childCount; i++) { 13260 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 13261 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 13262 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 13263 } 13264 return disabled; 13265 } 13266 13267 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 13268 String installerPackageName) { 13269 // Enable the parent package 13270 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 13271 // Enable the child packages 13272 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13273 for (int i = 0; i < childCount; i++) { 13274 PackageParser.Package childPkg = pkg.childPackages.get(i); 13275 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 13276 } 13277 } 13278 13279 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 13280 // Collect all used permissions in the UID 13281 ArraySet<String> usedPermissions = new ArraySet<>(); 13282 final int packageCount = su.packages.size(); 13283 for (int i = 0; i < packageCount; i++) { 13284 PackageSetting ps = su.packages.valueAt(i); 13285 if (ps.pkg == null) { 13286 continue; 13287 } 13288 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 13289 for (int j = 0; j < requestedPermCount; j++) { 13290 String permission = ps.pkg.requestedPermissions.get(j); 13291 BasePermission bp = mSettings.mPermissions.get(permission); 13292 if (bp != null) { 13293 usedPermissions.add(permission); 13294 } 13295 } 13296 } 13297 13298 PermissionsState permissionsState = su.getPermissionsState(); 13299 // Prune install permissions 13300 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 13301 final int installPermCount = installPermStates.size(); 13302 for (int i = installPermCount - 1; i >= 0; i--) { 13303 PermissionState permissionState = installPermStates.get(i); 13304 if (!usedPermissions.contains(permissionState.getName())) { 13305 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 13306 if (bp != null) { 13307 permissionsState.revokeInstallPermission(bp); 13308 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 13309 PackageManager.MASK_PERMISSION_FLAGS, 0); 13310 } 13311 } 13312 } 13313 13314 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 13315 13316 // Prune runtime permissions 13317 for (int userId : allUserIds) { 13318 List<PermissionState> runtimePermStates = permissionsState 13319 .getRuntimePermissionStates(userId); 13320 final int runtimePermCount = runtimePermStates.size(); 13321 for (int i = runtimePermCount - 1; i >= 0; i--) { 13322 PermissionState permissionState = runtimePermStates.get(i); 13323 if (!usedPermissions.contains(permissionState.getName())) { 13324 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 13325 if (bp != null) { 13326 permissionsState.revokeRuntimePermission(bp, userId); 13327 permissionsState.updatePermissionFlags(bp, userId, 13328 PackageManager.MASK_PERMISSION_FLAGS, 0); 13329 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 13330 runtimePermissionChangedUserIds, userId); 13331 } 13332 } 13333 } 13334 } 13335 13336 return runtimePermissionChangedUserIds; 13337 } 13338 13339 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 13340 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 13341 // Update the parent package setting 13342 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 13343 res, user); 13344 // Update the child packages setting 13345 final int childCount = (newPackage.childPackages != null) 13346 ? newPackage.childPackages.size() : 0; 13347 for (int i = 0; i < childCount; i++) { 13348 PackageParser.Package childPackage = newPackage.childPackages.get(i); 13349 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 13350 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 13351 childRes.origUsers, childRes, user); 13352 } 13353 } 13354 13355 private void updateSettingsInternalLI(PackageParser.Package newPackage, 13356 String installerPackageName, int[] allUsers, int[] installedForUsers, 13357 PackageInstalledInfo res, UserHandle user) { 13358 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 13359 13360 String pkgName = newPackage.packageName; 13361 synchronized (mPackages) { 13362 //write settings. the installStatus will be incomplete at this stage. 13363 //note that the new package setting would have already been 13364 //added to mPackages. It hasn't been persisted yet. 13365 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 13366 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 13367 mSettings.writeLPr(); 13368 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13369 } 13370 13371 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 13372 synchronized (mPackages) { 13373 updatePermissionsLPw(newPackage.packageName, newPackage, 13374 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 13375 ? UPDATE_PERMISSIONS_ALL : 0)); 13376 // For system-bundled packages, we assume that installing an upgraded version 13377 // of the package implies that the user actually wants to run that new code, 13378 // so we enable the package. 13379 PackageSetting ps = mSettings.mPackages.get(pkgName); 13380 final int userId = user.getIdentifier(); 13381 if (ps != null) { 13382 if (isSystemApp(newPackage)) { 13383 if (DEBUG_INSTALL) { 13384 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 13385 } 13386 // Enable system package for requested users 13387 if (res.origUsers != null) { 13388 for (int origUserId : res.origUsers) { 13389 if (userId == UserHandle.USER_ALL || userId == origUserId) { 13390 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 13391 origUserId, installerPackageName); 13392 } 13393 } 13394 } 13395 // Also convey the prior install/uninstall state 13396 if (allUsers != null && installedForUsers != null) { 13397 for (int currentUserId : allUsers) { 13398 final boolean installed = ArrayUtils.contains( 13399 installedForUsers, currentUserId); 13400 if (DEBUG_INSTALL) { 13401 Slog.d(TAG, " user " + currentUserId + " => " + installed); 13402 } 13403 ps.setInstalled(installed, currentUserId); 13404 } 13405 // these install state changes will be persisted in the 13406 // upcoming call to mSettings.writeLPr(). 13407 } 13408 } 13409 // It's implied that when a user requests installation, they want the app to be 13410 // installed and enabled. 13411 if (userId != UserHandle.USER_ALL) { 13412 ps.setInstalled(true, userId); 13413 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 13414 } 13415 } 13416 res.name = pkgName; 13417 res.uid = newPackage.applicationInfo.uid; 13418 res.pkg = newPackage; 13419 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 13420 mSettings.setInstallerPackageName(pkgName, installerPackageName); 13421 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13422 //to update install status 13423 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 13424 mSettings.writeLPr(); 13425 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13426 } 13427 13428 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13429 } 13430 13431 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 13432 try { 13433 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 13434 installPackageLI(args, res); 13435 } finally { 13436 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13437 } 13438 } 13439 13440 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 13441 final int installFlags = args.installFlags; 13442 final String installerPackageName = args.installerPackageName; 13443 final String volumeUuid = args.volumeUuid; 13444 final File tmpPackageFile = new File(args.getCodePath()); 13445 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 13446 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 13447 || (args.volumeUuid != null)); 13448 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 13449 boolean replace = false; 13450 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 13451 if (args.move != null) { 13452 // moving a complete application; perform an initial scan on the new install location 13453 scanFlags |= SCAN_INITIAL; 13454 } 13455 13456 // Result object to be returned 13457 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13458 13459 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 13460 13461 // Sanity check 13462 if (ephemeral && (forwardLocked || onExternal)) { 13463 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 13464 + " external=" + onExternal); 13465 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13466 return; 13467 } 13468 13469 // Retrieve PackageSettings and parse package 13470 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 13471 | PackageParser.PARSE_ENFORCE_CODE 13472 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 13473 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 13474 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 13475 PackageParser pp = new PackageParser(); 13476 pp.setSeparateProcesses(mSeparateProcesses); 13477 pp.setDisplayMetrics(mMetrics); 13478 13479 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 13480 final PackageParser.Package pkg; 13481 try { 13482 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 13483 } catch (PackageParserException e) { 13484 res.setError("Failed parse during installPackageLI", e); 13485 return; 13486 } finally { 13487 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13488 } 13489 13490 // If we are installing a clustered package add results for the children 13491 if (pkg.childPackages != null) { 13492 synchronized (mPackages) { 13493 final int childCount = pkg.childPackages.size(); 13494 for (int i = 0; i < childCount; i++) { 13495 PackageParser.Package childPkg = pkg.childPackages.get(i); 13496 PackageInstalledInfo childRes = new PackageInstalledInfo(); 13497 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13498 childRes.pkg = childPkg; 13499 childRes.name = childPkg.packageName; 13500 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13501 if (childPs != null) { 13502 childRes.origUsers = childPs.queryInstalledUsers( 13503 sUserManager.getUserIds(), true); 13504 } 13505 if ((mPackages.containsKey(childPkg.packageName))) { 13506 childRes.removedInfo = new PackageRemovedInfo(); 13507 childRes.removedInfo.removedPackage = childPkg.packageName; 13508 } 13509 if (res.addedChildPackages == null) { 13510 res.addedChildPackages = new ArrayMap<>(); 13511 } 13512 res.addedChildPackages.put(childPkg.packageName, childRes); 13513 } 13514 } 13515 } 13516 13517 // If package doesn't declare API override, mark that we have an install 13518 // time CPU ABI override. 13519 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 13520 pkg.cpuAbiOverride = args.abiOverride; 13521 } 13522 13523 String pkgName = res.name = pkg.packageName; 13524 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 13525 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 13526 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 13527 return; 13528 } 13529 } 13530 13531 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 13532 try { 13533 PackageParser.collectCertificates(pkg, parseFlags); 13534 } catch (PackageParserException e) { 13535 res.setError("Failed collect during installPackageLI", e); 13536 return; 13537 } finally { 13538 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13539 } 13540 13541 // Get rid of all references to package scan path via parser. 13542 pp = null; 13543 String oldCodePath = null; 13544 boolean systemApp = false; 13545 synchronized (mPackages) { 13546 // Check if installing already existing package 13547 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 13548 String oldName = mSettings.mRenamedPackages.get(pkgName); 13549 if (pkg.mOriginalPackages != null 13550 && pkg.mOriginalPackages.contains(oldName) 13551 && mPackages.containsKey(oldName)) { 13552 // This package is derived from an original package, 13553 // and this device has been updating from that original 13554 // name. We must continue using the original name, so 13555 // rename the new package here. 13556 pkg.setPackageName(oldName); 13557 pkgName = pkg.packageName; 13558 replace = true; 13559 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 13560 + oldName + " pkgName=" + pkgName); 13561 } else if (mPackages.containsKey(pkgName)) { 13562 // This package, under its official name, already exists 13563 // on the device; we should replace it. 13564 replace = true; 13565 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 13566 } 13567 13568 // Child packages are installed through the parent package 13569 if (pkg.parentPackage != null) { 13570 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 13571 "Package " + pkg.packageName + " is child of package " 13572 + pkg.parentPackage.parentPackage + ". Child packages " 13573 + "can be updated only through the parent package."); 13574 return; 13575 } 13576 13577 if (replace) { 13578 // Prevent apps opting out from runtime permissions 13579 PackageParser.Package oldPackage = mPackages.get(pkgName); 13580 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 13581 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 13582 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 13583 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 13584 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 13585 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 13586 + " doesn't support runtime permissions but the old" 13587 + " target SDK " + oldTargetSdk + " does."); 13588 return; 13589 } 13590 13591 // Prevent installing of child packages 13592 if (oldPackage.parentPackage != null) { 13593 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 13594 "Package " + pkg.packageName + " is child of package " 13595 + oldPackage.parentPackage + ". Child packages " 13596 + "can be updated only through the parent package."); 13597 return; 13598 } 13599 } 13600 } 13601 13602 PackageSetting ps = mSettings.mPackages.get(pkgName); 13603 if (ps != null) { 13604 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 13605 13606 // Quick sanity check that we're signed correctly if updating; 13607 // we'll check this again later when scanning, but we want to 13608 // bail early here before tripping over redefined permissions. 13609 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13610 if (!checkUpgradeKeySetLP(ps, pkg)) { 13611 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 13612 + pkg.packageName + " upgrade keys do not match the " 13613 + "previously installed version"); 13614 return; 13615 } 13616 } else { 13617 try { 13618 verifySignaturesLP(ps, pkg); 13619 } catch (PackageManagerException e) { 13620 res.setError(e.error, e.getMessage()); 13621 return; 13622 } 13623 } 13624 13625 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 13626 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 13627 systemApp = (ps.pkg.applicationInfo.flags & 13628 ApplicationInfo.FLAG_SYSTEM) != 0; 13629 } 13630 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13631 } 13632 13633 // Check whether the newly-scanned package wants to define an already-defined perm 13634 int N = pkg.permissions.size(); 13635 for (int i = N-1; i >= 0; i--) { 13636 PackageParser.Permission perm = pkg.permissions.get(i); 13637 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 13638 if (bp != null) { 13639 // If the defining package is signed with our cert, it's okay. This 13640 // also includes the "updating the same package" case, of course. 13641 // "updating same package" could also involve key-rotation. 13642 final boolean sigsOk; 13643 if (bp.sourcePackage.equals(pkg.packageName) 13644 && (bp.packageSetting instanceof PackageSetting) 13645 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 13646 scanFlags))) { 13647 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 13648 } else { 13649 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 13650 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 13651 } 13652 if (!sigsOk) { 13653 // If the owning package is the system itself, we log but allow 13654 // install to proceed; we fail the install on all other permission 13655 // redefinitions. 13656 if (!bp.sourcePackage.equals("android")) { 13657 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 13658 + pkg.packageName + " attempting to redeclare permission " 13659 + perm.info.name + " already owned by " + bp.sourcePackage); 13660 res.origPermission = perm.info.name; 13661 res.origPackage = bp.sourcePackage; 13662 return; 13663 } else { 13664 Slog.w(TAG, "Package " + pkg.packageName 13665 + " attempting to redeclare system permission " 13666 + perm.info.name + "; ignoring new declaration"); 13667 pkg.permissions.remove(i); 13668 } 13669 } 13670 } 13671 } 13672 } 13673 13674 if (systemApp) { 13675 if (onExternal) { 13676 // Abort update; system app can't be replaced with app on sdcard 13677 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 13678 "Cannot install updates to system apps on sdcard"); 13679 return; 13680 } else if (ephemeral) { 13681 // Abort update; system app can't be replaced with an ephemeral app 13682 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 13683 "Cannot update a system app with an ephemeral app"); 13684 return; 13685 } 13686 } 13687 13688 if (args.move != null) { 13689 // We did an in-place move, so dex is ready to roll 13690 scanFlags |= SCAN_NO_DEX; 13691 scanFlags |= SCAN_MOVE; 13692 13693 synchronized (mPackages) { 13694 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13695 if (ps == null) { 13696 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 13697 "Missing settings for moved package " + pkgName); 13698 } 13699 13700 // We moved the entire application as-is, so bring over the 13701 // previously derived ABI information. 13702 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 13703 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 13704 } 13705 13706 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 13707 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 13708 scanFlags |= SCAN_NO_DEX; 13709 13710 try { 13711 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 13712 args.abiOverride : pkg.cpuAbiOverride); 13713 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 13714 true /* extract libs */); 13715 } catch (PackageManagerException pme) { 13716 Slog.e(TAG, "Error deriving application ABI", pme); 13717 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 13718 return; 13719 } 13720 13721 // Extract package to save the VM unzipping the APK in memory during 13722 // launch. Only do this if profile-guided compilation is enabled because 13723 // otherwise BackgroundDexOptService will not dexopt the package later. 13724 if (mUseJitProfiles) { 13725 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 13726 // Do not run PackageDexOptimizer through the local performDexOpt 13727 // method because `pkg` is not in `mPackages` yet. 13728 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 13729 false /* useProfiles */, true /* extractOnly */); 13730 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13731 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 13732 String msg = "Extracking package failed for " + pkgName; 13733 res.setError(INSTALL_FAILED_DEXOPT, msg); 13734 return; 13735 } 13736 } 13737 } 13738 13739 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 13740 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 13741 return; 13742 } 13743 13744 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 13745 13746 if (replace) { 13747 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 13748 installerPackageName, res); 13749 } else { 13750 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 13751 args.user, installerPackageName, volumeUuid, res); 13752 } 13753 synchronized (mPackages) { 13754 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13755 if (ps != null) { 13756 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13757 } 13758 13759 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13760 for (int i = 0; i < childCount; i++) { 13761 PackageParser.Package childPkg = pkg.childPackages.get(i); 13762 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13763 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13764 if (childPs != null) { 13765 childRes.newUsers = childPs.queryInstalledUsers( 13766 sUserManager.getUserIds(), true); 13767 } 13768 } 13769 } 13770 } 13771 13772 private void startIntentFilterVerifications(int userId, boolean replacing, 13773 PackageParser.Package pkg) { 13774 if (mIntentFilterVerifierComponent == null) { 13775 Slog.w(TAG, "No IntentFilter verification will not be done as " 13776 + "there is no IntentFilterVerifier available!"); 13777 return; 13778 } 13779 13780 final int verifierUid = getPackageUid( 13781 mIntentFilterVerifierComponent.getPackageName(), 13782 MATCH_DEBUG_TRIAGED_MISSING, 13783 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 13784 13785 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 13786 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 13787 mHandler.sendMessage(msg); 13788 13789 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13790 for (int i = 0; i < childCount; i++) { 13791 PackageParser.Package childPkg = pkg.childPackages.get(i); 13792 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 13793 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 13794 mHandler.sendMessage(msg); 13795 } 13796 } 13797 13798 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 13799 PackageParser.Package pkg) { 13800 int size = pkg.activities.size(); 13801 if (size == 0) { 13802 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13803 "No activity, so no need to verify any IntentFilter!"); 13804 return; 13805 } 13806 13807 final boolean hasDomainURLs = hasDomainURLs(pkg); 13808 if (!hasDomainURLs) { 13809 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13810 "No domain URLs, so no need to verify any IntentFilter!"); 13811 return; 13812 } 13813 13814 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 13815 + " if any IntentFilter from the " + size 13816 + " Activities needs verification ..."); 13817 13818 int count = 0; 13819 final String packageName = pkg.packageName; 13820 13821 synchronized (mPackages) { 13822 // If this is a new install and we see that we've already run verification for this 13823 // package, we have nothing to do: it means the state was restored from backup. 13824 if (!replacing) { 13825 IntentFilterVerificationInfo ivi = 13826 mSettings.getIntentFilterVerificationLPr(packageName); 13827 if (ivi != null) { 13828 if (DEBUG_DOMAIN_VERIFICATION) { 13829 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 13830 + ivi.getStatusString()); 13831 } 13832 return; 13833 } 13834 } 13835 13836 // If any filters need to be verified, then all need to be. 13837 boolean needToVerify = false; 13838 for (PackageParser.Activity a : pkg.activities) { 13839 for (ActivityIntentInfo filter : a.intents) { 13840 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 13841 if (DEBUG_DOMAIN_VERIFICATION) { 13842 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 13843 } 13844 needToVerify = true; 13845 break; 13846 } 13847 } 13848 } 13849 13850 if (needToVerify) { 13851 final int verificationId = mIntentFilterVerificationToken++; 13852 for (PackageParser.Activity a : pkg.activities) { 13853 for (ActivityIntentInfo filter : a.intents) { 13854 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 13855 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13856 "Verification needed for IntentFilter:" + filter.toString()); 13857 mIntentFilterVerifier.addOneIntentFilterVerification( 13858 verifierUid, userId, verificationId, filter, packageName); 13859 count++; 13860 } 13861 } 13862 } 13863 } 13864 } 13865 13866 if (count > 0) { 13867 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 13868 + " IntentFilter verification" + (count > 1 ? "s" : "") 13869 + " for userId:" + userId); 13870 mIntentFilterVerifier.startVerifications(userId); 13871 } else { 13872 if (DEBUG_DOMAIN_VERIFICATION) { 13873 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 13874 } 13875 } 13876 } 13877 13878 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 13879 final ComponentName cn = filter.activity.getComponentName(); 13880 final String packageName = cn.getPackageName(); 13881 13882 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 13883 packageName); 13884 if (ivi == null) { 13885 return true; 13886 } 13887 int status = ivi.getStatus(); 13888 switch (status) { 13889 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 13890 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 13891 return true; 13892 13893 default: 13894 // Nothing to do 13895 return false; 13896 } 13897 } 13898 13899 private static boolean isMultiArch(ApplicationInfo info) { 13900 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 13901 } 13902 13903 private static boolean isExternal(PackageParser.Package pkg) { 13904 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13905 } 13906 13907 private static boolean isExternal(PackageSetting ps) { 13908 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13909 } 13910 13911 private static boolean isEphemeral(PackageParser.Package pkg) { 13912 return pkg.applicationInfo.isEphemeralApp(); 13913 } 13914 13915 private static boolean isEphemeral(PackageSetting ps) { 13916 return ps.pkg != null && isEphemeral(ps.pkg); 13917 } 13918 13919 private static boolean isSystemApp(PackageParser.Package pkg) { 13920 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 13921 } 13922 13923 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 13924 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 13925 } 13926 13927 private static boolean hasDomainURLs(PackageParser.Package pkg) { 13928 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 13929 } 13930 13931 private static boolean isSystemApp(PackageSetting ps) { 13932 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 13933 } 13934 13935 private static boolean isUpdatedSystemApp(PackageSetting ps) { 13936 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 13937 } 13938 13939 private int packageFlagsToInstallFlags(PackageSetting ps) { 13940 int installFlags = 0; 13941 if (isEphemeral(ps)) { 13942 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13943 } 13944 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 13945 // This existing package was an external ASEC install when we have 13946 // the external flag without a UUID 13947 installFlags |= PackageManager.INSTALL_EXTERNAL; 13948 } 13949 if (ps.isForwardLocked()) { 13950 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13951 } 13952 return installFlags; 13953 } 13954 13955 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 13956 if (isExternal(pkg)) { 13957 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13958 return StorageManager.UUID_PRIMARY_PHYSICAL; 13959 } else { 13960 return pkg.volumeUuid; 13961 } 13962 } else { 13963 return StorageManager.UUID_PRIVATE_INTERNAL; 13964 } 13965 } 13966 13967 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 13968 if (isExternal(pkg)) { 13969 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13970 return mSettings.getExternalVersion(); 13971 } else { 13972 return mSettings.findOrCreateVersion(pkg.volumeUuid); 13973 } 13974 } else { 13975 return mSettings.getInternalVersion(); 13976 } 13977 } 13978 13979 private void deleteTempPackageFiles() { 13980 final FilenameFilter filter = new FilenameFilter() { 13981 public boolean accept(File dir, String name) { 13982 return name.startsWith("vmdl") && name.endsWith(".tmp"); 13983 } 13984 }; 13985 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 13986 file.delete(); 13987 } 13988 } 13989 13990 @Override 13991 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 13992 int flags) { 13993 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 13994 flags); 13995 } 13996 13997 @Override 13998 public void deletePackage(final String packageName, 13999 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 14000 mContext.enforceCallingOrSelfPermission( 14001 android.Manifest.permission.DELETE_PACKAGES, null); 14002 Preconditions.checkNotNull(packageName); 14003 Preconditions.checkNotNull(observer); 14004 final int uid = Binder.getCallingUid(); 14005 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 14006 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 14007 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 14008 mContext.enforceCallingOrSelfPermission( 14009 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14010 "deletePackage for user " + userId); 14011 } 14012 14013 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 14014 try { 14015 observer.onPackageDeleted(packageName, 14016 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 14017 } catch (RemoteException re) { 14018 } 14019 return; 14020 } 14021 14022 for (int currentUserId : users) { 14023 if (getBlockUninstallForUser(packageName, currentUserId)) { 14024 try { 14025 observer.onPackageDeleted(packageName, 14026 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 14027 } catch (RemoteException re) { 14028 } 14029 return; 14030 } 14031 } 14032 14033 if (DEBUG_REMOVE) { 14034 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 14035 } 14036 // Queue up an async operation since the package deletion may take a little while. 14037 mHandler.post(new Runnable() { 14038 public void run() { 14039 mHandler.removeCallbacks(this); 14040 final int returnCode = deletePackageX(packageName, userId, flags); 14041 try { 14042 observer.onPackageDeleted(packageName, returnCode, null); 14043 } catch (RemoteException e) { 14044 Log.i(TAG, "Observer no longer exists."); 14045 } //end catch 14046 } //end run 14047 }); 14048 } 14049 14050 private boolean isPackageDeviceAdmin(String packageName, int userId) { 14051 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 14052 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 14053 try { 14054 if (dpm != null) { 14055 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 14056 /* callingUserOnly =*/ false); 14057 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 14058 : deviceOwnerComponentName.getPackageName(); 14059 // Does the package contains the device owner? 14060 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 14061 // this check is probably not needed, since DO should be registered as a device 14062 // admin on some user too. (Original bug for this: b/17657954) 14063 if (packageName.equals(deviceOwnerPackageName)) { 14064 return true; 14065 } 14066 // Does it contain a device admin for any user? 14067 int[] users; 14068 if (userId == UserHandle.USER_ALL) { 14069 users = sUserManager.getUserIds(); 14070 } else { 14071 users = new int[]{userId}; 14072 } 14073 for (int i = 0; i < users.length; ++i) { 14074 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 14075 return true; 14076 } 14077 } 14078 } 14079 } catch (RemoteException e) { 14080 } 14081 return false; 14082 } 14083 14084 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 14085 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 14086 } 14087 14088 /** 14089 * This method is an internal method that could be get invoked either 14090 * to delete an installed package or to clean up a failed installation. 14091 * After deleting an installed package, a broadcast is sent to notify any 14092 * listeners that the package has been installed. For cleaning up a failed 14093 * installation, the broadcast is not necessary since the package's 14094 * installation wouldn't have sent the initial broadcast either 14095 * The key steps in deleting a package are 14096 * deleting the package information in internal structures like mPackages, 14097 * deleting the packages base directories through installd 14098 * updating mSettings to reflect current status 14099 * persisting settings for later use 14100 * sending a broadcast if necessary 14101 */ 14102 private int deletePackageX(String packageName, int userId, int flags) { 14103 final PackageRemovedInfo info = new PackageRemovedInfo(); 14104 final boolean res; 14105 14106 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 14107 ? UserHandle.ALL : new UserHandle(userId); 14108 14109 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 14110 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 14111 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 14112 } 14113 14114 PackageParser.Package uninstalledPkg; 14115 14116 // for the uninstall-updates case and restricted profiles, remember the per- 14117 // user handle installed state 14118 int[] allUsers; 14119 synchronized (mPackages) { 14120 uninstalledPkg = mPackages.get(packageName); 14121 PackageSetting ps = mSettings.mPackages.get(packageName); 14122 if (ps == null || uninstalledPkg == null) { 14123 Slog.w(TAG, "Not removing non-existent package " + packageName); 14124 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14125 } 14126 allUsers = sUserManager.getUserIds(); 14127 info.origUsers = ps.queryInstalledUsers(allUsers, true); 14128 } 14129 14130 synchronized (mInstallLock) { 14131 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 14132 res = deletePackageLI(packageName, removeForUser, true, allUsers, 14133 flags | REMOVE_CHATTY, info, true, null); 14134 synchronized (mPackages) { 14135 if (res) { 14136 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg); 14137 } 14138 } 14139 } 14140 14141 if (res) { 14142 info.sendPackageRemovedBroadcasts(); 14143 info.sendSystemPackageUpdatedBroadcasts(); 14144 info.sendSystemPackageAppearedBroadcasts(); 14145 } 14146 // Force a gc here. 14147 Runtime.getRuntime().gc(); 14148 // Delete the resources here after sending the broadcast to let 14149 // other processes clean up before deleting resources. 14150 if (info.args != null) { 14151 synchronized (mInstallLock) { 14152 info.args.doPostDeleteLI(true); 14153 } 14154 } 14155 14156 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14157 } 14158 14159 class PackageRemovedInfo { 14160 String removedPackage; 14161 int uid = -1; 14162 int removedAppId = -1; 14163 int[] origUsers; 14164 int[] removedUsers = null; 14165 boolean isRemovedPackageSystemUpdate = false; 14166 boolean isUpdate; 14167 boolean dataRemoved; 14168 boolean removedForAllUsers; 14169 // Clean up resources deleted packages. 14170 InstallArgs args = null; 14171 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 14172 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 14173 14174 void sendPackageRemovedBroadcasts() { 14175 sendPackageRemovedBroadcastInternal(); 14176 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 14177 for (int i = 0; i < childCount; i++) { 14178 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 14179 childInfo.sendPackageRemovedBroadcastInternal(); 14180 } 14181 } 14182 14183 void sendSystemPackageUpdatedBroadcasts() { 14184 if (isRemovedPackageSystemUpdate) { 14185 sendSystemPackageUpdatedBroadcastsInternal(); 14186 final int childCount = (removedChildPackages != null) 14187 ? removedChildPackages.size() : 0; 14188 for (int i = 0; i < childCount; i++) { 14189 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 14190 if (childInfo.isRemovedPackageSystemUpdate) { 14191 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 14192 } 14193 } 14194 } 14195 } 14196 14197 void sendSystemPackageAppearedBroadcasts() { 14198 final int packageCount = (appearedChildPackages != null) 14199 ? appearedChildPackages.size() : 0; 14200 for (int i = 0; i < packageCount; i++) { 14201 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 14202 for (int userId : installedInfo.newUsers) { 14203 sendPackageAddedForUser(installedInfo.name, true, 14204 UserHandle.getAppId(installedInfo.uid), userId); 14205 } 14206 } 14207 } 14208 14209 private void sendSystemPackageUpdatedBroadcastsInternal() { 14210 Bundle extras = new Bundle(2); 14211 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 14212 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14213 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 14214 extras, 0, null, null, null); 14215 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 14216 extras, 0, null, null, null); 14217 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 14218 null, 0, removedPackage, null, null); 14219 } 14220 14221 private void sendPackageRemovedBroadcastInternal() { 14222 Bundle extras = new Bundle(2); 14223 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 14224 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 14225 if (isUpdate || isRemovedPackageSystemUpdate) { 14226 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14227 } 14228 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 14229 if (removedPackage != null) { 14230 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 14231 extras, 0, null, null, removedUsers); 14232 if (dataRemoved && !isRemovedPackageSystemUpdate) { 14233 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 14234 removedPackage, extras, 0, null, null, removedUsers); 14235 } 14236 } 14237 if (removedAppId >= 0) { 14238 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 14239 removedUsers); 14240 } 14241 } 14242 } 14243 14244 /* 14245 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 14246 * flag is not set, the data directory is removed as well. 14247 * make sure this flag is set for partially installed apps. If not its meaningless to 14248 * delete a partially installed application. 14249 */ 14250 private void removePackageDataLI(PackageSetting ps, int[] allUserHandles, 14251 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 14252 String packageName = ps.name; 14253 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 14254 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 14255 // Retrieve object to delete permissions for shared user later on 14256 final PackageSetting deletedPs; 14257 // reader 14258 synchronized (mPackages) { 14259 deletedPs = mSettings.mPackages.get(packageName); 14260 if (outInfo != null) { 14261 outInfo.removedPackage = packageName; 14262 outInfo.removedUsers = deletedPs != null 14263 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 14264 : null; 14265 } 14266 } 14267 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 14268 removeDataDirsLI(ps.volumeUuid, packageName); 14269 if (outInfo != null) { 14270 outInfo.dataRemoved = true; 14271 } 14272 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 14273 } 14274 // writer 14275 synchronized (mPackages) { 14276 if (deletedPs != null) { 14277 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 14278 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 14279 clearDefaultBrowserIfNeeded(packageName); 14280 if (outInfo != null) { 14281 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 14282 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 14283 } 14284 updatePermissionsLPw(deletedPs.name, null, 0); 14285 if (deletedPs.sharedUser != null) { 14286 // Remove permissions associated with package. Since runtime 14287 // permissions are per user we have to kill the removed package 14288 // or packages running under the shared user of the removed 14289 // package if revoking the permissions requested only by the removed 14290 // package is successful and this causes a change in gids. 14291 for (int userId : UserManagerService.getInstance().getUserIds()) { 14292 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 14293 userId); 14294 if (userIdToKill == UserHandle.USER_ALL 14295 || userIdToKill >= UserHandle.USER_SYSTEM) { 14296 // If gids changed for this user, kill all affected packages. 14297 mHandler.post(new Runnable() { 14298 @Override 14299 public void run() { 14300 // This has to happen with no lock held. 14301 killApplication(deletedPs.name, deletedPs.appId, 14302 KILL_APP_REASON_GIDS_CHANGED); 14303 } 14304 }); 14305 break; 14306 } 14307 } 14308 } 14309 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 14310 } 14311 // make sure to preserve per-user disabled state if this removal was just 14312 // a downgrade of a system app to the factory package 14313 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 14314 if (DEBUG_REMOVE) { 14315 Slog.d(TAG, "Propagating install state across downgrade"); 14316 } 14317 for (int userId : allUserHandles) { 14318 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 14319 if (DEBUG_REMOVE) { 14320 Slog.d(TAG, " user " + userId + " => " + installed); 14321 } 14322 ps.setInstalled(installed, userId); 14323 } 14324 } 14325 } 14326 // can downgrade to reader 14327 if (writeSettings) { 14328 // Save settings now 14329 mSettings.writeLPr(); 14330 } 14331 } 14332 if (outInfo != null) { 14333 // A user ID was deleted here. Go through all users and remove it 14334 // from KeyStore. 14335 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 14336 } 14337 } 14338 14339 static boolean locationIsPrivileged(File path) { 14340 try { 14341 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 14342 .getCanonicalPath(); 14343 return path.getCanonicalPath().startsWith(privilegedAppDir); 14344 } catch (IOException e) { 14345 Slog.e(TAG, "Unable to access code path " + path); 14346 } 14347 return false; 14348 } 14349 14350 /* 14351 * Tries to delete system package. 14352 */ 14353 private boolean deleteSystemPackageLI(PackageParser.Package deletedPkg, 14354 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 14355 boolean writeSettings) { 14356 if (deletedPkg.parentPackage != null) { 14357 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 14358 return false; 14359 } 14360 14361 final boolean applyUserRestrictions 14362 = (allUserHandles != null) && (outInfo.origUsers != null); 14363 final PackageSetting disabledPs; 14364 // Confirm if the system package has been updated 14365 // An updated system app can be deleted. This will also have to restore 14366 // the system pkg from system partition 14367 // reader 14368 synchronized (mPackages) { 14369 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPkg.packageName); 14370 } 14371 14372 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 14373 + " disabledPs=" + disabledPs); 14374 14375 if (disabledPs == null) { 14376 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 14377 return false; 14378 } else if (DEBUG_REMOVE) { 14379 Slog.d(TAG, "Deleting system pkg from data partition"); 14380 } 14381 14382 if (DEBUG_REMOVE) { 14383 if (applyUserRestrictions) { 14384 Slog.d(TAG, "Remembering install states:"); 14385 for (int userId : allUserHandles) { 14386 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 14387 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 14388 } 14389 } 14390 } 14391 14392 // Delete the updated package 14393 outInfo.isRemovedPackageSystemUpdate = true; 14394 if (outInfo.removedChildPackages != null) { 14395 final int childCount = (deletedPkg.childPackages != null) 14396 ? deletedPkg.childPackages.size() : 0; 14397 for (int i = 0; i < childCount; i++) { 14398 String childPackageName = deletedPkg.childPackages.get(i).packageName; 14399 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 14400 .contains(childPackageName)) { 14401 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 14402 childPackageName); 14403 if (childInfo != null) { 14404 childInfo.isRemovedPackageSystemUpdate = true; 14405 } 14406 } 14407 } 14408 } 14409 14410 if (disabledPs.versionCode < deletedPs.versionCode) { 14411 // Delete data for downgrades 14412 flags &= ~PackageManager.DELETE_KEEP_DATA; 14413 } else { 14414 // Preserve data by setting flag 14415 flags |= PackageManager.DELETE_KEEP_DATA; 14416 } 14417 14418 boolean ret = deleteInstalledPackageLI(deletedPkg, true, flags, allUserHandles, 14419 outInfo, writeSettings, disabledPs.pkg); 14420 if (!ret) { 14421 return false; 14422 } 14423 14424 // writer 14425 synchronized (mPackages) { 14426 // Reinstate the old system package 14427 enableSystemPackageLPw(disabledPs.pkg); 14428 // Remove any native libraries from the upgraded package. 14429 removeNativeBinariesLI(deletedPkg); 14430 } 14431 14432 // Install the system package 14433 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 14434 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 14435 if (locationIsPrivileged(disabledPs.codePath)) { 14436 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 14437 } 14438 14439 final PackageParser.Package newPkg; 14440 try { 14441 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 14442 } catch (PackageManagerException e) { 14443 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 14444 + e.getMessage()); 14445 return false; 14446 } 14447 14448 prepareAppDataAfterInstall(newPkg); 14449 14450 // writer 14451 synchronized (mPackages) { 14452 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 14453 14454 // Propagate the permissions state as we do not want to drop on the floor 14455 // runtime permissions. The update permissions method below will take 14456 // care of removing obsolete permissions and grant install permissions. 14457 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 14458 updatePermissionsLPw(newPkg.packageName, newPkg, 14459 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 14460 14461 if (applyUserRestrictions) { 14462 if (DEBUG_REMOVE) { 14463 Slog.d(TAG, "Propagating install state across reinstall"); 14464 } 14465 for (int userId : allUserHandles) { 14466 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 14467 if (DEBUG_REMOVE) { 14468 Slog.d(TAG, " user " + userId + " => " + installed); 14469 } 14470 ps.setInstalled(installed, userId); 14471 14472 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 14473 } 14474 // Regardless of writeSettings we need to ensure that this restriction 14475 // state propagation is persisted 14476 mSettings.writeAllUsersPackageRestrictionsLPr(); 14477 } 14478 // can downgrade to reader here 14479 if (writeSettings) { 14480 mSettings.writeLPr(); 14481 } 14482 } 14483 return true; 14484 } 14485 14486 private boolean deleteInstalledPackageLI(PackageParser.Package pkg, 14487 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 14488 PackageRemovedInfo outInfo, boolean writeSettings, 14489 PackageParser.Package replacingPackage) { 14490 PackageSetting ps = null; 14491 14492 synchronized (mPackages) { 14493 pkg = mPackages.get(pkg.packageName); 14494 if (pkg == null) { 14495 return false; 14496 } 14497 14498 ps = mSettings.mPackages.get(pkg.packageName); 14499 if (ps == null) { 14500 return false; 14501 } 14502 14503 if (outInfo != null) { 14504 outInfo.uid = ps.appId; 14505 } 14506 14507 if (outInfo != null && outInfo.removedChildPackages != null) { 14508 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14509 for (int i = 0; i < childCount; i++) { 14510 String childPackageName = ps.childPackageNames.get(i); 14511 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 14512 if (childPs == null) { 14513 return false; 14514 } 14515 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 14516 childPackageName); 14517 if (childInfo != null) { 14518 childInfo.uid = childPs.appId; 14519 } 14520 } 14521 } 14522 } 14523 14524 // Delete package data from internal structures and also remove data if flag is set 14525 removePackageDataLI(ps, allUserHandles, outInfo, flags, writeSettings); 14526 14527 // Delete the child packages data 14528 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14529 for (int i = 0; i < childCount; i++) { 14530 PackageSetting childPs; 14531 synchronized (mPackages) { 14532 childPs = mSettings.peekPackageLPr(pkg.childPackages.get(i).packageName); 14533 } 14534 if (childPs != null) { 14535 PackageRemovedInfo childOutInfo = (outInfo != null 14536 && outInfo.removedChildPackages != null) 14537 ? outInfo.removedChildPackages.get(childPs.name) : null; 14538 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 14539 && (replacingPackage != null 14540 && !replacingPackage.hasChildPackage(childPs.name)) 14541 ? flags & ~DELETE_KEEP_DATA : flags; 14542 removePackageDataLI(childPs, allUserHandles, childOutInfo, 14543 deleteFlags, writeSettings); 14544 } 14545 } 14546 14547 // Delete application code and resources only for parent packages 14548 if (ps.pkg.parentPackage == null) { 14549 if (deleteCodeAndResources && (outInfo != null)) { 14550 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 14551 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 14552 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 14553 } 14554 } 14555 14556 return true; 14557 } 14558 14559 @Override 14560 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 14561 int userId) { 14562 mContext.enforceCallingOrSelfPermission( 14563 android.Manifest.permission.DELETE_PACKAGES, null); 14564 synchronized (mPackages) { 14565 PackageSetting ps = mSettings.mPackages.get(packageName); 14566 if (ps == null) { 14567 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 14568 return false; 14569 } 14570 if (!ps.getInstalled(userId)) { 14571 // Can't block uninstall for an app that is not installed or enabled. 14572 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 14573 return false; 14574 } 14575 ps.setBlockUninstall(blockUninstall, userId); 14576 mSettings.writePackageRestrictionsLPr(userId); 14577 } 14578 return true; 14579 } 14580 14581 @Override 14582 public boolean getBlockUninstallForUser(String packageName, int userId) { 14583 synchronized (mPackages) { 14584 PackageSetting ps = mSettings.mPackages.get(packageName); 14585 if (ps == null) { 14586 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 14587 return false; 14588 } 14589 return ps.getBlockUninstall(userId); 14590 } 14591 } 14592 14593 @Override 14594 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 14595 int callingUid = Binder.getCallingUid(); 14596 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 14597 throw new SecurityException( 14598 "setRequiredForSystemUser can only be run by the system or root"); 14599 } 14600 synchronized (mPackages) { 14601 PackageSetting ps = mSettings.mPackages.get(packageName); 14602 if (ps == null) { 14603 Log.w(TAG, "Package doesn't exist: " + packageName); 14604 return false; 14605 } 14606 if (systemUserApp) { 14607 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 14608 } else { 14609 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 14610 } 14611 mSettings.writeLPr(); 14612 } 14613 return true; 14614 } 14615 14616 /* 14617 * This method handles package deletion in general 14618 */ 14619 private boolean deletePackageLI(String packageName, UserHandle user, 14620 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 14621 PackageRemovedInfo outInfo, boolean writeSettings, 14622 PackageParser.Package replacingPackage) { 14623 if (packageName == null) { 14624 Slog.w(TAG, "Attempt to delete null packageName."); 14625 return false; 14626 } 14627 14628 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 14629 14630 PackageSetting ps; 14631 14632 synchronized (mPackages) { 14633 ps = mSettings.mPackages.get(packageName); 14634 if (ps == null) { 14635 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 14636 return false; 14637 } 14638 14639 if (ps.pkg.parentPackage != null && (!isSystemApp(ps) 14640 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 14641 if (DEBUG_REMOVE) { 14642 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 14643 + ((user == null) ? UserHandle.USER_ALL : user)); 14644 } 14645 final int removedUserId = (user != null) ? user.getIdentifier() 14646 : UserHandle.USER_ALL; 14647 if (!clearPackageStateForUser(ps, removedUserId, outInfo)) { 14648 return false; 14649 } 14650 markPackageUninstalledForUserLPw(ps, user); 14651 scheduleWritePackageRestrictionsLocked(user); 14652 return true; 14653 } 14654 } 14655 14656 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 14657 && user.getIdentifier() != UserHandle.USER_ALL)) { 14658 // The caller is asking that the package only be deleted for a single 14659 // user. To do this, we just mark its uninstalled state and delete 14660 // its data. If this is a system app, we only allow this to happen if 14661 // they have set the special DELETE_SYSTEM_APP which requests different 14662 // semantics than normal for uninstalling system apps. 14663 markPackageUninstalledForUserLPw(ps, user); 14664 14665 if (!isSystemApp(ps)) { 14666 // Do not uninstall the APK if an app should be cached 14667 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 14668 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 14669 // Other user still have this package installed, so all 14670 // we need to do is clear this user's data and save that 14671 // it is uninstalled. 14672 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 14673 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 14674 return false; 14675 } 14676 scheduleWritePackageRestrictionsLocked(user); 14677 return true; 14678 } else { 14679 // We need to set it back to 'installed' so the uninstall 14680 // broadcasts will be sent correctly. 14681 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 14682 ps.setInstalled(true, user.getIdentifier()); 14683 } 14684 } else { 14685 // This is a system app, so we assume that the 14686 // other users still have this package installed, so all 14687 // we need to do is clear this user's data and save that 14688 // it is uninstalled. 14689 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 14690 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 14691 return false; 14692 } 14693 scheduleWritePackageRestrictionsLocked(user); 14694 return true; 14695 } 14696 } 14697 14698 // If we are deleting a composite package for all users, keep track 14699 // of result for each child. 14700 if (ps.childPackageNames != null && outInfo != null) { 14701 synchronized (mPackages) { 14702 final int childCount = ps.childPackageNames.size(); 14703 outInfo.removedChildPackages = new ArrayMap<>(childCount); 14704 for (int i = 0; i < childCount; i++) { 14705 String childPackageName = ps.childPackageNames.get(i); 14706 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 14707 childInfo.removedPackage = childPackageName; 14708 outInfo.removedChildPackages.put(childPackageName, childInfo); 14709 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 14710 if (childPs != null) { 14711 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 14712 } 14713 } 14714 } 14715 } 14716 14717 boolean ret = false; 14718 if (isSystemApp(ps)) { 14719 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 14720 // When an updated system application is deleted we delete the existing resources 14721 // as well and fall back to existing code in system partition 14722 ret = deleteSystemPackageLI(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 14723 } else { 14724 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 14725 // Kill application pre-emptively especially for apps on sd. 14726 killApplication(packageName, ps.appId, "uninstall pkg"); 14727 ret = deleteInstalledPackageLI(ps.pkg, deleteCodeAndResources, flags, allUserHandles, 14728 outInfo, writeSettings, replacingPackage); 14729 } 14730 14731 // Take a note whether we deleted the package for all users 14732 if (outInfo != null) { 14733 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14734 if (outInfo.removedChildPackages != null) { 14735 synchronized (mPackages) { 14736 final int childCount = outInfo.removedChildPackages.size(); 14737 for (int i = 0; i < childCount; i++) { 14738 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 14739 if (childInfo != null) { 14740 childInfo.removedForAllUsers = mPackages.get( 14741 childInfo.removedPackage) == null; 14742 } 14743 } 14744 } 14745 } 14746 // If we uninstalled an update to a system app there may be some 14747 // child packages that appeared as they are declared in the system 14748 // app but were not declared in the update. 14749 if (isSystemApp(ps)) { 14750 synchronized (mPackages) { 14751 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 14752 final int childCount = (updatedPs.childPackageNames != null) 14753 ? updatedPs.childPackageNames.size() : 0; 14754 for (int i = 0; i < childCount; i++) { 14755 String childPackageName = updatedPs.childPackageNames.get(i); 14756 if (outInfo.removedChildPackages == null 14757 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 14758 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 14759 if (childPs == null) { 14760 continue; 14761 } 14762 PackageInstalledInfo installRes = new PackageInstalledInfo(); 14763 installRes.name = childPackageName; 14764 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 14765 installRes.pkg = mPackages.get(childPackageName); 14766 installRes.uid = childPs.pkg.applicationInfo.uid; 14767 if (outInfo.appearedChildPackages == null) { 14768 outInfo.appearedChildPackages = new ArrayMap<>(); 14769 } 14770 outInfo.appearedChildPackages.put(childPackageName, installRes); 14771 } 14772 } 14773 } 14774 } 14775 } 14776 14777 return ret; 14778 } 14779 14780 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 14781 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 14782 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 14783 for (int nextUserId : userIds) { 14784 if (DEBUG_REMOVE) { 14785 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 14786 } 14787 ps.setUserState(nextUserId, COMPONENT_ENABLED_STATE_DEFAULT, 14788 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 14789 false /*hidden*/, false /*suspended*/, null, null, null, 14790 false /*blockUninstall*/, 14791 ps.readUserState(nextUserId).domainVerificationStatus, 0); 14792 } 14793 } 14794 14795 private boolean clearPackageStateForUser(PackageSetting ps, int userId, 14796 PackageRemovedInfo outInfo) { 14797 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 14798 : new int[] {userId}; 14799 for (int nextUserId : userIds) { 14800 if (DEBUG_REMOVE) { 14801 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 14802 + nextUserId); 14803 } 14804 final int flags = StorageManager.FLAG_STORAGE_CE| StorageManager.FLAG_STORAGE_DE; 14805 try { 14806 mInstaller.destroyAppData(ps.volumeUuid, ps.name, nextUserId, flags); 14807 } catch (InstallerException e) { 14808 Slog.w(TAG, "Couldn't remove cache files for package " + ps.name, e); 14809 return false; 14810 } 14811 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 14812 schedulePackageCleaning(ps.name, nextUserId, false); 14813 synchronized (mPackages) { 14814 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 14815 scheduleWritePackageRestrictionsLocked(nextUserId); 14816 } 14817 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 14818 } 14819 } 14820 14821 if (outInfo != null) { 14822 outInfo.removedPackage = ps.name; 14823 outInfo.removedAppId = ps.appId; 14824 outInfo.removedUsers = userIds; 14825 } 14826 14827 return true; 14828 } 14829 14830 private final class ClearStorageConnection implements ServiceConnection { 14831 IMediaContainerService mContainerService; 14832 14833 @Override 14834 public void onServiceConnected(ComponentName name, IBinder service) { 14835 synchronized (this) { 14836 mContainerService = IMediaContainerService.Stub.asInterface(service); 14837 notifyAll(); 14838 } 14839 } 14840 14841 @Override 14842 public void onServiceDisconnected(ComponentName name) { 14843 } 14844 } 14845 14846 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 14847 final boolean mounted; 14848 if (Environment.isExternalStorageEmulated()) { 14849 mounted = true; 14850 } else { 14851 final String status = Environment.getExternalStorageState(); 14852 14853 mounted = status.equals(Environment.MEDIA_MOUNTED) 14854 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 14855 } 14856 14857 if (!mounted) { 14858 return; 14859 } 14860 14861 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 14862 int[] users; 14863 if (userId == UserHandle.USER_ALL) { 14864 users = sUserManager.getUserIds(); 14865 } else { 14866 users = new int[] { userId }; 14867 } 14868 final ClearStorageConnection conn = new ClearStorageConnection(); 14869 if (mContext.bindServiceAsUser( 14870 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 14871 try { 14872 for (int curUser : users) { 14873 long timeout = SystemClock.uptimeMillis() + 5000; 14874 synchronized (conn) { 14875 long now = SystemClock.uptimeMillis(); 14876 while (conn.mContainerService == null && now < timeout) { 14877 try { 14878 conn.wait(timeout - now); 14879 } catch (InterruptedException e) { 14880 } 14881 } 14882 } 14883 if (conn.mContainerService == null) { 14884 return; 14885 } 14886 14887 final UserEnvironment userEnv = new UserEnvironment(curUser); 14888 clearDirectory(conn.mContainerService, 14889 userEnv.buildExternalStorageAppCacheDirs(packageName)); 14890 if (allData) { 14891 clearDirectory(conn.mContainerService, 14892 userEnv.buildExternalStorageAppDataDirs(packageName)); 14893 clearDirectory(conn.mContainerService, 14894 userEnv.buildExternalStorageAppMediaDirs(packageName)); 14895 } 14896 } 14897 } finally { 14898 mContext.unbindService(conn); 14899 } 14900 } 14901 } 14902 14903 @Override 14904 public void clearApplicationUserData(final String packageName, 14905 final IPackageDataObserver observer, final int userId) { 14906 mContext.enforceCallingOrSelfPermission( 14907 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 14908 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 14909 // Queue up an async operation since the package deletion may take a little while. 14910 mHandler.post(new Runnable() { 14911 public void run() { 14912 mHandler.removeCallbacks(this); 14913 final boolean succeeded; 14914 synchronized (mInstallLock) { 14915 succeeded = clearApplicationUserDataLI(packageName, userId); 14916 } 14917 clearExternalStorageDataSync(packageName, userId, true); 14918 if (succeeded) { 14919 // invoke DeviceStorageMonitor's update method to clear any notifications 14920 DeviceStorageMonitorInternal 14921 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 14922 if (dsm != null) { 14923 dsm.checkMemory(); 14924 } 14925 } 14926 if(observer != null) { 14927 try { 14928 observer.onRemoveCompleted(packageName, succeeded); 14929 } catch (RemoteException e) { 14930 Log.i(TAG, "Observer no longer exists."); 14931 } 14932 } //end if observer 14933 } //end run 14934 }); 14935 } 14936 14937 private boolean clearApplicationUserDataLI(String packageName, int userId) { 14938 if (packageName == null) { 14939 Slog.w(TAG, "Attempt to delete null packageName."); 14940 return false; 14941 } 14942 14943 // Try finding details about the requested package 14944 PackageParser.Package pkg; 14945 synchronized (mPackages) { 14946 pkg = mPackages.get(packageName); 14947 if (pkg == null) { 14948 final PackageSetting ps = mSettings.mPackages.get(packageName); 14949 if (ps != null) { 14950 pkg = ps.pkg; 14951 } 14952 } 14953 14954 if (pkg == null) { 14955 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 14956 return false; 14957 } 14958 14959 PackageSetting ps = (PackageSetting) pkg.mExtras; 14960 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 14961 } 14962 14963 // Always delete data directories for package, even if we found no other 14964 // record of app. This helps users recover from UID mismatches without 14965 // resorting to a full data wipe. 14966 // TODO: triage flags as part of 26466827 14967 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 14968 try { 14969 mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags); 14970 } catch (InstallerException e) { 14971 Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e); 14972 return false; 14973 } 14974 14975 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 14976 removeKeystoreDataIfNeeded(userId, appId); 14977 14978 // Create a native library symlink only if we have native libraries 14979 // and if the native libraries are 32 bit libraries. We do not provide 14980 // this symlink for 64 bit libraries. 14981 if (pkg.applicationInfo.primaryCpuAbi != null && 14982 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 14983 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 14984 try { 14985 mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 14986 nativeLibPath, userId); 14987 } catch (InstallerException e) { 14988 Slog.w(TAG, "Failed linking native library dir", e); 14989 return false; 14990 } 14991 } 14992 14993 return true; 14994 } 14995 14996 /** 14997 * Reverts user permission state changes (permissions and flags) in 14998 * all packages for a given user. 14999 * 15000 * @param userId The device user for which to do a reset. 15001 */ 15002 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 15003 final int packageCount = mPackages.size(); 15004 for (int i = 0; i < packageCount; i++) { 15005 PackageParser.Package pkg = mPackages.valueAt(i); 15006 PackageSetting ps = (PackageSetting) pkg.mExtras; 15007 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15008 } 15009 } 15010 15011 /** 15012 * Reverts user permission state changes (permissions and flags). 15013 * 15014 * @param ps The package for which to reset. 15015 * @param userId The device user for which to do a reset. 15016 */ 15017 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 15018 final PackageSetting ps, final int userId) { 15019 if (ps.pkg == null) { 15020 return; 15021 } 15022 15023 // These are flags that can change base on user actions. 15024 final int userSettableMask = FLAG_PERMISSION_USER_SET 15025 | FLAG_PERMISSION_USER_FIXED 15026 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 15027 | FLAG_PERMISSION_REVIEW_REQUIRED; 15028 15029 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 15030 | FLAG_PERMISSION_POLICY_FIXED; 15031 15032 boolean writeInstallPermissions = false; 15033 boolean writeRuntimePermissions = false; 15034 15035 final int permissionCount = ps.pkg.requestedPermissions.size(); 15036 for (int i = 0; i < permissionCount; i++) { 15037 String permission = ps.pkg.requestedPermissions.get(i); 15038 15039 BasePermission bp = mSettings.mPermissions.get(permission); 15040 if (bp == null) { 15041 continue; 15042 } 15043 15044 // If shared user we just reset the state to which only this app contributed. 15045 if (ps.sharedUser != null) { 15046 boolean used = false; 15047 final int packageCount = ps.sharedUser.packages.size(); 15048 for (int j = 0; j < packageCount; j++) { 15049 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 15050 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 15051 && pkg.pkg.requestedPermissions.contains(permission)) { 15052 used = true; 15053 break; 15054 } 15055 } 15056 if (used) { 15057 continue; 15058 } 15059 } 15060 15061 PermissionsState permissionsState = ps.getPermissionsState(); 15062 15063 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 15064 15065 // Always clear the user settable flags. 15066 final boolean hasInstallState = permissionsState.getInstallPermissionState( 15067 bp.name) != null; 15068 // If permission review is enabled and this is a legacy app, mark the 15069 // permission as requiring a review as this is the initial state. 15070 int flags = 0; 15071 if (Build.PERMISSIONS_REVIEW_REQUIRED 15072 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 15073 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 15074 } 15075 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 15076 if (hasInstallState) { 15077 writeInstallPermissions = true; 15078 } else { 15079 writeRuntimePermissions = true; 15080 } 15081 } 15082 15083 // Below is only runtime permission handling. 15084 if (!bp.isRuntime()) { 15085 continue; 15086 } 15087 15088 // Never clobber system or policy. 15089 if ((oldFlags & policyOrSystemFlags) != 0) { 15090 continue; 15091 } 15092 15093 // If this permission was granted by default, make sure it is. 15094 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 15095 if (permissionsState.grantRuntimePermission(bp, userId) 15096 != PERMISSION_OPERATION_FAILURE) { 15097 writeRuntimePermissions = true; 15098 } 15099 // If permission review is enabled the permissions for a legacy apps 15100 // are represented as constantly granted runtime ones, so don't revoke. 15101 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 15102 // Otherwise, reset the permission. 15103 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 15104 switch (revokeResult) { 15105 case PERMISSION_OPERATION_SUCCESS: { 15106 writeRuntimePermissions = true; 15107 } break; 15108 15109 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 15110 writeRuntimePermissions = true; 15111 final int appId = ps.appId; 15112 mHandler.post(new Runnable() { 15113 @Override 15114 public void run() { 15115 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 15116 } 15117 }); 15118 } break; 15119 } 15120 } 15121 } 15122 15123 // Synchronously write as we are taking permissions away. 15124 if (writeRuntimePermissions) { 15125 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 15126 } 15127 15128 // Synchronously write as we are taking permissions away. 15129 if (writeInstallPermissions) { 15130 mSettings.writeLPr(); 15131 } 15132 } 15133 15134 /** 15135 * Remove entries from the keystore daemon. Will only remove it if the 15136 * {@code appId} is valid. 15137 */ 15138 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 15139 if (appId < 0) { 15140 return; 15141 } 15142 15143 final KeyStore keyStore = KeyStore.getInstance(); 15144 if (keyStore != null) { 15145 if (userId == UserHandle.USER_ALL) { 15146 for (final int individual : sUserManager.getUserIds()) { 15147 keyStore.clearUid(UserHandle.getUid(individual, appId)); 15148 } 15149 } else { 15150 keyStore.clearUid(UserHandle.getUid(userId, appId)); 15151 } 15152 } else { 15153 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 15154 } 15155 } 15156 15157 @Override 15158 public void deleteApplicationCacheFiles(final String packageName, 15159 final IPackageDataObserver observer) { 15160 mContext.enforceCallingOrSelfPermission( 15161 android.Manifest.permission.DELETE_CACHE_FILES, null); 15162 // Queue up an async operation since the package deletion may take a little while. 15163 final int userId = UserHandle.getCallingUserId(); 15164 mHandler.post(new Runnable() { 15165 public void run() { 15166 mHandler.removeCallbacks(this); 15167 final boolean succeded; 15168 synchronized (mInstallLock) { 15169 succeded = deleteApplicationCacheFilesLI(packageName, userId); 15170 } 15171 clearExternalStorageDataSync(packageName, userId, false); 15172 if (observer != null) { 15173 try { 15174 observer.onRemoveCompleted(packageName, succeded); 15175 } catch (RemoteException e) { 15176 Log.i(TAG, "Observer no longer exists."); 15177 } 15178 } //end if observer 15179 } //end run 15180 }); 15181 } 15182 15183 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 15184 if (packageName == null) { 15185 Slog.w(TAG, "Attempt to delete null packageName."); 15186 return false; 15187 } 15188 PackageParser.Package p; 15189 synchronized (mPackages) { 15190 p = mPackages.get(packageName); 15191 } 15192 if (p == null) { 15193 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 15194 return false; 15195 } 15196 final ApplicationInfo applicationInfo = p.applicationInfo; 15197 if (applicationInfo == null) { 15198 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 15199 return false; 15200 } 15201 // TODO: triage flags as part of 26466827 15202 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15203 try { 15204 mInstaller.clearAppData(p.volumeUuid, packageName, userId, 15205 flags | Installer.FLAG_CLEAR_CACHE_ONLY); 15206 } catch (InstallerException e) { 15207 Slog.w(TAG, "Couldn't remove cache files for package " 15208 + packageName + " u" + userId, e); 15209 return false; 15210 } 15211 return true; 15212 } 15213 15214 @Override 15215 public void getPackageSizeInfo(final String packageName, int userHandle, 15216 final IPackageStatsObserver observer) { 15217 mContext.enforceCallingOrSelfPermission( 15218 android.Manifest.permission.GET_PACKAGE_SIZE, null); 15219 if (packageName == null) { 15220 throw new IllegalArgumentException("Attempt to get size of null packageName"); 15221 } 15222 15223 PackageStats stats = new PackageStats(packageName, userHandle); 15224 15225 /* 15226 * Queue up an async operation since the package measurement may take a 15227 * little while. 15228 */ 15229 Message msg = mHandler.obtainMessage(INIT_COPY); 15230 msg.obj = new MeasureParams(stats, observer); 15231 mHandler.sendMessage(msg); 15232 } 15233 15234 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 15235 PackageStats pStats) { 15236 if (packageName == null) { 15237 Slog.w(TAG, "Attempt to get size of null packageName."); 15238 return false; 15239 } 15240 PackageParser.Package p; 15241 boolean dataOnly = false; 15242 String libDirRoot = null; 15243 String asecPath = null; 15244 PackageSetting ps = null; 15245 synchronized (mPackages) { 15246 p = mPackages.get(packageName); 15247 ps = mSettings.mPackages.get(packageName); 15248 if(p == null) { 15249 dataOnly = true; 15250 if((ps == null) || (ps.pkg == null)) { 15251 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 15252 return false; 15253 } 15254 p = ps.pkg; 15255 } 15256 if (ps != null) { 15257 libDirRoot = ps.legacyNativeLibraryPathString; 15258 } 15259 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 15260 final long token = Binder.clearCallingIdentity(); 15261 try { 15262 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 15263 if (secureContainerId != null) { 15264 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 15265 } 15266 } finally { 15267 Binder.restoreCallingIdentity(token); 15268 } 15269 } 15270 } 15271 String publicSrcDir = null; 15272 if(!dataOnly) { 15273 final ApplicationInfo applicationInfo = p.applicationInfo; 15274 if (applicationInfo == null) { 15275 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 15276 return false; 15277 } 15278 if (p.isForwardLocked()) { 15279 publicSrcDir = applicationInfo.getBaseResourcePath(); 15280 } 15281 } 15282 // TODO: extend to measure size of split APKs 15283 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 15284 // not just the first level. 15285 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 15286 // just the primary. 15287 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 15288 15289 String apkPath; 15290 File packageDir = new File(p.codePath); 15291 15292 if (packageDir.isDirectory() && p.canHaveOatDir()) { 15293 apkPath = packageDir.getAbsolutePath(); 15294 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 15295 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 15296 libDirRoot = null; 15297 } 15298 } else { 15299 apkPath = p.baseCodePath; 15300 } 15301 15302 // TODO: triage flags as part of 26466827 15303 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15304 try { 15305 mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath, 15306 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 15307 } catch (InstallerException e) { 15308 return false; 15309 } 15310 15311 // Fix-up for forward-locked applications in ASEC containers. 15312 if (!isExternal(p)) { 15313 pStats.codeSize += pStats.externalCodeSize; 15314 pStats.externalCodeSize = 0L; 15315 } 15316 15317 return true; 15318 } 15319 15320 15321 @Override 15322 public void addPackageToPreferred(String packageName) { 15323 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 15324 } 15325 15326 @Override 15327 public void removePackageFromPreferred(String packageName) { 15328 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 15329 } 15330 15331 @Override 15332 public List<PackageInfo> getPreferredPackages(int flags) { 15333 return new ArrayList<PackageInfo>(); 15334 } 15335 15336 private int getUidTargetSdkVersionLockedLPr(int uid) { 15337 Object obj = mSettings.getUserIdLPr(uid); 15338 if (obj instanceof SharedUserSetting) { 15339 final SharedUserSetting sus = (SharedUserSetting) obj; 15340 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 15341 final Iterator<PackageSetting> it = sus.packages.iterator(); 15342 while (it.hasNext()) { 15343 final PackageSetting ps = it.next(); 15344 if (ps.pkg != null) { 15345 int v = ps.pkg.applicationInfo.targetSdkVersion; 15346 if (v < vers) vers = v; 15347 } 15348 } 15349 return vers; 15350 } else if (obj instanceof PackageSetting) { 15351 final PackageSetting ps = (PackageSetting) obj; 15352 if (ps.pkg != null) { 15353 return ps.pkg.applicationInfo.targetSdkVersion; 15354 } 15355 } 15356 return Build.VERSION_CODES.CUR_DEVELOPMENT; 15357 } 15358 15359 @Override 15360 public void addPreferredActivity(IntentFilter filter, int match, 15361 ComponentName[] set, ComponentName activity, int userId) { 15362 addPreferredActivityInternal(filter, match, set, activity, true, userId, 15363 "Adding preferred"); 15364 } 15365 15366 private void addPreferredActivityInternal(IntentFilter filter, int match, 15367 ComponentName[] set, ComponentName activity, boolean always, int userId, 15368 String opname) { 15369 // writer 15370 int callingUid = Binder.getCallingUid(); 15371 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 15372 if (filter.countActions() == 0) { 15373 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 15374 return; 15375 } 15376 synchronized (mPackages) { 15377 if (mContext.checkCallingOrSelfPermission( 15378 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15379 != PackageManager.PERMISSION_GRANTED) { 15380 if (getUidTargetSdkVersionLockedLPr(callingUid) 15381 < Build.VERSION_CODES.FROYO) { 15382 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 15383 + callingUid); 15384 return; 15385 } 15386 mContext.enforceCallingOrSelfPermission( 15387 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15388 } 15389 15390 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 15391 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 15392 + userId + ":"); 15393 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15394 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 15395 scheduleWritePackageRestrictionsLocked(userId); 15396 } 15397 } 15398 15399 @Override 15400 public void replacePreferredActivity(IntentFilter filter, int match, 15401 ComponentName[] set, ComponentName activity, int userId) { 15402 if (filter.countActions() != 1) { 15403 throw new IllegalArgumentException( 15404 "replacePreferredActivity expects filter to have only 1 action."); 15405 } 15406 if (filter.countDataAuthorities() != 0 15407 || filter.countDataPaths() != 0 15408 || filter.countDataSchemes() > 1 15409 || filter.countDataTypes() != 0) { 15410 throw new IllegalArgumentException( 15411 "replacePreferredActivity expects filter to have no data authorities, " + 15412 "paths, or types; and at most one scheme."); 15413 } 15414 15415 final int callingUid = Binder.getCallingUid(); 15416 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 15417 synchronized (mPackages) { 15418 if (mContext.checkCallingOrSelfPermission( 15419 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15420 != PackageManager.PERMISSION_GRANTED) { 15421 if (getUidTargetSdkVersionLockedLPr(callingUid) 15422 < Build.VERSION_CODES.FROYO) { 15423 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 15424 + Binder.getCallingUid()); 15425 return; 15426 } 15427 mContext.enforceCallingOrSelfPermission( 15428 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15429 } 15430 15431 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 15432 if (pir != null) { 15433 // Get all of the existing entries that exactly match this filter. 15434 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 15435 if (existing != null && existing.size() == 1) { 15436 PreferredActivity cur = existing.get(0); 15437 if (DEBUG_PREFERRED) { 15438 Slog.i(TAG, "Checking replace of preferred:"); 15439 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15440 if (!cur.mPref.mAlways) { 15441 Slog.i(TAG, " -- CUR; not mAlways!"); 15442 } else { 15443 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 15444 Slog.i(TAG, " -- CUR: mSet=" 15445 + Arrays.toString(cur.mPref.mSetComponents)); 15446 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 15447 Slog.i(TAG, " -- NEW: mMatch=" 15448 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 15449 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 15450 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 15451 } 15452 } 15453 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 15454 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 15455 && cur.mPref.sameSet(set)) { 15456 // Setting the preferred activity to what it happens to be already 15457 if (DEBUG_PREFERRED) { 15458 Slog.i(TAG, "Replacing with same preferred activity " 15459 + cur.mPref.mShortComponent + " for user " 15460 + userId + ":"); 15461 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15462 } 15463 return; 15464 } 15465 } 15466 15467 if (existing != null) { 15468 if (DEBUG_PREFERRED) { 15469 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 15470 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15471 } 15472 for (int i = 0; i < existing.size(); i++) { 15473 PreferredActivity pa = existing.get(i); 15474 if (DEBUG_PREFERRED) { 15475 Slog.i(TAG, "Removing existing preferred activity " 15476 + pa.mPref.mComponent + ":"); 15477 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 15478 } 15479 pir.removeFilter(pa); 15480 } 15481 } 15482 } 15483 addPreferredActivityInternal(filter, match, set, activity, true, userId, 15484 "Replacing preferred"); 15485 } 15486 } 15487 15488 @Override 15489 public void clearPackagePreferredActivities(String packageName) { 15490 final int uid = Binder.getCallingUid(); 15491 // writer 15492 synchronized (mPackages) { 15493 PackageParser.Package pkg = mPackages.get(packageName); 15494 if (pkg == null || pkg.applicationInfo.uid != uid) { 15495 if (mContext.checkCallingOrSelfPermission( 15496 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15497 != PackageManager.PERMISSION_GRANTED) { 15498 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 15499 < Build.VERSION_CODES.FROYO) { 15500 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 15501 + Binder.getCallingUid()); 15502 return; 15503 } 15504 mContext.enforceCallingOrSelfPermission( 15505 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15506 } 15507 } 15508 15509 int user = UserHandle.getCallingUserId(); 15510 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 15511 scheduleWritePackageRestrictionsLocked(user); 15512 } 15513 } 15514 } 15515 15516 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15517 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 15518 ArrayList<PreferredActivity> removed = null; 15519 boolean changed = false; 15520 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15521 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 15522 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15523 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 15524 continue; 15525 } 15526 Iterator<PreferredActivity> it = pir.filterIterator(); 15527 while (it.hasNext()) { 15528 PreferredActivity pa = it.next(); 15529 // Mark entry for removal only if it matches the package name 15530 // and the entry is of type "always". 15531 if (packageName == null || 15532 (pa.mPref.mComponent.getPackageName().equals(packageName) 15533 && pa.mPref.mAlways)) { 15534 if (removed == null) { 15535 removed = new ArrayList<PreferredActivity>(); 15536 } 15537 removed.add(pa); 15538 } 15539 } 15540 if (removed != null) { 15541 for (int j=0; j<removed.size(); j++) { 15542 PreferredActivity pa = removed.get(j); 15543 pir.removeFilter(pa); 15544 } 15545 changed = true; 15546 } 15547 } 15548 return changed; 15549 } 15550 15551 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15552 private void clearIntentFilterVerificationsLPw(int userId) { 15553 final int packageCount = mPackages.size(); 15554 for (int i = 0; i < packageCount; i++) { 15555 PackageParser.Package pkg = mPackages.valueAt(i); 15556 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 15557 } 15558 } 15559 15560 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15561 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 15562 if (userId == UserHandle.USER_ALL) { 15563 if (mSettings.removeIntentFilterVerificationLPw(packageName, 15564 sUserManager.getUserIds())) { 15565 for (int oneUserId : sUserManager.getUserIds()) { 15566 scheduleWritePackageRestrictionsLocked(oneUserId); 15567 } 15568 } 15569 } else { 15570 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 15571 scheduleWritePackageRestrictionsLocked(userId); 15572 } 15573 } 15574 } 15575 15576 void clearDefaultBrowserIfNeeded(String packageName) { 15577 for (int oneUserId : sUserManager.getUserIds()) { 15578 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 15579 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 15580 if (packageName.equals(defaultBrowserPackageName)) { 15581 setDefaultBrowserPackageName(null, oneUserId); 15582 } 15583 } 15584 } 15585 15586 @Override 15587 public void resetApplicationPreferences(int userId) { 15588 mContext.enforceCallingOrSelfPermission( 15589 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15590 // writer 15591 synchronized (mPackages) { 15592 final long identity = Binder.clearCallingIdentity(); 15593 try { 15594 clearPackagePreferredActivitiesLPw(null, userId); 15595 mSettings.applyDefaultPreferredAppsLPw(this, userId); 15596 // TODO: We have to reset the default SMS and Phone. This requires 15597 // significant refactoring to keep all default apps in the package 15598 // manager (cleaner but more work) or have the services provide 15599 // callbacks to the package manager to request a default app reset. 15600 applyFactoryDefaultBrowserLPw(userId); 15601 clearIntentFilterVerificationsLPw(userId); 15602 primeDomainVerificationsLPw(userId); 15603 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 15604 scheduleWritePackageRestrictionsLocked(userId); 15605 } finally { 15606 Binder.restoreCallingIdentity(identity); 15607 } 15608 } 15609 } 15610 15611 @Override 15612 public int getPreferredActivities(List<IntentFilter> outFilters, 15613 List<ComponentName> outActivities, String packageName) { 15614 15615 int num = 0; 15616 final int userId = UserHandle.getCallingUserId(); 15617 // reader 15618 synchronized (mPackages) { 15619 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 15620 if (pir != null) { 15621 final Iterator<PreferredActivity> it = pir.filterIterator(); 15622 while (it.hasNext()) { 15623 final PreferredActivity pa = it.next(); 15624 if (packageName == null 15625 || (pa.mPref.mComponent.getPackageName().equals(packageName) 15626 && pa.mPref.mAlways)) { 15627 if (outFilters != null) { 15628 outFilters.add(new IntentFilter(pa)); 15629 } 15630 if (outActivities != null) { 15631 outActivities.add(pa.mPref.mComponent); 15632 } 15633 } 15634 } 15635 } 15636 } 15637 15638 return num; 15639 } 15640 15641 @Override 15642 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 15643 int userId) { 15644 int callingUid = Binder.getCallingUid(); 15645 if (callingUid != Process.SYSTEM_UID) { 15646 throw new SecurityException( 15647 "addPersistentPreferredActivity can only be run by the system"); 15648 } 15649 if (filter.countActions() == 0) { 15650 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 15651 return; 15652 } 15653 synchronized (mPackages) { 15654 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 15655 ":"); 15656 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15657 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 15658 new PersistentPreferredActivity(filter, activity)); 15659 scheduleWritePackageRestrictionsLocked(userId); 15660 } 15661 } 15662 15663 @Override 15664 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 15665 int callingUid = Binder.getCallingUid(); 15666 if (callingUid != Process.SYSTEM_UID) { 15667 throw new SecurityException( 15668 "clearPackagePersistentPreferredActivities can only be run by the system"); 15669 } 15670 ArrayList<PersistentPreferredActivity> removed = null; 15671 boolean changed = false; 15672 synchronized (mPackages) { 15673 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 15674 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 15675 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 15676 .valueAt(i); 15677 if (userId != thisUserId) { 15678 continue; 15679 } 15680 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 15681 while (it.hasNext()) { 15682 PersistentPreferredActivity ppa = it.next(); 15683 // Mark entry for removal only if it matches the package name. 15684 if (ppa.mComponent.getPackageName().equals(packageName)) { 15685 if (removed == null) { 15686 removed = new ArrayList<PersistentPreferredActivity>(); 15687 } 15688 removed.add(ppa); 15689 } 15690 } 15691 if (removed != null) { 15692 for (int j=0; j<removed.size(); j++) { 15693 PersistentPreferredActivity ppa = removed.get(j); 15694 ppir.removeFilter(ppa); 15695 } 15696 changed = true; 15697 } 15698 } 15699 15700 if (changed) { 15701 scheduleWritePackageRestrictionsLocked(userId); 15702 } 15703 } 15704 } 15705 15706 /** 15707 * Common machinery for picking apart a restored XML blob and passing 15708 * it to a caller-supplied functor to be applied to the running system. 15709 */ 15710 private void restoreFromXml(XmlPullParser parser, int userId, 15711 String expectedStartTag, BlobXmlRestorer functor) 15712 throws IOException, XmlPullParserException { 15713 int type; 15714 while ((type = parser.next()) != XmlPullParser.START_TAG 15715 && type != XmlPullParser.END_DOCUMENT) { 15716 } 15717 if (type != XmlPullParser.START_TAG) { 15718 // oops didn't find a start tag?! 15719 if (DEBUG_BACKUP) { 15720 Slog.e(TAG, "Didn't find start tag during restore"); 15721 } 15722 return; 15723 } 15724Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 15725 // this is supposed to be TAG_PREFERRED_BACKUP 15726 if (!expectedStartTag.equals(parser.getName())) { 15727 if (DEBUG_BACKUP) { 15728 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 15729 } 15730 return; 15731 } 15732 15733 // skip interfering stuff, then we're aligned with the backing implementation 15734 while ((type = parser.next()) == XmlPullParser.TEXT) { } 15735Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 15736 functor.apply(parser, userId); 15737 } 15738 15739 private interface BlobXmlRestorer { 15740 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 15741 } 15742 15743 /** 15744 * Non-Binder method, support for the backup/restore mechanism: write the 15745 * full set of preferred activities in its canonical XML format. Returns the 15746 * XML output as a byte array, or null if there is none. 15747 */ 15748 @Override 15749 public byte[] getPreferredActivityBackup(int userId) { 15750 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15751 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 15752 } 15753 15754 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 15755 try { 15756 final XmlSerializer serializer = new FastXmlSerializer(); 15757 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 15758 serializer.startDocument(null, true); 15759 serializer.startTag(null, TAG_PREFERRED_BACKUP); 15760 15761 synchronized (mPackages) { 15762 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 15763 } 15764 15765 serializer.endTag(null, TAG_PREFERRED_BACKUP); 15766 serializer.endDocument(); 15767 serializer.flush(); 15768 } catch (Exception e) { 15769 if (DEBUG_BACKUP) { 15770 Slog.e(TAG, "Unable to write preferred activities for backup", e); 15771 } 15772 return null; 15773 } 15774 15775 return dataStream.toByteArray(); 15776 } 15777 15778 @Override 15779 public void restorePreferredActivities(byte[] backup, int userId) { 15780 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15781 throw new SecurityException("Only the system may call restorePreferredActivities()"); 15782 } 15783 15784 try { 15785 final XmlPullParser parser = Xml.newPullParser(); 15786 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 15787 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 15788 new BlobXmlRestorer() { 15789 @Override 15790 public void apply(XmlPullParser parser, int userId) 15791 throws XmlPullParserException, IOException { 15792 synchronized (mPackages) { 15793 mSettings.readPreferredActivitiesLPw(parser, userId); 15794 } 15795 } 15796 } ); 15797 } catch (Exception e) { 15798 if (DEBUG_BACKUP) { 15799 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 15800 } 15801 } 15802 } 15803 15804 /** 15805 * Non-Binder method, support for the backup/restore mechanism: write the 15806 * default browser (etc) settings in its canonical XML format. Returns the default 15807 * browser XML representation as a byte array, or null if there is none. 15808 */ 15809 @Override 15810 public byte[] getDefaultAppsBackup(int userId) { 15811 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15812 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 15813 } 15814 15815 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 15816 try { 15817 final XmlSerializer serializer = new FastXmlSerializer(); 15818 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 15819 serializer.startDocument(null, true); 15820 serializer.startTag(null, TAG_DEFAULT_APPS); 15821 15822 synchronized (mPackages) { 15823 mSettings.writeDefaultAppsLPr(serializer, userId); 15824 } 15825 15826 serializer.endTag(null, TAG_DEFAULT_APPS); 15827 serializer.endDocument(); 15828 serializer.flush(); 15829 } catch (Exception e) { 15830 if (DEBUG_BACKUP) { 15831 Slog.e(TAG, "Unable to write default apps for backup", e); 15832 } 15833 return null; 15834 } 15835 15836 return dataStream.toByteArray(); 15837 } 15838 15839 @Override 15840 public void restoreDefaultApps(byte[] backup, int userId) { 15841 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15842 throw new SecurityException("Only the system may call restoreDefaultApps()"); 15843 } 15844 15845 try { 15846 final XmlPullParser parser = Xml.newPullParser(); 15847 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 15848 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 15849 new BlobXmlRestorer() { 15850 @Override 15851 public void apply(XmlPullParser parser, int userId) 15852 throws XmlPullParserException, IOException { 15853 synchronized (mPackages) { 15854 mSettings.readDefaultAppsLPw(parser, userId); 15855 } 15856 } 15857 } ); 15858 } catch (Exception e) { 15859 if (DEBUG_BACKUP) { 15860 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 15861 } 15862 } 15863 } 15864 15865 @Override 15866 public byte[] getIntentFilterVerificationBackup(int userId) { 15867 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15868 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 15869 } 15870 15871 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 15872 try { 15873 final XmlSerializer serializer = new FastXmlSerializer(); 15874 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 15875 serializer.startDocument(null, true); 15876 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 15877 15878 synchronized (mPackages) { 15879 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 15880 } 15881 15882 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 15883 serializer.endDocument(); 15884 serializer.flush(); 15885 } catch (Exception e) { 15886 if (DEBUG_BACKUP) { 15887 Slog.e(TAG, "Unable to write default apps for backup", e); 15888 } 15889 return null; 15890 } 15891 15892 return dataStream.toByteArray(); 15893 } 15894 15895 @Override 15896 public void restoreIntentFilterVerification(byte[] backup, int userId) { 15897 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15898 throw new SecurityException("Only the system may call restorePreferredActivities()"); 15899 } 15900 15901 try { 15902 final XmlPullParser parser = Xml.newPullParser(); 15903 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 15904 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 15905 new BlobXmlRestorer() { 15906 @Override 15907 public void apply(XmlPullParser parser, int userId) 15908 throws XmlPullParserException, IOException { 15909 synchronized (mPackages) { 15910 mSettings.readAllDomainVerificationsLPr(parser, userId); 15911 mSettings.writeLPr(); 15912 } 15913 } 15914 } ); 15915 } catch (Exception e) { 15916 if (DEBUG_BACKUP) { 15917 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 15918 } 15919 } 15920 } 15921 15922 @Override 15923 public byte[] getPermissionGrantBackup(int userId) { 15924 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15925 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 15926 } 15927 15928 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 15929 try { 15930 final XmlSerializer serializer = new FastXmlSerializer(); 15931 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 15932 serializer.startDocument(null, true); 15933 serializer.startTag(null, TAG_PERMISSION_BACKUP); 15934 15935 synchronized (mPackages) { 15936 serializeRuntimePermissionGrantsLPr(serializer, userId); 15937 } 15938 15939 serializer.endTag(null, TAG_PERMISSION_BACKUP); 15940 serializer.endDocument(); 15941 serializer.flush(); 15942 } catch (Exception e) { 15943 if (DEBUG_BACKUP) { 15944 Slog.e(TAG, "Unable to write default apps for backup", e); 15945 } 15946 return null; 15947 } 15948 15949 return dataStream.toByteArray(); 15950 } 15951 15952 @Override 15953 public void restorePermissionGrants(byte[] backup, int userId) { 15954 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15955 throw new SecurityException("Only the system may call restorePermissionGrants()"); 15956 } 15957 15958 try { 15959 final XmlPullParser parser = Xml.newPullParser(); 15960 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 15961 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 15962 new BlobXmlRestorer() { 15963 @Override 15964 public void apply(XmlPullParser parser, int userId) 15965 throws XmlPullParserException, IOException { 15966 synchronized (mPackages) { 15967 processRestoredPermissionGrantsLPr(parser, userId); 15968 } 15969 } 15970 } ); 15971 } catch (Exception e) { 15972 if (DEBUG_BACKUP) { 15973 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 15974 } 15975 } 15976 } 15977 15978 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 15979 throws IOException { 15980 serializer.startTag(null, TAG_ALL_GRANTS); 15981 15982 final int N = mSettings.mPackages.size(); 15983 for (int i = 0; i < N; i++) { 15984 final PackageSetting ps = mSettings.mPackages.valueAt(i); 15985 boolean pkgGrantsKnown = false; 15986 15987 PermissionsState packagePerms = ps.getPermissionsState(); 15988 15989 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 15990 final int grantFlags = state.getFlags(); 15991 // only look at grants that are not system/policy fixed 15992 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 15993 final boolean isGranted = state.isGranted(); 15994 // And only back up the user-twiddled state bits 15995 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 15996 final String packageName = mSettings.mPackages.keyAt(i); 15997 if (!pkgGrantsKnown) { 15998 serializer.startTag(null, TAG_GRANT); 15999 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 16000 pkgGrantsKnown = true; 16001 } 16002 16003 final boolean userSet = 16004 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 16005 final boolean userFixed = 16006 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 16007 final boolean revoke = 16008 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 16009 16010 serializer.startTag(null, TAG_PERMISSION); 16011 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 16012 if (isGranted) { 16013 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 16014 } 16015 if (userSet) { 16016 serializer.attribute(null, ATTR_USER_SET, "true"); 16017 } 16018 if (userFixed) { 16019 serializer.attribute(null, ATTR_USER_FIXED, "true"); 16020 } 16021 if (revoke) { 16022 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 16023 } 16024 serializer.endTag(null, TAG_PERMISSION); 16025 } 16026 } 16027 } 16028 16029 if (pkgGrantsKnown) { 16030 serializer.endTag(null, TAG_GRANT); 16031 } 16032 } 16033 16034 serializer.endTag(null, TAG_ALL_GRANTS); 16035 } 16036 16037 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 16038 throws XmlPullParserException, IOException { 16039 String pkgName = null; 16040 int outerDepth = parser.getDepth(); 16041 int type; 16042 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 16043 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 16044 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 16045 continue; 16046 } 16047 16048 final String tagName = parser.getName(); 16049 if (tagName.equals(TAG_GRANT)) { 16050 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 16051 if (DEBUG_BACKUP) { 16052 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 16053 } 16054 } else if (tagName.equals(TAG_PERMISSION)) { 16055 16056 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 16057 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 16058 16059 int newFlagSet = 0; 16060 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 16061 newFlagSet |= FLAG_PERMISSION_USER_SET; 16062 } 16063 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 16064 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 16065 } 16066 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 16067 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 16068 } 16069 if (DEBUG_BACKUP) { 16070 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 16071 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 16072 } 16073 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16074 if (ps != null) { 16075 // Already installed so we apply the grant immediately 16076 if (DEBUG_BACKUP) { 16077 Slog.v(TAG, " + already installed; applying"); 16078 } 16079 PermissionsState perms = ps.getPermissionsState(); 16080 BasePermission bp = mSettings.mPermissions.get(permName); 16081 if (bp != null) { 16082 if (isGranted) { 16083 perms.grantRuntimePermission(bp, userId); 16084 } 16085 if (newFlagSet != 0) { 16086 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 16087 } 16088 } 16089 } else { 16090 // Need to wait for post-restore install to apply the grant 16091 if (DEBUG_BACKUP) { 16092 Slog.v(TAG, " - not yet installed; saving for later"); 16093 } 16094 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 16095 isGranted, newFlagSet, userId); 16096 } 16097 } else { 16098 PackageManagerService.reportSettingsProblem(Log.WARN, 16099 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 16100 XmlUtils.skipCurrentTag(parser); 16101 } 16102 } 16103 16104 scheduleWriteSettingsLocked(); 16105 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16106 } 16107 16108 @Override 16109 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 16110 int sourceUserId, int targetUserId, int flags) { 16111 mContext.enforceCallingOrSelfPermission( 16112 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16113 int callingUid = Binder.getCallingUid(); 16114 enforceOwnerRights(ownerPackage, callingUid); 16115 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16116 if (intentFilter.countActions() == 0) { 16117 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 16118 return; 16119 } 16120 synchronized (mPackages) { 16121 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 16122 ownerPackage, targetUserId, flags); 16123 CrossProfileIntentResolver resolver = 16124 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16125 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 16126 // We have all those whose filter is equal. Now checking if the rest is equal as well. 16127 if (existing != null) { 16128 int size = existing.size(); 16129 for (int i = 0; i < size; i++) { 16130 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 16131 return; 16132 } 16133 } 16134 } 16135 resolver.addFilter(newFilter); 16136 scheduleWritePackageRestrictionsLocked(sourceUserId); 16137 } 16138 } 16139 16140 @Override 16141 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 16142 mContext.enforceCallingOrSelfPermission( 16143 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16144 int callingUid = Binder.getCallingUid(); 16145 enforceOwnerRights(ownerPackage, callingUid); 16146 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16147 synchronized (mPackages) { 16148 CrossProfileIntentResolver resolver = 16149 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16150 ArraySet<CrossProfileIntentFilter> set = 16151 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 16152 for (CrossProfileIntentFilter filter : set) { 16153 if (filter.getOwnerPackage().equals(ownerPackage)) { 16154 resolver.removeFilter(filter); 16155 } 16156 } 16157 scheduleWritePackageRestrictionsLocked(sourceUserId); 16158 } 16159 } 16160 16161 // Enforcing that callingUid is owning pkg on userId 16162 private void enforceOwnerRights(String pkg, int callingUid) { 16163 // The system owns everything. 16164 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 16165 return; 16166 } 16167 int callingUserId = UserHandle.getUserId(callingUid); 16168 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 16169 if (pi == null) { 16170 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 16171 + callingUserId); 16172 } 16173 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 16174 throw new SecurityException("Calling uid " + callingUid 16175 + " does not own package " + pkg); 16176 } 16177 } 16178 16179 @Override 16180 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 16181 Intent intent = new Intent(Intent.ACTION_MAIN); 16182 intent.addCategory(Intent.CATEGORY_HOME); 16183 16184 final int callingUserId = UserHandle.getCallingUserId(); 16185 List<ResolveInfo> list = queryIntentActivities(intent, null, 16186 PackageManager.GET_META_DATA, callingUserId); 16187 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 16188 true, false, false, callingUserId); 16189 16190 allHomeCandidates.clear(); 16191 if (list != null) { 16192 for (ResolveInfo ri : list) { 16193 allHomeCandidates.add(ri); 16194 } 16195 } 16196 return (preferred == null || preferred.activityInfo == null) 16197 ? null 16198 : new ComponentName(preferred.activityInfo.packageName, 16199 preferred.activityInfo.name); 16200 } 16201 16202 @Override 16203 public void setApplicationEnabledSetting(String appPackageName, 16204 int newState, int flags, int userId, String callingPackage) { 16205 if (!sUserManager.exists(userId)) return; 16206 if (callingPackage == null) { 16207 callingPackage = Integer.toString(Binder.getCallingUid()); 16208 } 16209 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 16210 } 16211 16212 @Override 16213 public void setComponentEnabledSetting(ComponentName componentName, 16214 int newState, int flags, int userId) { 16215 if (!sUserManager.exists(userId)) return; 16216 setEnabledSetting(componentName.getPackageName(), 16217 componentName.getClassName(), newState, flags, userId, null); 16218 } 16219 16220 private void setEnabledSetting(final String packageName, String className, int newState, 16221 final int flags, int userId, String callingPackage) { 16222 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 16223 || newState == COMPONENT_ENABLED_STATE_ENABLED 16224 || newState == COMPONENT_ENABLED_STATE_DISABLED 16225 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 16226 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 16227 throw new IllegalArgumentException("Invalid new component state: " 16228 + newState); 16229 } 16230 PackageSetting pkgSetting; 16231 final int uid = Binder.getCallingUid(); 16232 final int permission = mContext.checkCallingOrSelfPermission( 16233 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 16234 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 16235 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 16236 boolean sendNow = false; 16237 boolean isApp = (className == null); 16238 String componentName = isApp ? packageName : className; 16239 int packageUid = -1; 16240 ArrayList<String> components; 16241 16242 // writer 16243 synchronized (mPackages) { 16244 pkgSetting = mSettings.mPackages.get(packageName); 16245 if (pkgSetting == null) { 16246 if (className == null) { 16247 throw new IllegalArgumentException("Unknown package: " + packageName); 16248 } 16249 throw new IllegalArgumentException( 16250 "Unknown component: " + packageName + "/" + className); 16251 } 16252 // Allow root and verify that userId is not being specified by a different user 16253 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 16254 throw new SecurityException( 16255 "Permission Denial: attempt to change component state from pid=" 16256 + Binder.getCallingPid() 16257 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 16258 } 16259 if (className == null) { 16260 // We're dealing with an application/package level state change 16261 if (pkgSetting.getEnabled(userId) == newState) { 16262 // Nothing to do 16263 return; 16264 } 16265 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 16266 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 16267 // Don't care about who enables an app. 16268 callingPackage = null; 16269 } 16270 pkgSetting.setEnabled(newState, userId, callingPackage); 16271 // pkgSetting.pkg.mSetEnabled = newState; 16272 } else { 16273 // We're dealing with a component level state change 16274 // First, verify that this is a valid class name. 16275 PackageParser.Package pkg = pkgSetting.pkg; 16276 if (pkg == null || !pkg.hasComponentClassName(className)) { 16277 if (pkg != null && 16278 pkg.applicationInfo.targetSdkVersion >= 16279 Build.VERSION_CODES.JELLY_BEAN) { 16280 throw new IllegalArgumentException("Component class " + className 16281 + " does not exist in " + packageName); 16282 } else { 16283 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 16284 + className + " does not exist in " + packageName); 16285 } 16286 } 16287 switch (newState) { 16288 case COMPONENT_ENABLED_STATE_ENABLED: 16289 if (!pkgSetting.enableComponentLPw(className, userId)) { 16290 return; 16291 } 16292 break; 16293 case COMPONENT_ENABLED_STATE_DISABLED: 16294 if (!pkgSetting.disableComponentLPw(className, userId)) { 16295 return; 16296 } 16297 break; 16298 case COMPONENT_ENABLED_STATE_DEFAULT: 16299 if (!pkgSetting.restoreComponentLPw(className, userId)) { 16300 return; 16301 } 16302 break; 16303 default: 16304 Slog.e(TAG, "Invalid new component state: " + newState); 16305 return; 16306 } 16307 } 16308 scheduleWritePackageRestrictionsLocked(userId); 16309 components = mPendingBroadcasts.get(userId, packageName); 16310 final boolean newPackage = components == null; 16311 if (newPackage) { 16312 components = new ArrayList<String>(); 16313 } 16314 if (!components.contains(componentName)) { 16315 components.add(componentName); 16316 } 16317 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 16318 sendNow = true; 16319 // Purge entry from pending broadcast list if another one exists already 16320 // since we are sending one right away. 16321 mPendingBroadcasts.remove(userId, packageName); 16322 } else { 16323 if (newPackage) { 16324 mPendingBroadcasts.put(userId, packageName, components); 16325 } 16326 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 16327 // Schedule a message 16328 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 16329 } 16330 } 16331 } 16332 16333 long callingId = Binder.clearCallingIdentity(); 16334 try { 16335 if (sendNow) { 16336 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 16337 sendPackageChangedBroadcast(packageName, 16338 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 16339 } 16340 } finally { 16341 Binder.restoreCallingIdentity(callingId); 16342 } 16343 } 16344 16345 private void sendPackageChangedBroadcast(String packageName, 16346 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 16347 if (DEBUG_INSTALL) 16348 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 16349 + componentNames); 16350 Bundle extras = new Bundle(4); 16351 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 16352 String nameList[] = new String[componentNames.size()]; 16353 componentNames.toArray(nameList); 16354 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 16355 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 16356 extras.putInt(Intent.EXTRA_UID, packageUid); 16357 // If this is not reporting a change of the overall package, then only send it 16358 // to registered receivers. We don't want to launch a swath of apps for every 16359 // little component state change. 16360 final int flags = !componentNames.contains(packageName) 16361 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 16362 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 16363 new int[] {UserHandle.getUserId(packageUid)}); 16364 } 16365 16366 @Override 16367 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 16368 if (!sUserManager.exists(userId)) return; 16369 final int uid = Binder.getCallingUid(); 16370 final int permission = mContext.checkCallingOrSelfPermission( 16371 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 16372 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 16373 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 16374 // writer 16375 synchronized (mPackages) { 16376 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 16377 allowedByPermission, uid, userId)) { 16378 scheduleWritePackageRestrictionsLocked(userId); 16379 } 16380 } 16381 } 16382 16383 @Override 16384 public String getInstallerPackageName(String packageName) { 16385 // reader 16386 synchronized (mPackages) { 16387 return mSettings.getInstallerPackageNameLPr(packageName); 16388 } 16389 } 16390 16391 @Override 16392 public int getApplicationEnabledSetting(String packageName, int userId) { 16393 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 16394 int uid = Binder.getCallingUid(); 16395 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 16396 // reader 16397 synchronized (mPackages) { 16398 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 16399 } 16400 } 16401 16402 @Override 16403 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 16404 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 16405 int uid = Binder.getCallingUid(); 16406 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 16407 // reader 16408 synchronized (mPackages) { 16409 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 16410 } 16411 } 16412 16413 @Override 16414 public void enterSafeMode() { 16415 enforceSystemOrRoot("Only the system can request entering safe mode"); 16416 16417 if (!mSystemReady) { 16418 mSafeMode = true; 16419 } 16420 } 16421 16422 @Override 16423 public void systemReady() { 16424 mSystemReady = true; 16425 16426 // Read the compatibilty setting when the system is ready. 16427 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 16428 mContext.getContentResolver(), 16429 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 16430 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 16431 if (DEBUG_SETTINGS) { 16432 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 16433 } 16434 16435 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 16436 16437 synchronized (mPackages) { 16438 // Verify that all of the preferred activity components actually 16439 // exist. It is possible for applications to be updated and at 16440 // that point remove a previously declared activity component that 16441 // had been set as a preferred activity. We try to clean this up 16442 // the next time we encounter that preferred activity, but it is 16443 // possible for the user flow to never be able to return to that 16444 // situation so here we do a sanity check to make sure we haven't 16445 // left any junk around. 16446 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 16447 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16448 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16449 removed.clear(); 16450 for (PreferredActivity pa : pir.filterSet()) { 16451 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 16452 removed.add(pa); 16453 } 16454 } 16455 if (removed.size() > 0) { 16456 for (int r=0; r<removed.size(); r++) { 16457 PreferredActivity pa = removed.get(r); 16458 Slog.w(TAG, "Removing dangling preferred activity: " 16459 + pa.mPref.mComponent); 16460 pir.removeFilter(pa); 16461 } 16462 mSettings.writePackageRestrictionsLPr( 16463 mSettings.mPreferredActivities.keyAt(i)); 16464 } 16465 } 16466 16467 for (int userId : UserManagerService.getInstance().getUserIds()) { 16468 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 16469 grantPermissionsUserIds = ArrayUtils.appendInt( 16470 grantPermissionsUserIds, userId); 16471 } 16472 } 16473 } 16474 sUserManager.systemReady(); 16475 16476 // If we upgraded grant all default permissions before kicking off. 16477 for (int userId : grantPermissionsUserIds) { 16478 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 16479 } 16480 16481 // Kick off any messages waiting for system ready 16482 if (mPostSystemReadyMessages != null) { 16483 for (Message msg : mPostSystemReadyMessages) { 16484 msg.sendToTarget(); 16485 } 16486 mPostSystemReadyMessages = null; 16487 } 16488 16489 // Watch for external volumes that come and go over time 16490 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16491 storage.registerListener(mStorageListener); 16492 16493 mInstallerService.systemReady(); 16494 mPackageDexOptimizer.systemReady(); 16495 16496 MountServiceInternal mountServiceInternal = LocalServices.getService( 16497 MountServiceInternal.class); 16498 mountServiceInternal.addExternalStoragePolicy( 16499 new MountServiceInternal.ExternalStorageMountPolicy() { 16500 @Override 16501 public int getMountMode(int uid, String packageName) { 16502 if (Process.isIsolated(uid)) { 16503 return Zygote.MOUNT_EXTERNAL_NONE; 16504 } 16505 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 16506 return Zygote.MOUNT_EXTERNAL_DEFAULT; 16507 } 16508 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 16509 return Zygote.MOUNT_EXTERNAL_DEFAULT; 16510 } 16511 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 16512 return Zygote.MOUNT_EXTERNAL_READ; 16513 } 16514 return Zygote.MOUNT_EXTERNAL_WRITE; 16515 } 16516 16517 @Override 16518 public boolean hasExternalStorage(int uid, String packageName) { 16519 return true; 16520 } 16521 }); 16522 } 16523 16524 @Override 16525 public boolean isSafeMode() { 16526 return mSafeMode; 16527 } 16528 16529 @Override 16530 public boolean hasSystemUidErrors() { 16531 return mHasSystemUidErrors; 16532 } 16533 16534 static String arrayToString(int[] array) { 16535 StringBuffer buf = new StringBuffer(128); 16536 buf.append('['); 16537 if (array != null) { 16538 for (int i=0; i<array.length; i++) { 16539 if (i > 0) buf.append(", "); 16540 buf.append(array[i]); 16541 } 16542 } 16543 buf.append(']'); 16544 return buf.toString(); 16545 } 16546 16547 static class DumpState { 16548 public static final int DUMP_LIBS = 1 << 0; 16549 public static final int DUMP_FEATURES = 1 << 1; 16550 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 16551 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 16552 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 16553 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 16554 public static final int DUMP_PERMISSIONS = 1 << 6; 16555 public static final int DUMP_PACKAGES = 1 << 7; 16556 public static final int DUMP_SHARED_USERS = 1 << 8; 16557 public static final int DUMP_MESSAGES = 1 << 9; 16558 public static final int DUMP_PROVIDERS = 1 << 10; 16559 public static final int DUMP_VERIFIERS = 1 << 11; 16560 public static final int DUMP_PREFERRED = 1 << 12; 16561 public static final int DUMP_PREFERRED_XML = 1 << 13; 16562 public static final int DUMP_KEYSETS = 1 << 14; 16563 public static final int DUMP_VERSION = 1 << 15; 16564 public static final int DUMP_INSTALLS = 1 << 16; 16565 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 16566 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 16567 16568 public static final int OPTION_SHOW_FILTERS = 1 << 0; 16569 16570 private int mTypes; 16571 16572 private int mOptions; 16573 16574 private boolean mTitlePrinted; 16575 16576 private SharedUserSetting mSharedUser; 16577 16578 public boolean isDumping(int type) { 16579 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 16580 return true; 16581 } 16582 16583 return (mTypes & type) != 0; 16584 } 16585 16586 public void setDump(int type) { 16587 mTypes |= type; 16588 } 16589 16590 public boolean isOptionEnabled(int option) { 16591 return (mOptions & option) != 0; 16592 } 16593 16594 public void setOptionEnabled(int option) { 16595 mOptions |= option; 16596 } 16597 16598 public boolean onTitlePrinted() { 16599 final boolean printed = mTitlePrinted; 16600 mTitlePrinted = true; 16601 return printed; 16602 } 16603 16604 public boolean getTitlePrinted() { 16605 return mTitlePrinted; 16606 } 16607 16608 public void setTitlePrinted(boolean enabled) { 16609 mTitlePrinted = enabled; 16610 } 16611 16612 public SharedUserSetting getSharedUser() { 16613 return mSharedUser; 16614 } 16615 16616 public void setSharedUser(SharedUserSetting user) { 16617 mSharedUser = user; 16618 } 16619 } 16620 16621 @Override 16622 public void onShellCommand(FileDescriptor in, FileDescriptor out, 16623 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 16624 (new PackageManagerShellCommand(this)).exec( 16625 this, in, out, err, args, resultReceiver); 16626 } 16627 16628 @Override 16629 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 16630 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 16631 != PackageManager.PERMISSION_GRANTED) { 16632 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 16633 + Binder.getCallingPid() 16634 + ", uid=" + Binder.getCallingUid() 16635 + " without permission " 16636 + android.Manifest.permission.DUMP); 16637 return; 16638 } 16639 16640 DumpState dumpState = new DumpState(); 16641 boolean fullPreferred = false; 16642 boolean checkin = false; 16643 16644 String packageName = null; 16645 ArraySet<String> permissionNames = null; 16646 16647 int opti = 0; 16648 while (opti < args.length) { 16649 String opt = args[opti]; 16650 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 16651 break; 16652 } 16653 opti++; 16654 16655 if ("-a".equals(opt)) { 16656 // Right now we only know how to print all. 16657 } else if ("-h".equals(opt)) { 16658 pw.println("Package manager dump options:"); 16659 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 16660 pw.println(" --checkin: dump for a checkin"); 16661 pw.println(" -f: print details of intent filters"); 16662 pw.println(" -h: print this help"); 16663 pw.println(" cmd may be one of:"); 16664 pw.println(" l[ibraries]: list known shared libraries"); 16665 pw.println(" f[eatures]: list device features"); 16666 pw.println(" k[eysets]: print known keysets"); 16667 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 16668 pw.println(" perm[issions]: dump permissions"); 16669 pw.println(" permission [name ...]: dump declaration and use of given permission"); 16670 pw.println(" pref[erred]: print preferred package settings"); 16671 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 16672 pw.println(" prov[iders]: dump content providers"); 16673 pw.println(" p[ackages]: dump installed packages"); 16674 pw.println(" s[hared-users]: dump shared user IDs"); 16675 pw.println(" m[essages]: print collected runtime messages"); 16676 pw.println(" v[erifiers]: print package verifier info"); 16677 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 16678 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 16679 pw.println(" version: print database version info"); 16680 pw.println(" write: write current settings now"); 16681 pw.println(" installs: details about install sessions"); 16682 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 16683 pw.println(" <package.name>: info about given package"); 16684 return; 16685 } else if ("--checkin".equals(opt)) { 16686 checkin = true; 16687 } else if ("-f".equals(opt)) { 16688 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 16689 } else { 16690 pw.println("Unknown argument: " + opt + "; use -h for help"); 16691 } 16692 } 16693 16694 // Is the caller requesting to dump a particular piece of data? 16695 if (opti < args.length) { 16696 String cmd = args[opti]; 16697 opti++; 16698 // Is this a package name? 16699 if ("android".equals(cmd) || cmd.contains(".")) { 16700 packageName = cmd; 16701 // When dumping a single package, we always dump all of its 16702 // filter information since the amount of data will be reasonable. 16703 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 16704 } else if ("check-permission".equals(cmd)) { 16705 if (opti >= args.length) { 16706 pw.println("Error: check-permission missing permission argument"); 16707 return; 16708 } 16709 String perm = args[opti]; 16710 opti++; 16711 if (opti >= args.length) { 16712 pw.println("Error: check-permission missing package argument"); 16713 return; 16714 } 16715 String pkg = args[opti]; 16716 opti++; 16717 int user = UserHandle.getUserId(Binder.getCallingUid()); 16718 if (opti < args.length) { 16719 try { 16720 user = Integer.parseInt(args[opti]); 16721 } catch (NumberFormatException e) { 16722 pw.println("Error: check-permission user argument is not a number: " 16723 + args[opti]); 16724 return; 16725 } 16726 } 16727 pw.println(checkPermission(perm, pkg, user)); 16728 return; 16729 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 16730 dumpState.setDump(DumpState.DUMP_LIBS); 16731 } else if ("f".equals(cmd) || "features".equals(cmd)) { 16732 dumpState.setDump(DumpState.DUMP_FEATURES); 16733 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 16734 if (opti >= args.length) { 16735 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 16736 | DumpState.DUMP_SERVICE_RESOLVERS 16737 | DumpState.DUMP_RECEIVER_RESOLVERS 16738 | DumpState.DUMP_CONTENT_RESOLVERS); 16739 } else { 16740 while (opti < args.length) { 16741 String name = args[opti]; 16742 if ("a".equals(name) || "activity".equals(name)) { 16743 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 16744 } else if ("s".equals(name) || "service".equals(name)) { 16745 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 16746 } else if ("r".equals(name) || "receiver".equals(name)) { 16747 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 16748 } else if ("c".equals(name) || "content".equals(name)) { 16749 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 16750 } else { 16751 pw.println("Error: unknown resolver table type: " + name); 16752 return; 16753 } 16754 opti++; 16755 } 16756 } 16757 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 16758 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 16759 } else if ("permission".equals(cmd)) { 16760 if (opti >= args.length) { 16761 pw.println("Error: permission requires permission name"); 16762 return; 16763 } 16764 permissionNames = new ArraySet<>(); 16765 while (opti < args.length) { 16766 permissionNames.add(args[opti]); 16767 opti++; 16768 } 16769 dumpState.setDump(DumpState.DUMP_PERMISSIONS 16770 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 16771 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 16772 dumpState.setDump(DumpState.DUMP_PREFERRED); 16773 } else if ("preferred-xml".equals(cmd)) { 16774 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 16775 if (opti < args.length && "--full".equals(args[opti])) { 16776 fullPreferred = true; 16777 opti++; 16778 } 16779 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 16780 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 16781 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 16782 dumpState.setDump(DumpState.DUMP_PACKAGES); 16783 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 16784 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 16785 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 16786 dumpState.setDump(DumpState.DUMP_PROVIDERS); 16787 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 16788 dumpState.setDump(DumpState.DUMP_MESSAGES); 16789 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 16790 dumpState.setDump(DumpState.DUMP_VERIFIERS); 16791 } else if ("i".equals(cmd) || "ifv".equals(cmd) 16792 || "intent-filter-verifiers".equals(cmd)) { 16793 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 16794 } else if ("version".equals(cmd)) { 16795 dumpState.setDump(DumpState.DUMP_VERSION); 16796 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 16797 dumpState.setDump(DumpState.DUMP_KEYSETS); 16798 } else if ("installs".equals(cmd)) { 16799 dumpState.setDump(DumpState.DUMP_INSTALLS); 16800 } else if ("write".equals(cmd)) { 16801 synchronized (mPackages) { 16802 mSettings.writeLPr(); 16803 pw.println("Settings written."); 16804 return; 16805 } 16806 } 16807 } 16808 16809 if (checkin) { 16810 pw.println("vers,1"); 16811 } 16812 16813 // reader 16814 synchronized (mPackages) { 16815 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 16816 if (!checkin) { 16817 if (dumpState.onTitlePrinted()) 16818 pw.println(); 16819 pw.println("Database versions:"); 16820 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 16821 } 16822 } 16823 16824 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 16825 if (!checkin) { 16826 if (dumpState.onTitlePrinted()) 16827 pw.println(); 16828 pw.println("Verifiers:"); 16829 pw.print(" Required: "); 16830 pw.print(mRequiredVerifierPackage); 16831 pw.print(" (uid="); 16832 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 16833 UserHandle.USER_SYSTEM)); 16834 pw.println(")"); 16835 } else if (mRequiredVerifierPackage != null) { 16836 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 16837 pw.print(","); 16838 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 16839 UserHandle.USER_SYSTEM)); 16840 } 16841 } 16842 16843 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 16844 packageName == null) { 16845 if (mIntentFilterVerifierComponent != null) { 16846 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 16847 if (!checkin) { 16848 if (dumpState.onTitlePrinted()) 16849 pw.println(); 16850 pw.println("Intent Filter Verifier:"); 16851 pw.print(" Using: "); 16852 pw.print(verifierPackageName); 16853 pw.print(" (uid="); 16854 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 16855 UserHandle.USER_SYSTEM)); 16856 pw.println(")"); 16857 } else if (verifierPackageName != null) { 16858 pw.print("ifv,"); pw.print(verifierPackageName); 16859 pw.print(","); 16860 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 16861 UserHandle.USER_SYSTEM)); 16862 } 16863 } else { 16864 pw.println(); 16865 pw.println("No Intent Filter Verifier available!"); 16866 } 16867 } 16868 16869 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 16870 boolean printedHeader = false; 16871 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 16872 while (it.hasNext()) { 16873 String name = it.next(); 16874 SharedLibraryEntry ent = mSharedLibraries.get(name); 16875 if (!checkin) { 16876 if (!printedHeader) { 16877 if (dumpState.onTitlePrinted()) 16878 pw.println(); 16879 pw.println("Libraries:"); 16880 printedHeader = true; 16881 } 16882 pw.print(" "); 16883 } else { 16884 pw.print("lib,"); 16885 } 16886 pw.print(name); 16887 if (!checkin) { 16888 pw.print(" -> "); 16889 } 16890 if (ent.path != null) { 16891 if (!checkin) { 16892 pw.print("(jar) "); 16893 pw.print(ent.path); 16894 } else { 16895 pw.print(",jar,"); 16896 pw.print(ent.path); 16897 } 16898 } else { 16899 if (!checkin) { 16900 pw.print("(apk) "); 16901 pw.print(ent.apk); 16902 } else { 16903 pw.print(",apk,"); 16904 pw.print(ent.apk); 16905 } 16906 } 16907 pw.println(); 16908 } 16909 } 16910 16911 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 16912 if (dumpState.onTitlePrinted()) 16913 pw.println(); 16914 if (!checkin) { 16915 pw.println("Features:"); 16916 } 16917 16918 for (FeatureInfo feat : mAvailableFeatures.values()) { 16919 if (checkin) { 16920 pw.print("feat,"); 16921 pw.print(feat.name); 16922 pw.print(","); 16923 pw.println(feat.version); 16924 } else { 16925 pw.print(" "); 16926 pw.print(feat.name); 16927 if (feat.version > 0) { 16928 pw.print(" version="); 16929 pw.print(feat.version); 16930 } 16931 pw.println(); 16932 } 16933 } 16934 } 16935 16936 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 16937 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 16938 : "Activity Resolver Table:", " ", packageName, 16939 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16940 dumpState.setTitlePrinted(true); 16941 } 16942 } 16943 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 16944 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 16945 : "Receiver Resolver Table:", " ", packageName, 16946 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16947 dumpState.setTitlePrinted(true); 16948 } 16949 } 16950 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 16951 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 16952 : "Service Resolver Table:", " ", packageName, 16953 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16954 dumpState.setTitlePrinted(true); 16955 } 16956 } 16957 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 16958 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 16959 : "Provider Resolver Table:", " ", packageName, 16960 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16961 dumpState.setTitlePrinted(true); 16962 } 16963 } 16964 16965 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 16966 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16967 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16968 int user = mSettings.mPreferredActivities.keyAt(i); 16969 if (pir.dump(pw, 16970 dumpState.getTitlePrinted() 16971 ? "\nPreferred Activities User " + user + ":" 16972 : "Preferred Activities User " + user + ":", " ", 16973 packageName, true, false)) { 16974 dumpState.setTitlePrinted(true); 16975 } 16976 } 16977 } 16978 16979 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 16980 pw.flush(); 16981 FileOutputStream fout = new FileOutputStream(fd); 16982 BufferedOutputStream str = new BufferedOutputStream(fout); 16983 XmlSerializer serializer = new FastXmlSerializer(); 16984 try { 16985 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 16986 serializer.startDocument(null, true); 16987 serializer.setFeature( 16988 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 16989 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 16990 serializer.endDocument(); 16991 serializer.flush(); 16992 } catch (IllegalArgumentException e) { 16993 pw.println("Failed writing: " + e); 16994 } catch (IllegalStateException e) { 16995 pw.println("Failed writing: " + e); 16996 } catch (IOException e) { 16997 pw.println("Failed writing: " + e); 16998 } 16999 } 17000 17001 if (!checkin 17002 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 17003 && packageName == null) { 17004 pw.println(); 17005 int count = mSettings.mPackages.size(); 17006 if (count == 0) { 17007 pw.println("No applications!"); 17008 pw.println(); 17009 } else { 17010 final String prefix = " "; 17011 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 17012 if (allPackageSettings.size() == 0) { 17013 pw.println("No domain preferred apps!"); 17014 pw.println(); 17015 } else { 17016 pw.println("App verification status:"); 17017 pw.println(); 17018 count = 0; 17019 for (PackageSetting ps : allPackageSettings) { 17020 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 17021 if (ivi == null || ivi.getPackageName() == null) continue; 17022 pw.println(prefix + "Package: " + ivi.getPackageName()); 17023 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 17024 pw.println(prefix + "Status: " + ivi.getStatusString()); 17025 pw.println(); 17026 count++; 17027 } 17028 if (count == 0) { 17029 pw.println(prefix + "No app verification established."); 17030 pw.println(); 17031 } 17032 for (int userId : sUserManager.getUserIds()) { 17033 pw.println("App linkages for user " + userId + ":"); 17034 pw.println(); 17035 count = 0; 17036 for (PackageSetting ps : allPackageSettings) { 17037 final long status = ps.getDomainVerificationStatusForUser(userId); 17038 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 17039 continue; 17040 } 17041 pw.println(prefix + "Package: " + ps.name); 17042 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 17043 String statusStr = IntentFilterVerificationInfo. 17044 getStatusStringFromValue(status); 17045 pw.println(prefix + "Status: " + statusStr); 17046 pw.println(); 17047 count++; 17048 } 17049 if (count == 0) { 17050 pw.println(prefix + "No configured app linkages."); 17051 pw.println(); 17052 } 17053 } 17054 } 17055 } 17056 } 17057 17058 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 17059 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 17060 if (packageName == null && permissionNames == null) { 17061 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 17062 if (iperm == 0) { 17063 if (dumpState.onTitlePrinted()) 17064 pw.println(); 17065 pw.println("AppOp Permissions:"); 17066 } 17067 pw.print(" AppOp Permission "); 17068 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 17069 pw.println(":"); 17070 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 17071 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 17072 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 17073 } 17074 } 17075 } 17076 } 17077 17078 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 17079 boolean printedSomething = false; 17080 for (PackageParser.Provider p : mProviders.mProviders.values()) { 17081 if (packageName != null && !packageName.equals(p.info.packageName)) { 17082 continue; 17083 } 17084 if (!printedSomething) { 17085 if (dumpState.onTitlePrinted()) 17086 pw.println(); 17087 pw.println("Registered ContentProviders:"); 17088 printedSomething = true; 17089 } 17090 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 17091 pw.print(" "); pw.println(p.toString()); 17092 } 17093 printedSomething = false; 17094 for (Map.Entry<String, PackageParser.Provider> entry : 17095 mProvidersByAuthority.entrySet()) { 17096 PackageParser.Provider p = entry.getValue(); 17097 if (packageName != null && !packageName.equals(p.info.packageName)) { 17098 continue; 17099 } 17100 if (!printedSomething) { 17101 if (dumpState.onTitlePrinted()) 17102 pw.println(); 17103 pw.println("ContentProvider Authorities:"); 17104 printedSomething = true; 17105 } 17106 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 17107 pw.print(" "); pw.println(p.toString()); 17108 if (p.info != null && p.info.applicationInfo != null) { 17109 final String appInfo = p.info.applicationInfo.toString(); 17110 pw.print(" applicationInfo="); pw.println(appInfo); 17111 } 17112 } 17113 } 17114 17115 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 17116 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 17117 } 17118 17119 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 17120 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 17121 } 17122 17123 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 17124 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 17125 } 17126 17127 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 17128 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 17129 } 17130 17131 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 17132 // XXX should handle packageName != null by dumping only install data that 17133 // the given package is involved with. 17134 if (dumpState.onTitlePrinted()) pw.println(); 17135 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 17136 } 17137 17138 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 17139 if (dumpState.onTitlePrinted()) pw.println(); 17140 mSettings.dumpReadMessagesLPr(pw, dumpState); 17141 17142 pw.println(); 17143 pw.println("Package warning messages:"); 17144 BufferedReader in = null; 17145 String line = null; 17146 try { 17147 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 17148 while ((line = in.readLine()) != null) { 17149 if (line.contains("ignored: updated version")) continue; 17150 pw.println(line); 17151 } 17152 } catch (IOException ignored) { 17153 } finally { 17154 IoUtils.closeQuietly(in); 17155 } 17156 } 17157 17158 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 17159 BufferedReader in = null; 17160 String line = null; 17161 try { 17162 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 17163 while ((line = in.readLine()) != null) { 17164 if (line.contains("ignored: updated version")) continue; 17165 pw.print("msg,"); 17166 pw.println(line); 17167 } 17168 } catch (IOException ignored) { 17169 } finally { 17170 IoUtils.closeQuietly(in); 17171 } 17172 } 17173 } 17174 } 17175 17176 private String dumpDomainString(String packageName) { 17177 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 17178 List<IntentFilter> filters = getAllIntentFilters(packageName); 17179 17180 ArraySet<String> result = new ArraySet<>(); 17181 if (iviList.size() > 0) { 17182 for (IntentFilterVerificationInfo ivi : iviList) { 17183 for (String host : ivi.getDomains()) { 17184 result.add(host); 17185 } 17186 } 17187 } 17188 if (filters != null && filters.size() > 0) { 17189 for (IntentFilter filter : filters) { 17190 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 17191 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 17192 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 17193 result.addAll(filter.getHostsList()); 17194 } 17195 } 17196 } 17197 17198 StringBuilder sb = new StringBuilder(result.size() * 16); 17199 for (String domain : result) { 17200 if (sb.length() > 0) sb.append(" "); 17201 sb.append(domain); 17202 } 17203 return sb.toString(); 17204 } 17205 17206 // ------- apps on sdcard specific code ------- 17207 static final boolean DEBUG_SD_INSTALL = false; 17208 17209 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 17210 17211 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 17212 17213 private boolean mMediaMounted = false; 17214 17215 static String getEncryptKey() { 17216 try { 17217 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 17218 SD_ENCRYPTION_KEYSTORE_NAME); 17219 if (sdEncKey == null) { 17220 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 17221 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 17222 if (sdEncKey == null) { 17223 Slog.e(TAG, "Failed to create encryption keys"); 17224 return null; 17225 } 17226 } 17227 return sdEncKey; 17228 } catch (NoSuchAlgorithmException nsae) { 17229 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 17230 return null; 17231 } catch (IOException ioe) { 17232 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 17233 return null; 17234 } 17235 } 17236 17237 /* 17238 * Update media status on PackageManager. 17239 */ 17240 @Override 17241 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 17242 int callingUid = Binder.getCallingUid(); 17243 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 17244 throw new SecurityException("Media status can only be updated by the system"); 17245 } 17246 // reader; this apparently protects mMediaMounted, but should probably 17247 // be a different lock in that case. 17248 synchronized (mPackages) { 17249 Log.i(TAG, "Updating external media status from " 17250 + (mMediaMounted ? "mounted" : "unmounted") + " to " 17251 + (mediaStatus ? "mounted" : "unmounted")); 17252 if (DEBUG_SD_INSTALL) 17253 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 17254 + ", mMediaMounted=" + mMediaMounted); 17255 if (mediaStatus == mMediaMounted) { 17256 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 17257 : 0, -1); 17258 mHandler.sendMessage(msg); 17259 return; 17260 } 17261 mMediaMounted = mediaStatus; 17262 } 17263 // Queue up an async operation since the package installation may take a 17264 // little while. 17265 mHandler.post(new Runnable() { 17266 public void run() { 17267 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 17268 } 17269 }); 17270 } 17271 17272 /** 17273 * Called by MountService when the initial ASECs to scan are available. 17274 * Should block until all the ASEC containers are finished being scanned. 17275 */ 17276 public void scanAvailableAsecs() { 17277 updateExternalMediaStatusInner(true, false, false); 17278 } 17279 17280 /* 17281 * Collect information of applications on external media, map them against 17282 * existing containers and update information based on current mount status. 17283 * Please note that we always have to report status if reportStatus has been 17284 * set to true especially when unloading packages. 17285 */ 17286 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 17287 boolean externalStorage) { 17288 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 17289 int[] uidArr = EmptyArray.INT; 17290 17291 final String[] list = PackageHelper.getSecureContainerList(); 17292 if (ArrayUtils.isEmpty(list)) { 17293 Log.i(TAG, "No secure containers found"); 17294 } else { 17295 // Process list of secure containers and categorize them 17296 // as active or stale based on their package internal state. 17297 17298 // reader 17299 synchronized (mPackages) { 17300 for (String cid : list) { 17301 // Leave stages untouched for now; installer service owns them 17302 if (PackageInstallerService.isStageName(cid)) continue; 17303 17304 if (DEBUG_SD_INSTALL) 17305 Log.i(TAG, "Processing container " + cid); 17306 String pkgName = getAsecPackageName(cid); 17307 if (pkgName == null) { 17308 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 17309 continue; 17310 } 17311 if (DEBUG_SD_INSTALL) 17312 Log.i(TAG, "Looking for pkg : " + pkgName); 17313 17314 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17315 if (ps == null) { 17316 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 17317 continue; 17318 } 17319 17320 /* 17321 * Skip packages that are not external if we're unmounting 17322 * external storage. 17323 */ 17324 if (externalStorage && !isMounted && !isExternal(ps)) { 17325 continue; 17326 } 17327 17328 final AsecInstallArgs args = new AsecInstallArgs(cid, 17329 getAppDexInstructionSets(ps), ps.isForwardLocked()); 17330 // The package status is changed only if the code path 17331 // matches between settings and the container id. 17332 if (ps.codePathString != null 17333 && ps.codePathString.startsWith(args.getCodePath())) { 17334 if (DEBUG_SD_INSTALL) { 17335 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 17336 + " at code path: " + ps.codePathString); 17337 } 17338 17339 // We do have a valid package installed on sdcard 17340 processCids.put(args, ps.codePathString); 17341 final int uid = ps.appId; 17342 if (uid != -1) { 17343 uidArr = ArrayUtils.appendInt(uidArr, uid); 17344 } 17345 } else { 17346 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 17347 + ps.codePathString); 17348 } 17349 } 17350 } 17351 17352 Arrays.sort(uidArr); 17353 } 17354 17355 // Process packages with valid entries. 17356 if (isMounted) { 17357 if (DEBUG_SD_INSTALL) 17358 Log.i(TAG, "Loading packages"); 17359 loadMediaPackages(processCids, uidArr, externalStorage); 17360 startCleaningPackages(); 17361 mInstallerService.onSecureContainersAvailable(); 17362 } else { 17363 if (DEBUG_SD_INSTALL) 17364 Log.i(TAG, "Unloading packages"); 17365 unloadMediaPackages(processCids, uidArr, reportStatus); 17366 } 17367 } 17368 17369 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17370 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 17371 final int size = infos.size(); 17372 final String[] packageNames = new String[size]; 17373 final int[] packageUids = new int[size]; 17374 for (int i = 0; i < size; i++) { 17375 final ApplicationInfo info = infos.get(i); 17376 packageNames[i] = info.packageName; 17377 packageUids[i] = info.uid; 17378 } 17379 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 17380 finishedReceiver); 17381 } 17382 17383 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17384 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 17385 sendResourcesChangedBroadcast(mediaStatus, replacing, 17386 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 17387 } 17388 17389 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17390 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 17391 int size = pkgList.length; 17392 if (size > 0) { 17393 // Send broadcasts here 17394 Bundle extras = new Bundle(); 17395 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 17396 if (uidArr != null) { 17397 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 17398 } 17399 if (replacing) { 17400 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 17401 } 17402 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 17403 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 17404 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 17405 } 17406 } 17407 17408 /* 17409 * Look at potentially valid container ids from processCids If package 17410 * information doesn't match the one on record or package scanning fails, 17411 * the cid is added to list of removeCids. We currently don't delete stale 17412 * containers. 17413 */ 17414 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 17415 boolean externalStorage) { 17416 ArrayList<String> pkgList = new ArrayList<String>(); 17417 Set<AsecInstallArgs> keys = processCids.keySet(); 17418 17419 for (AsecInstallArgs args : keys) { 17420 String codePath = processCids.get(args); 17421 if (DEBUG_SD_INSTALL) 17422 Log.i(TAG, "Loading container : " + args.cid); 17423 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 17424 try { 17425 // Make sure there are no container errors first. 17426 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 17427 Slog.e(TAG, "Failed to mount cid : " + args.cid 17428 + " when installing from sdcard"); 17429 continue; 17430 } 17431 // Check code path here. 17432 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 17433 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 17434 + " does not match one in settings " + codePath); 17435 continue; 17436 } 17437 // Parse package 17438 int parseFlags = mDefParseFlags; 17439 if (args.isExternalAsec()) { 17440 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 17441 } 17442 if (args.isFwdLocked()) { 17443 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 17444 } 17445 17446 synchronized (mInstallLock) { 17447 PackageParser.Package pkg = null; 17448 try { 17449 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 17450 } catch (PackageManagerException e) { 17451 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 17452 } 17453 // Scan the package 17454 if (pkg != null) { 17455 /* 17456 * TODO why is the lock being held? doPostInstall is 17457 * called in other places without the lock. This needs 17458 * to be straightened out. 17459 */ 17460 // writer 17461 synchronized (mPackages) { 17462 retCode = PackageManager.INSTALL_SUCCEEDED; 17463 pkgList.add(pkg.packageName); 17464 // Post process args 17465 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 17466 pkg.applicationInfo.uid); 17467 } 17468 } else { 17469 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 17470 } 17471 } 17472 17473 } finally { 17474 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 17475 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 17476 } 17477 } 17478 } 17479 // writer 17480 synchronized (mPackages) { 17481 // If the platform SDK has changed since the last time we booted, 17482 // we need to re-grant app permission to catch any new ones that 17483 // appear. This is really a hack, and means that apps can in some 17484 // cases get permissions that the user didn't initially explicitly 17485 // allow... it would be nice to have some better way to handle 17486 // this situation. 17487 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 17488 : mSettings.getInternalVersion(); 17489 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 17490 : StorageManager.UUID_PRIVATE_INTERNAL; 17491 17492 int updateFlags = UPDATE_PERMISSIONS_ALL; 17493 if (ver.sdkVersion != mSdkVersion) { 17494 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 17495 + mSdkVersion + "; regranting permissions for external"); 17496 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 17497 } 17498 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 17499 17500 // Yay, everything is now upgraded 17501 ver.forceCurrent(); 17502 17503 // can downgrade to reader 17504 // Persist settings 17505 mSettings.writeLPr(); 17506 } 17507 // Send a broadcast to let everyone know we are done processing 17508 if (pkgList.size() > 0) { 17509 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 17510 } 17511 } 17512 17513 /* 17514 * Utility method to unload a list of specified containers 17515 */ 17516 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 17517 // Just unmount all valid containers. 17518 for (AsecInstallArgs arg : cidArgs) { 17519 synchronized (mInstallLock) { 17520 arg.doPostDeleteLI(false); 17521 } 17522 } 17523 } 17524 17525 /* 17526 * Unload packages mounted on external media. This involves deleting package 17527 * data from internal structures, sending broadcasts about disabled packages, 17528 * gc'ing to free up references, unmounting all secure containers 17529 * corresponding to packages on external media, and posting a 17530 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 17531 * that we always have to post this message if status has been requested no 17532 * matter what. 17533 */ 17534 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 17535 final boolean reportStatus) { 17536 if (DEBUG_SD_INSTALL) 17537 Log.i(TAG, "unloading media packages"); 17538 ArrayList<String> pkgList = new ArrayList<String>(); 17539 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 17540 final Set<AsecInstallArgs> keys = processCids.keySet(); 17541 for (AsecInstallArgs args : keys) { 17542 String pkgName = args.getPackageName(); 17543 if (DEBUG_SD_INSTALL) 17544 Log.i(TAG, "Trying to unload pkg : " + pkgName); 17545 // Delete package internally 17546 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 17547 synchronized (mInstallLock) { 17548 boolean res = deletePackageLI(pkgName, null, false, null, 17549 PackageManager.DELETE_KEEP_DATA, outInfo, false, null); 17550 if (res) { 17551 pkgList.add(pkgName); 17552 } else { 17553 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 17554 failedList.add(args); 17555 } 17556 } 17557 } 17558 17559 // reader 17560 synchronized (mPackages) { 17561 // We didn't update the settings after removing each package; 17562 // write them now for all packages. 17563 mSettings.writeLPr(); 17564 } 17565 17566 // We have to absolutely send UPDATED_MEDIA_STATUS only 17567 // after confirming that all the receivers processed the ordered 17568 // broadcast when packages get disabled, force a gc to clean things up. 17569 // and unload all the containers. 17570 if (pkgList.size() > 0) { 17571 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 17572 new IIntentReceiver.Stub() { 17573 public void performReceive(Intent intent, int resultCode, String data, 17574 Bundle extras, boolean ordered, boolean sticky, 17575 int sendingUser) throws RemoteException { 17576 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 17577 reportStatus ? 1 : 0, 1, keys); 17578 mHandler.sendMessage(msg); 17579 } 17580 }); 17581 } else { 17582 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 17583 keys); 17584 mHandler.sendMessage(msg); 17585 } 17586 } 17587 17588 private void loadPrivatePackages(final VolumeInfo vol) { 17589 mHandler.post(new Runnable() { 17590 @Override 17591 public void run() { 17592 loadPrivatePackagesInner(vol); 17593 } 17594 }); 17595 } 17596 17597 private void loadPrivatePackagesInner(VolumeInfo vol) { 17598 final String volumeUuid = vol.fsUuid; 17599 if (TextUtils.isEmpty(volumeUuid)) { 17600 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 17601 return; 17602 } 17603 17604 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 17605 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 17606 17607 final VersionInfo ver; 17608 final List<PackageSetting> packages; 17609 synchronized (mPackages) { 17610 ver = mSettings.findOrCreateVersion(volumeUuid); 17611 packages = mSettings.getVolumePackagesLPr(volumeUuid); 17612 } 17613 17614 // TODO: introduce a new concept similar to "frozen" to prevent these 17615 // apps from being launched until after data has been fully reconciled 17616 for (PackageSetting ps : packages) { 17617 synchronized (mInstallLock) { 17618 final PackageParser.Package pkg; 17619 try { 17620 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 17621 loaded.add(pkg.applicationInfo); 17622 17623 } catch (PackageManagerException e) { 17624 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 17625 } 17626 17627 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 17628 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 17629 } 17630 } 17631 } 17632 17633 // Reconcile app data for all started/unlocked users 17634 final StorageManager sm = mContext.getSystemService(StorageManager.class); 17635 final UserManager um = mContext.getSystemService(UserManager.class); 17636 for (UserInfo user : um.getUsers()) { 17637 final int flags; 17638 if (um.isUserUnlocked(user.id)) { 17639 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 17640 } else if (um.isUserRunning(user.id)) { 17641 flags = StorageManager.FLAG_STORAGE_DE; 17642 } else { 17643 continue; 17644 } 17645 17646 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 17647 reconcileAppsData(volumeUuid, user.id, flags); 17648 } 17649 17650 synchronized (mPackages) { 17651 int updateFlags = UPDATE_PERMISSIONS_ALL; 17652 if (ver.sdkVersion != mSdkVersion) { 17653 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 17654 + mSdkVersion + "; regranting permissions for " + volumeUuid); 17655 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 17656 } 17657 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 17658 17659 // Yay, everything is now upgraded 17660 ver.forceCurrent(); 17661 17662 mSettings.writeLPr(); 17663 } 17664 17665 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 17666 sendResourcesChangedBroadcast(true, false, loaded, null); 17667 } 17668 17669 private void unloadPrivatePackages(final VolumeInfo vol) { 17670 mHandler.post(new Runnable() { 17671 @Override 17672 public void run() { 17673 unloadPrivatePackagesInner(vol); 17674 } 17675 }); 17676 } 17677 17678 private void unloadPrivatePackagesInner(VolumeInfo vol) { 17679 final String volumeUuid = vol.fsUuid; 17680 if (TextUtils.isEmpty(volumeUuid)) { 17681 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 17682 return; 17683 } 17684 17685 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 17686 synchronized (mInstallLock) { 17687 synchronized (mPackages) { 17688 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 17689 for (PackageSetting ps : packages) { 17690 if (ps.pkg == null) continue; 17691 17692 final ApplicationInfo info = ps.pkg.applicationInfo; 17693 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 17694 if (deletePackageLI(ps.name, null, false, null, 17695 PackageManager.DELETE_KEEP_DATA, outInfo, false, null)) { 17696 unloaded.add(info); 17697 } else { 17698 Slog.w(TAG, "Failed to unload " + ps.codePath); 17699 } 17700 } 17701 17702 mSettings.writeLPr(); 17703 } 17704 } 17705 17706 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 17707 sendResourcesChangedBroadcast(false, false, unloaded, null); 17708 } 17709 17710 /** 17711 * Examine all users present on given mounted volume, and destroy data 17712 * belonging to users that are no longer valid, or whose user ID has been 17713 * recycled. 17714 */ 17715 private void reconcileUsers(String volumeUuid) { 17716 // TODO: also reconcile DE directories 17717 final File[] files = FileUtils 17718 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)); 17719 for (File file : files) { 17720 if (!file.isDirectory()) continue; 17721 17722 final int userId; 17723 final UserInfo info; 17724 try { 17725 userId = Integer.parseInt(file.getName()); 17726 info = sUserManager.getUserInfo(userId); 17727 } catch (NumberFormatException e) { 17728 Slog.w(TAG, "Invalid user directory " + file); 17729 continue; 17730 } 17731 17732 boolean destroyUser = false; 17733 if (info == null) { 17734 logCriticalInfo(Log.WARN, "Destroying user directory " + file 17735 + " because no matching user was found"); 17736 destroyUser = true; 17737 } else { 17738 try { 17739 UserManagerService.enforceSerialNumber(file, info.serialNumber); 17740 } catch (IOException e) { 17741 logCriticalInfo(Log.WARN, "Destroying user directory " + file 17742 + " because we failed to enforce serial number: " + e); 17743 destroyUser = true; 17744 } 17745 } 17746 17747 if (destroyUser) { 17748 synchronized (mInstallLock) { 17749 try { 17750 mInstaller.removeUserDataDirs(volumeUuid, userId); 17751 } catch (InstallerException e) { 17752 Slog.w(TAG, "Failed to clean up user dirs", e); 17753 } 17754 } 17755 } 17756 } 17757 } 17758 17759 private void assertPackageKnown(String volumeUuid, String packageName) 17760 throws PackageManagerException { 17761 synchronized (mPackages) { 17762 final PackageSetting ps = mSettings.mPackages.get(packageName); 17763 if (ps == null) { 17764 throw new PackageManagerException("Package " + packageName + " is unknown"); 17765 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 17766 throw new PackageManagerException( 17767 "Package " + packageName + " found on unknown volume " + volumeUuid 17768 + "; expected volume " + ps.volumeUuid); 17769 } 17770 } 17771 } 17772 17773 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 17774 throws PackageManagerException { 17775 synchronized (mPackages) { 17776 final PackageSetting ps = mSettings.mPackages.get(packageName); 17777 if (ps == null) { 17778 throw new PackageManagerException("Package " + packageName + " is unknown"); 17779 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 17780 throw new PackageManagerException( 17781 "Package " + packageName + " found on unknown volume " + volumeUuid 17782 + "; expected volume " + ps.volumeUuid); 17783 } else if (!ps.getInstalled(userId)) { 17784 throw new PackageManagerException( 17785 "Package " + packageName + " not installed for user " + userId); 17786 } 17787 } 17788 } 17789 17790 /** 17791 * Examine all apps present on given mounted volume, and destroy apps that 17792 * aren't expected, either due to uninstallation or reinstallation on 17793 * another volume. 17794 */ 17795 private void reconcileApps(String volumeUuid) { 17796 final File[] files = FileUtils 17797 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 17798 for (File file : files) { 17799 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 17800 && !PackageInstallerService.isStageName(file.getName()); 17801 if (!isPackage) { 17802 // Ignore entries which are not packages 17803 continue; 17804 } 17805 17806 try { 17807 final PackageLite pkg = PackageParser.parsePackageLite(file, 17808 PackageParser.PARSE_MUST_BE_APK); 17809 assertPackageKnown(volumeUuid, pkg.packageName); 17810 17811 } catch (PackageParserException | PackageManagerException e) { 17812 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 17813 synchronized (mInstallLock) { 17814 removeCodePathLI(file); 17815 } 17816 } 17817 } 17818 } 17819 17820 /** 17821 * Reconcile all app data for the given user. 17822 * <p> 17823 * Verifies that directories exist and that ownership and labeling is 17824 * correct for all installed apps on all mounted volumes. 17825 */ 17826 void reconcileAppsData(int userId, int flags) { 17827 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17828 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 17829 final String volumeUuid = vol.getFsUuid(); 17830 reconcileAppsData(volumeUuid, userId, flags); 17831 } 17832 } 17833 17834 /** 17835 * Reconcile all app data on given mounted volume. 17836 * <p> 17837 * Destroys app data that isn't expected, either due to uninstallation or 17838 * reinstallation on another volume. 17839 * <p> 17840 * Verifies that directories exist and that ownership and labeling is 17841 * correct for all installed apps. 17842 */ 17843 private void reconcileAppsData(String volumeUuid, int userId, int flags) { 17844 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 17845 + Integer.toHexString(flags)); 17846 17847 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 17848 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 17849 17850 boolean restoreconNeeded = false; 17851 17852 // First look for stale data that doesn't belong, and check if things 17853 // have changed since we did our last restorecon 17854 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 17855 if (!isUserKeyUnlocked(userId)) { 17856 throw new RuntimeException( 17857 "Yikes, someone asked us to reconcile CE storage while " + userId 17858 + " was still locked; this would have caused massive data loss!"); 17859 } 17860 17861 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 17862 17863 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 17864 for (File file : files) { 17865 final String packageName = file.getName(); 17866 try { 17867 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 17868 } catch (PackageManagerException e) { 17869 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 17870 synchronized (mInstallLock) { 17871 destroyAppDataLI(volumeUuid, packageName, userId, 17872 StorageManager.FLAG_STORAGE_CE); 17873 } 17874 } 17875 } 17876 } 17877 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 17878 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 17879 17880 final File[] files = FileUtils.listFilesOrEmpty(deDir); 17881 for (File file : files) { 17882 final String packageName = file.getName(); 17883 try { 17884 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 17885 } catch (PackageManagerException e) { 17886 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 17887 synchronized (mInstallLock) { 17888 destroyAppDataLI(volumeUuid, packageName, userId, 17889 StorageManager.FLAG_STORAGE_DE); 17890 } 17891 } 17892 } 17893 } 17894 17895 // Ensure that data directories are ready to roll for all packages 17896 // installed for this volume and user 17897 final List<PackageSetting> packages; 17898 synchronized (mPackages) { 17899 packages = mSettings.getVolumePackagesLPr(volumeUuid); 17900 } 17901 int preparedCount = 0; 17902 for (PackageSetting ps : packages) { 17903 final String packageName = ps.name; 17904 if (ps.pkg == null) { 17905 Slog.w(TAG, "Odd, missing scanned package " + packageName); 17906 // TODO: might be due to legacy ASEC apps; we should circle back 17907 // and reconcile again once they're scanned 17908 continue; 17909 } 17910 17911 if (ps.getInstalled(userId)) { 17912 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 17913 preparedCount++; 17914 } 17915 } 17916 17917 if (restoreconNeeded) { 17918 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 17919 SELinuxMMAC.setRestoreconDone(ceDir); 17920 } 17921 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 17922 SELinuxMMAC.setRestoreconDone(deDir); 17923 } 17924 } 17925 17926 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 17927 + " packages; restoreconNeeded was " + restoreconNeeded); 17928 } 17929 17930 /** 17931 * Prepare app data for the given app just after it was installed or 17932 * upgraded. This method carefully only touches users that it's installed 17933 * for, and it forces a restorecon to handle any seinfo changes. 17934 * <p> 17935 * Verifies that directories exist and that ownership and labeling is 17936 * correct for all installed apps. If there is an ownership mismatch, it 17937 * will try recovering system apps by wiping data; third-party app data is 17938 * left intact. 17939 */ 17940 private void prepareAppDataAfterInstall(PackageParser.Package pkg) { 17941 prepareAppDataAfterInstallInternal(pkg); 17942 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17943 for (int i = 0; i < childCount; i++) { 17944 PackageParser.Package childPackage = pkg.childPackages.get(i); 17945 prepareAppDataAfterInstallInternal(childPackage); 17946 } 17947 } 17948 17949 private void prepareAppDataAfterInstallInternal(PackageParser.Package pkg) { 17950 final PackageSetting ps; 17951 synchronized (mPackages) { 17952 ps = mSettings.mPackages.get(pkg.packageName); 17953 } 17954 17955 final UserManager um = mContext.getSystemService(UserManager.class); 17956 for (UserInfo user : um.getUsers()) { 17957 final int flags; 17958 if (um.isUserUnlocked(user.id)) { 17959 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 17960 } else if (um.isUserRunning(user.id)) { 17961 flags = StorageManager.FLAG_STORAGE_DE; 17962 } else { 17963 continue; 17964 } 17965 17966 if (ps.getInstalled(user.id)) { 17967 // Whenever an app changes, force a restorecon of its data 17968 // TODO: when user data is locked, mark that we're still dirty 17969 prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true); 17970 } 17971 } 17972 } 17973 17974 /** 17975 * Prepare app data for the given app. 17976 * <p> 17977 * Verifies that directories exist and that ownership and labeling is 17978 * correct for all installed apps. If there is an ownership mismatch, this 17979 * will try recovering system apps by wiping data; third-party app data is 17980 * left intact. 17981 */ 17982 private void prepareAppData(String volumeUuid, int userId, int flags, 17983 PackageParser.Package pkg, boolean restoreconNeeded) { 17984 if (DEBUG_APP_DATA) { 17985 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 17986 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 17987 } 17988 17989 final String packageName = pkg.packageName; 17990 final ApplicationInfo app = pkg.applicationInfo; 17991 final int appId = UserHandle.getAppId(app.uid); 17992 17993 Preconditions.checkNotNull(app.seinfo); 17994 17995 synchronized (mInstallLock) { 17996 try { 17997 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 17998 appId, app.seinfo, app.targetSdkVersion); 17999 } catch (InstallerException e) { 18000 if (app.isSystemApp()) { 18001 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 18002 + ", but trying to recover: " + e); 18003 destroyAppDataLI(volumeUuid, packageName, userId, flags); 18004 try { 18005 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18006 appId, app.seinfo, app.targetSdkVersion); 18007 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 18008 } catch (InstallerException e2) { 18009 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 18010 } 18011 } else { 18012 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 18013 } 18014 } 18015 18016 if (restoreconNeeded) { 18017 restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo); 18018 } 18019 18020 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18021 // Create a native library symlink only if we have native libraries 18022 // and if the native libraries are 32 bit libraries. We do not provide 18023 // this symlink for 64 bit libraries. 18024 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 18025 final String nativeLibPath = app.nativeLibraryDir; 18026 try { 18027 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 18028 nativeLibPath, userId); 18029 } catch (InstallerException e) { 18030 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 18031 } 18032 } 18033 } 18034 } 18035 } 18036 18037 private void unfreezePackage(String packageName) { 18038 synchronized (mPackages) { 18039 final PackageSetting ps = mSettings.mPackages.get(packageName); 18040 if (ps != null) { 18041 ps.frozen = false; 18042 } 18043 } 18044 } 18045 18046 @Override 18047 public int movePackage(final String packageName, final String volumeUuid) { 18048 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 18049 18050 final int moveId = mNextMoveId.getAndIncrement(); 18051 mHandler.post(new Runnable() { 18052 @Override 18053 public void run() { 18054 try { 18055 movePackageInternal(packageName, volumeUuid, moveId); 18056 } catch (PackageManagerException e) { 18057 Slog.w(TAG, "Failed to move " + packageName, e); 18058 mMoveCallbacks.notifyStatusChanged(moveId, 18059 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 18060 } 18061 } 18062 }); 18063 return moveId; 18064 } 18065 18066 private void movePackageInternal(final String packageName, final String volumeUuid, 18067 final int moveId) throws PackageManagerException { 18068 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 18069 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18070 final PackageManager pm = mContext.getPackageManager(); 18071 18072 final boolean currentAsec; 18073 final String currentVolumeUuid; 18074 final File codeFile; 18075 final String installerPackageName; 18076 final String packageAbiOverride; 18077 final int appId; 18078 final String seinfo; 18079 final String label; 18080 final int targetSdkVersion; 18081 18082 // reader 18083 synchronized (mPackages) { 18084 final PackageParser.Package pkg = mPackages.get(packageName); 18085 final PackageSetting ps = mSettings.mPackages.get(packageName); 18086 if (pkg == null || ps == null) { 18087 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 18088 } 18089 18090 if (pkg.applicationInfo.isSystemApp()) { 18091 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 18092 "Cannot move system application"); 18093 } 18094 18095 if (pkg.applicationInfo.isExternalAsec()) { 18096 currentAsec = true; 18097 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 18098 } else if (pkg.applicationInfo.isForwardLocked()) { 18099 currentAsec = true; 18100 currentVolumeUuid = "forward_locked"; 18101 } else { 18102 currentAsec = false; 18103 currentVolumeUuid = ps.volumeUuid; 18104 18105 final File probe = new File(pkg.codePath); 18106 final File probeOat = new File(probe, "oat"); 18107 if (!probe.isDirectory() || !probeOat.isDirectory()) { 18108 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18109 "Move only supported for modern cluster style installs"); 18110 } 18111 } 18112 18113 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 18114 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18115 "Package already moved to " + volumeUuid); 18116 } 18117 18118 if (ps.frozen) { 18119 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 18120 "Failed to move already frozen package"); 18121 } 18122 ps.frozen = true; 18123 18124 codeFile = new File(pkg.codePath); 18125 installerPackageName = ps.installerPackageName; 18126 packageAbiOverride = ps.cpuAbiOverrideString; 18127 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18128 seinfo = pkg.applicationInfo.seinfo; 18129 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 18130 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 18131 } 18132 18133 // Now that we're guarded by frozen state, kill app during move 18134 final long token = Binder.clearCallingIdentity(); 18135 try { 18136 killApplication(packageName, appId, "move pkg"); 18137 } finally { 18138 Binder.restoreCallingIdentity(token); 18139 } 18140 18141 final Bundle extras = new Bundle(); 18142 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 18143 extras.putString(Intent.EXTRA_TITLE, label); 18144 mMoveCallbacks.notifyCreated(moveId, extras); 18145 18146 int installFlags; 18147 final boolean moveCompleteApp; 18148 final File measurePath; 18149 18150 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 18151 installFlags = INSTALL_INTERNAL; 18152 moveCompleteApp = !currentAsec; 18153 measurePath = Environment.getDataAppDirectory(volumeUuid); 18154 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 18155 installFlags = INSTALL_EXTERNAL; 18156 moveCompleteApp = false; 18157 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 18158 } else { 18159 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 18160 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 18161 || !volume.isMountedWritable()) { 18162 unfreezePackage(packageName); 18163 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18164 "Move location not mounted private volume"); 18165 } 18166 18167 Preconditions.checkState(!currentAsec); 18168 18169 installFlags = INSTALL_INTERNAL; 18170 moveCompleteApp = true; 18171 measurePath = Environment.getDataAppDirectory(volumeUuid); 18172 } 18173 18174 final PackageStats stats = new PackageStats(null, -1); 18175 synchronized (mInstaller) { 18176 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 18177 unfreezePackage(packageName); 18178 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18179 "Failed to measure package size"); 18180 } 18181 } 18182 18183 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 18184 + stats.dataSize); 18185 18186 final long startFreeBytes = measurePath.getFreeSpace(); 18187 final long sizeBytes; 18188 if (moveCompleteApp) { 18189 sizeBytes = stats.codeSize + stats.dataSize; 18190 } else { 18191 sizeBytes = stats.codeSize; 18192 } 18193 18194 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 18195 unfreezePackage(packageName); 18196 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18197 "Not enough free space to move"); 18198 } 18199 18200 mMoveCallbacks.notifyStatusChanged(moveId, 10); 18201 18202 final CountDownLatch installedLatch = new CountDownLatch(1); 18203 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 18204 @Override 18205 public void onUserActionRequired(Intent intent) throws RemoteException { 18206 throw new IllegalStateException(); 18207 } 18208 18209 @Override 18210 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 18211 Bundle extras) throws RemoteException { 18212 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 18213 + PackageManager.installStatusToString(returnCode, msg)); 18214 18215 installedLatch.countDown(); 18216 18217 // Regardless of success or failure of the move operation, 18218 // always unfreeze the package 18219 unfreezePackage(packageName); 18220 18221 final int status = PackageManager.installStatusToPublicStatus(returnCode); 18222 switch (status) { 18223 case PackageInstaller.STATUS_SUCCESS: 18224 mMoveCallbacks.notifyStatusChanged(moveId, 18225 PackageManager.MOVE_SUCCEEDED); 18226 break; 18227 case PackageInstaller.STATUS_FAILURE_STORAGE: 18228 mMoveCallbacks.notifyStatusChanged(moveId, 18229 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 18230 break; 18231 default: 18232 mMoveCallbacks.notifyStatusChanged(moveId, 18233 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 18234 break; 18235 } 18236 } 18237 }; 18238 18239 final MoveInfo move; 18240 if (moveCompleteApp) { 18241 // Kick off a thread to report progress estimates 18242 new Thread() { 18243 @Override 18244 public void run() { 18245 while (true) { 18246 try { 18247 if (installedLatch.await(1, TimeUnit.SECONDS)) { 18248 break; 18249 } 18250 } catch (InterruptedException ignored) { 18251 } 18252 18253 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 18254 final int progress = 10 + (int) MathUtils.constrain( 18255 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 18256 mMoveCallbacks.notifyStatusChanged(moveId, progress); 18257 } 18258 } 18259 }.start(); 18260 18261 final String dataAppName = codeFile.getName(); 18262 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 18263 dataAppName, appId, seinfo, targetSdkVersion); 18264 } else { 18265 move = null; 18266 } 18267 18268 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 18269 18270 final Message msg = mHandler.obtainMessage(INIT_COPY); 18271 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 18272 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 18273 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 18274 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 18275 msg.obj = params; 18276 18277 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 18278 System.identityHashCode(msg.obj)); 18279 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 18280 System.identityHashCode(msg.obj)); 18281 18282 mHandler.sendMessage(msg); 18283 } 18284 18285 @Override 18286 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 18287 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 18288 18289 final int realMoveId = mNextMoveId.getAndIncrement(); 18290 final Bundle extras = new Bundle(); 18291 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 18292 mMoveCallbacks.notifyCreated(realMoveId, extras); 18293 18294 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 18295 @Override 18296 public void onCreated(int moveId, Bundle extras) { 18297 // Ignored 18298 } 18299 18300 @Override 18301 public void onStatusChanged(int moveId, int status, long estMillis) { 18302 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 18303 } 18304 }; 18305 18306 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18307 storage.setPrimaryStorageUuid(volumeUuid, callback); 18308 return realMoveId; 18309 } 18310 18311 @Override 18312 public int getMoveStatus(int moveId) { 18313 mContext.enforceCallingOrSelfPermission( 18314 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18315 return mMoveCallbacks.mLastStatus.get(moveId); 18316 } 18317 18318 @Override 18319 public void registerMoveCallback(IPackageMoveObserver callback) { 18320 mContext.enforceCallingOrSelfPermission( 18321 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18322 mMoveCallbacks.register(callback); 18323 } 18324 18325 @Override 18326 public void unregisterMoveCallback(IPackageMoveObserver callback) { 18327 mContext.enforceCallingOrSelfPermission( 18328 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18329 mMoveCallbacks.unregister(callback); 18330 } 18331 18332 @Override 18333 public boolean setInstallLocation(int loc) { 18334 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 18335 null); 18336 if (getInstallLocation() == loc) { 18337 return true; 18338 } 18339 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 18340 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 18341 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 18342 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 18343 return true; 18344 } 18345 return false; 18346 } 18347 18348 @Override 18349 public int getInstallLocation() { 18350 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 18351 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 18352 PackageHelper.APP_INSTALL_AUTO); 18353 } 18354 18355 /** Called by UserManagerService */ 18356 void cleanUpUser(UserManagerService userManager, int userHandle) { 18357 synchronized (mPackages) { 18358 mDirtyUsers.remove(userHandle); 18359 mUserNeedsBadging.delete(userHandle); 18360 mSettings.removeUserLPw(userHandle); 18361 mPendingBroadcasts.remove(userHandle); 18362 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 18363 } 18364 synchronized (mInstallLock) { 18365 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18366 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18367 final String volumeUuid = vol.getFsUuid(); 18368 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 18369 try { 18370 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 18371 } catch (InstallerException e) { 18372 Slog.w(TAG, "Failed to remove user data", e); 18373 } 18374 } 18375 synchronized (mPackages) { 18376 removeUnusedPackagesLILPw(userManager, userHandle); 18377 } 18378 } 18379 } 18380 18381 /** 18382 * We're removing userHandle and would like to remove any downloaded packages 18383 * that are no longer in use by any other user. 18384 * @param userHandle the user being removed 18385 */ 18386 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 18387 final boolean DEBUG_CLEAN_APKS = false; 18388 int [] users = userManager.getUserIds(); 18389 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 18390 while (psit.hasNext()) { 18391 PackageSetting ps = psit.next(); 18392 if (ps.pkg == null) { 18393 continue; 18394 } 18395 final String packageName = ps.pkg.packageName; 18396 // Skip over if system app 18397 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 18398 continue; 18399 } 18400 if (DEBUG_CLEAN_APKS) { 18401 Slog.i(TAG, "Checking package " + packageName); 18402 } 18403 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 18404 if (keep) { 18405 if (DEBUG_CLEAN_APKS) { 18406 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 18407 } 18408 } else { 18409 for (int i = 0; i < users.length; i++) { 18410 if (users[i] != userHandle && ps.getInstalled(users[i])) { 18411 keep = true; 18412 if (DEBUG_CLEAN_APKS) { 18413 Slog.i(TAG, " Keeping package " + packageName + " for user " 18414 + users[i]); 18415 } 18416 break; 18417 } 18418 } 18419 } 18420 if (!keep) { 18421 if (DEBUG_CLEAN_APKS) { 18422 Slog.i(TAG, " Removing package " + packageName); 18423 } 18424 mHandler.post(new Runnable() { 18425 public void run() { 18426 deletePackageX(packageName, userHandle, 0); 18427 } //end run 18428 }); 18429 } 18430 } 18431 } 18432 18433 /** Called by UserManagerService */ 18434 void createNewUser(int userHandle) { 18435 synchronized (mInstallLock) { 18436 try { 18437 mInstaller.createUserConfig(userHandle); 18438 } catch (InstallerException e) { 18439 Slog.w(TAG, "Failed to create user config", e); 18440 } 18441 mSettings.createNewUserLI(this, mInstaller, userHandle); 18442 } 18443 synchronized (mPackages) { 18444 applyFactoryDefaultBrowserLPw(userHandle); 18445 primeDomainVerificationsLPw(userHandle); 18446 } 18447 } 18448 18449 void newUserCreated(final int userHandle) { 18450 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 18451 // If permission review for legacy apps is required, we represent 18452 // dagerous permissions for such apps as always granted runtime 18453 // permissions to keep per user flag state whether review is needed. 18454 // Hence, if a new user is added we have to propagate dangerous 18455 // permission grants for these legacy apps. 18456 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 18457 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 18458 | UPDATE_PERMISSIONS_REPLACE_ALL); 18459 } 18460 } 18461 18462 @Override 18463 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 18464 mContext.enforceCallingOrSelfPermission( 18465 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 18466 "Only package verification agents can read the verifier device identity"); 18467 18468 synchronized (mPackages) { 18469 return mSettings.getVerifierDeviceIdentityLPw(); 18470 } 18471 } 18472 18473 @Override 18474 public void setPermissionEnforced(String permission, boolean enforced) { 18475 // TODO: Now that we no longer change GID for storage, this should to away. 18476 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 18477 "setPermissionEnforced"); 18478 if (READ_EXTERNAL_STORAGE.equals(permission)) { 18479 synchronized (mPackages) { 18480 if (mSettings.mReadExternalStorageEnforced == null 18481 || mSettings.mReadExternalStorageEnforced != enforced) { 18482 mSettings.mReadExternalStorageEnforced = enforced; 18483 mSettings.writeLPr(); 18484 } 18485 } 18486 // kill any non-foreground processes so we restart them and 18487 // grant/revoke the GID. 18488 final IActivityManager am = ActivityManagerNative.getDefault(); 18489 if (am != null) { 18490 final long token = Binder.clearCallingIdentity(); 18491 try { 18492 am.killProcessesBelowForeground("setPermissionEnforcement"); 18493 } catch (RemoteException e) { 18494 } finally { 18495 Binder.restoreCallingIdentity(token); 18496 } 18497 } 18498 } else { 18499 throw new IllegalArgumentException("No selective enforcement for " + permission); 18500 } 18501 } 18502 18503 @Override 18504 @Deprecated 18505 public boolean isPermissionEnforced(String permission) { 18506 return true; 18507 } 18508 18509 @Override 18510 public boolean isStorageLow() { 18511 final long token = Binder.clearCallingIdentity(); 18512 try { 18513 final DeviceStorageMonitorInternal 18514 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 18515 if (dsm != null) { 18516 return dsm.isMemoryLow(); 18517 } else { 18518 return false; 18519 } 18520 } finally { 18521 Binder.restoreCallingIdentity(token); 18522 } 18523 } 18524 18525 @Override 18526 public IPackageInstaller getPackageInstaller() { 18527 return mInstallerService; 18528 } 18529 18530 private boolean userNeedsBadging(int userId) { 18531 int index = mUserNeedsBadging.indexOfKey(userId); 18532 if (index < 0) { 18533 final UserInfo userInfo; 18534 final long token = Binder.clearCallingIdentity(); 18535 try { 18536 userInfo = sUserManager.getUserInfo(userId); 18537 } finally { 18538 Binder.restoreCallingIdentity(token); 18539 } 18540 final boolean b; 18541 if (userInfo != null && userInfo.isManagedProfile()) { 18542 b = true; 18543 } else { 18544 b = false; 18545 } 18546 mUserNeedsBadging.put(userId, b); 18547 return b; 18548 } 18549 return mUserNeedsBadging.valueAt(index); 18550 } 18551 18552 @Override 18553 public KeySet getKeySetByAlias(String packageName, String alias) { 18554 if (packageName == null || alias == null) { 18555 return null; 18556 } 18557 synchronized(mPackages) { 18558 final PackageParser.Package pkg = mPackages.get(packageName); 18559 if (pkg == null) { 18560 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18561 throw new IllegalArgumentException("Unknown package: " + packageName); 18562 } 18563 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18564 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 18565 } 18566 } 18567 18568 @Override 18569 public KeySet getSigningKeySet(String packageName) { 18570 if (packageName == null) { 18571 return null; 18572 } 18573 synchronized(mPackages) { 18574 final PackageParser.Package pkg = mPackages.get(packageName); 18575 if (pkg == null) { 18576 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18577 throw new IllegalArgumentException("Unknown package: " + packageName); 18578 } 18579 if (pkg.applicationInfo.uid != Binder.getCallingUid() 18580 && Process.SYSTEM_UID != Binder.getCallingUid()) { 18581 throw new SecurityException("May not access signing KeySet of other apps."); 18582 } 18583 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18584 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 18585 } 18586 } 18587 18588 @Override 18589 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 18590 if (packageName == null || ks == null) { 18591 return false; 18592 } 18593 synchronized(mPackages) { 18594 final PackageParser.Package pkg = mPackages.get(packageName); 18595 if (pkg == null) { 18596 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18597 throw new IllegalArgumentException("Unknown package: " + packageName); 18598 } 18599 IBinder ksh = ks.getToken(); 18600 if (ksh instanceof KeySetHandle) { 18601 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18602 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 18603 } 18604 return false; 18605 } 18606 } 18607 18608 @Override 18609 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 18610 if (packageName == null || ks == null) { 18611 return false; 18612 } 18613 synchronized(mPackages) { 18614 final PackageParser.Package pkg = mPackages.get(packageName); 18615 if (pkg == null) { 18616 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18617 throw new IllegalArgumentException("Unknown package: " + packageName); 18618 } 18619 IBinder ksh = ks.getToken(); 18620 if (ksh instanceof KeySetHandle) { 18621 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18622 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 18623 } 18624 return false; 18625 } 18626 } 18627 18628 private void deletePackageIfUnusedLPr(final String packageName) { 18629 PackageSetting ps = mSettings.mPackages.get(packageName); 18630 if (ps == null) { 18631 return; 18632 } 18633 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 18634 // TODO Implement atomic delete if package is unused 18635 // It is currently possible that the package will be deleted even if it is installed 18636 // after this method returns. 18637 mHandler.post(new Runnable() { 18638 public void run() { 18639 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 18640 } 18641 }); 18642 } 18643 } 18644 18645 /** 18646 * Check and throw if the given before/after packages would be considered a 18647 * downgrade. 18648 */ 18649 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 18650 throws PackageManagerException { 18651 if (after.versionCode < before.mVersionCode) { 18652 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 18653 "Update version code " + after.versionCode + " is older than current " 18654 + before.mVersionCode); 18655 } else if (after.versionCode == before.mVersionCode) { 18656 if (after.baseRevisionCode < before.baseRevisionCode) { 18657 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 18658 "Update base revision code " + after.baseRevisionCode 18659 + " is older than current " + before.baseRevisionCode); 18660 } 18661 18662 if (!ArrayUtils.isEmpty(after.splitNames)) { 18663 for (int i = 0; i < after.splitNames.length; i++) { 18664 final String splitName = after.splitNames[i]; 18665 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 18666 if (j != -1) { 18667 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 18668 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 18669 "Update split " + splitName + " revision code " 18670 + after.splitRevisionCodes[i] + " is older than current " 18671 + before.splitRevisionCodes[j]); 18672 } 18673 } 18674 } 18675 } 18676 } 18677 } 18678 18679 private static class MoveCallbacks extends Handler { 18680 private static final int MSG_CREATED = 1; 18681 private static final int MSG_STATUS_CHANGED = 2; 18682 18683 private final RemoteCallbackList<IPackageMoveObserver> 18684 mCallbacks = new RemoteCallbackList<>(); 18685 18686 private final SparseIntArray mLastStatus = new SparseIntArray(); 18687 18688 public MoveCallbacks(Looper looper) { 18689 super(looper); 18690 } 18691 18692 public void register(IPackageMoveObserver callback) { 18693 mCallbacks.register(callback); 18694 } 18695 18696 public void unregister(IPackageMoveObserver callback) { 18697 mCallbacks.unregister(callback); 18698 } 18699 18700 @Override 18701 public void handleMessage(Message msg) { 18702 final SomeArgs args = (SomeArgs) msg.obj; 18703 final int n = mCallbacks.beginBroadcast(); 18704 for (int i = 0; i < n; i++) { 18705 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 18706 try { 18707 invokeCallback(callback, msg.what, args); 18708 } catch (RemoteException ignored) { 18709 } 18710 } 18711 mCallbacks.finishBroadcast(); 18712 args.recycle(); 18713 } 18714 18715 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 18716 throws RemoteException { 18717 switch (what) { 18718 case MSG_CREATED: { 18719 callback.onCreated(args.argi1, (Bundle) args.arg2); 18720 break; 18721 } 18722 case MSG_STATUS_CHANGED: { 18723 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 18724 break; 18725 } 18726 } 18727 } 18728 18729 private void notifyCreated(int moveId, Bundle extras) { 18730 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 18731 18732 final SomeArgs args = SomeArgs.obtain(); 18733 args.argi1 = moveId; 18734 args.arg2 = extras; 18735 obtainMessage(MSG_CREATED, args).sendToTarget(); 18736 } 18737 18738 private void notifyStatusChanged(int moveId, int status) { 18739 notifyStatusChanged(moveId, status, -1); 18740 } 18741 18742 private void notifyStatusChanged(int moveId, int status, long estMillis) { 18743 Slog.v(TAG, "Move " + moveId + " status " + status); 18744 18745 final SomeArgs args = SomeArgs.obtain(); 18746 args.argi1 = moveId; 18747 args.argi2 = status; 18748 args.arg3 = estMillis; 18749 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 18750 18751 synchronized (mLastStatus) { 18752 mLastStatus.put(moveId, status); 18753 } 18754 } 18755 } 18756 18757 private final static class OnPermissionChangeListeners extends Handler { 18758 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 18759 18760 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 18761 new RemoteCallbackList<>(); 18762 18763 public OnPermissionChangeListeners(Looper looper) { 18764 super(looper); 18765 } 18766 18767 @Override 18768 public void handleMessage(Message msg) { 18769 switch (msg.what) { 18770 case MSG_ON_PERMISSIONS_CHANGED: { 18771 final int uid = msg.arg1; 18772 handleOnPermissionsChanged(uid); 18773 } break; 18774 } 18775 } 18776 18777 public void addListenerLocked(IOnPermissionsChangeListener listener) { 18778 mPermissionListeners.register(listener); 18779 18780 } 18781 18782 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 18783 mPermissionListeners.unregister(listener); 18784 } 18785 18786 public void onPermissionsChanged(int uid) { 18787 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 18788 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 18789 } 18790 } 18791 18792 private void handleOnPermissionsChanged(int uid) { 18793 final int count = mPermissionListeners.beginBroadcast(); 18794 try { 18795 for (int i = 0; i < count; i++) { 18796 IOnPermissionsChangeListener callback = mPermissionListeners 18797 .getBroadcastItem(i); 18798 try { 18799 callback.onPermissionsChanged(uid); 18800 } catch (RemoteException e) { 18801 Log.e(TAG, "Permission listener is dead", e); 18802 } 18803 } 18804 } finally { 18805 mPermissionListeners.finishBroadcast(); 18806 } 18807 } 18808 } 18809 18810 private class PackageManagerInternalImpl extends PackageManagerInternal { 18811 @Override 18812 public void setLocationPackagesProvider(PackagesProvider provider) { 18813 synchronized (mPackages) { 18814 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 18815 } 18816 } 18817 18818 @Override 18819 public void setImePackagesProvider(PackagesProvider provider) { 18820 synchronized (mPackages) { 18821 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 18822 } 18823 } 18824 18825 @Override 18826 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 18827 synchronized (mPackages) { 18828 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 18829 } 18830 } 18831 18832 @Override 18833 public void setSmsAppPackagesProvider(PackagesProvider provider) { 18834 synchronized (mPackages) { 18835 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 18836 } 18837 } 18838 18839 @Override 18840 public void setDialerAppPackagesProvider(PackagesProvider provider) { 18841 synchronized (mPackages) { 18842 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 18843 } 18844 } 18845 18846 @Override 18847 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 18848 synchronized (mPackages) { 18849 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 18850 } 18851 } 18852 18853 @Override 18854 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 18855 synchronized (mPackages) { 18856 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 18857 } 18858 } 18859 18860 @Override 18861 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 18862 synchronized (mPackages) { 18863 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 18864 packageName, userId); 18865 } 18866 } 18867 18868 @Override 18869 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 18870 synchronized (mPackages) { 18871 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 18872 packageName, userId); 18873 } 18874 } 18875 18876 @Override 18877 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 18878 synchronized (mPackages) { 18879 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 18880 packageName, userId); 18881 } 18882 } 18883 18884 @Override 18885 public void setKeepUninstalledPackages(final List<String> packageList) { 18886 Preconditions.checkNotNull(packageList); 18887 List<String> removedFromList = null; 18888 synchronized (mPackages) { 18889 if (mKeepUninstalledPackages != null) { 18890 final int packagesCount = mKeepUninstalledPackages.size(); 18891 for (int i = 0; i < packagesCount; i++) { 18892 String oldPackage = mKeepUninstalledPackages.get(i); 18893 if (packageList != null && packageList.contains(oldPackage)) { 18894 continue; 18895 } 18896 if (removedFromList == null) { 18897 removedFromList = new ArrayList<>(); 18898 } 18899 removedFromList.add(oldPackage); 18900 } 18901 } 18902 mKeepUninstalledPackages = new ArrayList<>(packageList); 18903 if (removedFromList != null) { 18904 final int removedCount = removedFromList.size(); 18905 for (int i = 0; i < removedCount; i++) { 18906 deletePackageIfUnusedLPr(removedFromList.get(i)); 18907 } 18908 } 18909 } 18910 } 18911 18912 @Override 18913 public boolean isPermissionsReviewRequired(String packageName, int userId) { 18914 synchronized (mPackages) { 18915 // If we do not support permission review, done. 18916 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 18917 return false; 18918 } 18919 18920 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 18921 if (packageSetting == null) { 18922 return false; 18923 } 18924 18925 // Permission review applies only to apps not supporting the new permission model. 18926 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 18927 return false; 18928 } 18929 18930 // Legacy apps have the permission and get user consent on launch. 18931 PermissionsState permissionsState = packageSetting.getPermissionsState(); 18932 return permissionsState.isPermissionReviewRequired(userId); 18933 } 18934 } 18935 } 18936 18937 @Override 18938 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 18939 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 18940 synchronized (mPackages) { 18941 final long identity = Binder.clearCallingIdentity(); 18942 try { 18943 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 18944 packageNames, userId); 18945 } finally { 18946 Binder.restoreCallingIdentity(identity); 18947 } 18948 } 18949 } 18950 18951 private static void enforceSystemOrPhoneCaller(String tag) { 18952 int callingUid = Binder.getCallingUid(); 18953 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 18954 throw new SecurityException( 18955 "Cannot call " + tag + " from UID " + callingUid); 18956 } 18957 } 18958 18959 boolean isHistoricalPackageUsageAvailable() { 18960 return mPackageUsage.isHistoricalPackageUsageAvailable(); 18961 } 18962} 18963