PackageManagerService.java revision 20a0e405aadd4a200834b70283c20ed34ae09336
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.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 34import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 35import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 36import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 37import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 40import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 41import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 45import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 46import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 47import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 48import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 54import static android.content.pm.PackageManager.INSTALL_INTERNAL; 55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 61import static android.content.pm.PackageManager.MATCH_ALL; 62import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 63import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 64import static android.content.pm.PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE; 65import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 66import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 67import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 68import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 69import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 70import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 71import static android.content.pm.PackageManager.PERMISSION_DENIED; 72import static android.content.pm.PackageManager.PERMISSION_GRANTED; 73import static android.content.pm.PackageParser.isApkFile; 74import static android.os.Process.PACKAGE_INFO_GID; 75import static android.os.Process.SYSTEM_UID; 76import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 77import static android.system.OsConstants.O_CREAT; 78import static android.system.OsConstants.O_RDWR; 79 80import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 81import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 82import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 83import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 84import static com.android.internal.util.ArrayUtils.appendInt; 85import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 86import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 87import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 88import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 89import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 90import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 91import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 92import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 93import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 94 95import android.Manifest; 96import android.annotation.NonNull; 97import android.annotation.Nullable; 98import android.app.ActivityManager; 99import android.app.ActivityManagerNative; 100import android.app.AppGlobals; 101import android.app.IActivityManager; 102import android.app.admin.IDevicePolicyManager; 103import android.app.backup.IBackupManager; 104import android.content.BroadcastReceiver; 105import android.content.ComponentName; 106import android.content.Context; 107import android.content.IIntentReceiver; 108import android.content.Intent; 109import android.content.IntentFilter; 110import android.content.IntentSender; 111import android.content.IntentSender.SendIntentException; 112import android.content.ServiceConnection; 113import android.content.pm.ActivityInfo; 114import android.content.pm.ApplicationInfo; 115import android.content.pm.AppsQueryHelper; 116import android.content.pm.ComponentInfo; 117import android.content.pm.EphemeralApplicationInfo; 118import android.content.pm.EphemeralResolveInfo; 119import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 120import android.content.pm.FeatureInfo; 121import android.content.pm.IOnPermissionsChangeListener; 122import android.content.pm.IPackageDataObserver; 123import android.content.pm.IPackageDeleteObserver; 124import android.content.pm.IPackageDeleteObserver2; 125import android.content.pm.IPackageInstallObserver2; 126import android.content.pm.IPackageInstaller; 127import android.content.pm.IPackageManager; 128import android.content.pm.IPackageMoveObserver; 129import android.content.pm.IPackageStatsObserver; 130import android.content.pm.InstrumentationInfo; 131import android.content.pm.IntentFilterVerificationInfo; 132import android.content.pm.KeySet; 133import android.content.pm.PackageCleanItem; 134import android.content.pm.PackageInfo; 135import android.content.pm.PackageInfoLite; 136import android.content.pm.PackageInstaller; 137import android.content.pm.PackageManager; 138import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 139import android.content.pm.PackageManagerInternal; 140import android.content.pm.PackageParser; 141import android.content.pm.PackageParser.ActivityIntentInfo; 142import android.content.pm.PackageParser.PackageLite; 143import android.content.pm.PackageParser.PackageParserException; 144import android.content.pm.PackageStats; 145import android.content.pm.PackageUserState; 146import android.content.pm.ParceledListSlice; 147import android.content.pm.PermissionGroupInfo; 148import android.content.pm.PermissionInfo; 149import android.content.pm.ProviderInfo; 150import android.content.pm.ResolveInfo; 151import android.content.pm.ServiceInfo; 152import android.content.pm.Signature; 153import android.content.pm.UserInfo; 154import android.content.pm.VerificationParams; 155import android.content.pm.VerifierDeviceIdentity; 156import android.content.pm.VerifierInfo; 157import android.content.res.Resources; 158import android.graphics.Bitmap; 159import android.hardware.display.DisplayManager; 160import android.net.Uri; 161import android.os.Binder; 162import android.os.Build; 163import android.os.Bundle; 164import android.os.Debug; 165import android.os.Environment; 166import android.os.Environment.UserEnvironment; 167import android.os.FileUtils; 168import android.os.Handler; 169import android.os.IBinder; 170import android.os.Looper; 171import android.os.Message; 172import android.os.Parcel; 173import android.os.ParcelFileDescriptor; 174import android.os.Process; 175import android.os.RemoteCallbackList; 176import android.os.RemoteException; 177import android.os.ResultReceiver; 178import android.os.SELinux; 179import android.os.ServiceManager; 180import android.os.SystemClock; 181import android.os.SystemProperties; 182import android.os.Trace; 183import android.os.UserHandle; 184import android.os.UserManager; 185import android.os.storage.IMountService; 186import android.os.storage.MountServiceInternal; 187import android.os.storage.StorageEventListener; 188import android.os.storage.StorageManager; 189import android.os.storage.VolumeInfo; 190import android.os.storage.VolumeRecord; 191import android.security.KeyStore; 192import android.security.SystemKeyStore; 193import android.system.ErrnoException; 194import android.system.Os; 195import android.text.TextUtils; 196import android.text.format.DateUtils; 197import android.util.ArrayMap; 198import android.util.ArraySet; 199import android.util.AtomicFile; 200import android.util.DisplayMetrics; 201import android.util.EventLog; 202import android.util.ExceptionUtils; 203import android.util.Log; 204import android.util.LogPrinter; 205import android.util.MathUtils; 206import android.util.PrintStreamPrinter; 207import android.util.Slog; 208import android.util.SparseArray; 209import android.util.SparseBooleanArray; 210import android.util.SparseIntArray; 211import android.util.Xml; 212import android.view.Display; 213 214import com.android.internal.R; 215import com.android.internal.annotations.GuardedBy; 216import com.android.internal.app.IMediaContainerService; 217import com.android.internal.app.ResolverActivity; 218import com.android.internal.content.NativeLibraryHelper; 219import com.android.internal.content.PackageHelper; 220import com.android.internal.os.IParcelFileDescriptorFactory; 221import com.android.internal.os.InstallerConnection.InstallerException; 222import com.android.internal.os.SomeArgs; 223import com.android.internal.os.Zygote; 224import com.android.internal.util.ArrayUtils; 225import com.android.internal.util.FastPrintWriter; 226import com.android.internal.util.FastXmlSerializer; 227import com.android.internal.util.IndentingPrintWriter; 228import com.android.internal.util.Preconditions; 229import com.android.internal.util.XmlUtils; 230import com.android.server.EventLogTags; 231import com.android.server.FgThread; 232import com.android.server.IntentResolver; 233import com.android.server.LocalServices; 234import com.android.server.ServiceThread; 235import com.android.server.SystemConfig; 236import com.android.server.Watchdog; 237import com.android.server.pm.Installer.StorageFlags; 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.Iterator; 281import java.util.List; 282import java.util.Map; 283import java.util.Objects; 284import java.util.Set; 285import java.util.concurrent.CountDownLatch; 286import java.util.concurrent.TimeUnit; 287import java.util.concurrent.atomic.AtomicBoolean; 288import java.util.concurrent.atomic.AtomicInteger; 289import java.util.concurrent.atomic.AtomicLong; 290 291/** 292 * Keep track of all those .apks everywhere. 293 * 294 * This is very central to the platform's security; please run the unit 295 * tests whenever making modifications here: 296 * 297runtest -c android.content.pm.PackageManagerTests frameworks-core 298 * 299 * {@hide} 300 */ 301public class PackageManagerService extends IPackageManager.Stub { 302 static final String TAG = "PackageManager"; 303 static final boolean DEBUG_SETTINGS = false; 304 static final boolean DEBUG_PREFERRED = false; 305 static final boolean DEBUG_UPGRADE = false; 306 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 307 private static final boolean DEBUG_BACKUP = false; 308 private static final boolean DEBUG_INSTALL = false; 309 private static final boolean DEBUG_REMOVE = false; 310 private static final boolean DEBUG_BROADCASTS = false; 311 private static final boolean DEBUG_SHOW_INFO = false; 312 private static final boolean DEBUG_PACKAGE_INFO = false; 313 private static final boolean DEBUG_INTENT_MATCHING = false; 314 private static final boolean DEBUG_PACKAGE_SCANNING = false; 315 private static final boolean DEBUG_VERIFY = false; 316 private static final boolean DEBUG_DEXOPT = false; 317 private static final boolean DEBUG_ABI_SELECTION = false; 318 private static final boolean DEBUG_EPHEMERAL = false; 319 private static final boolean DEBUG_TRIAGED_MISSING = false; 320 private static final boolean DEBUG_APP_DATA = false; 321 322 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 323 324 private static final boolean DISABLE_EPHEMERAL_APPS = true; 325 326 private static final int RADIO_UID = Process.PHONE_UID; 327 private static final int LOG_UID = Process.LOG_UID; 328 private static final int NFC_UID = Process.NFC_UID; 329 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 330 private static final int SHELL_UID = Process.SHELL_UID; 331 332 // Cap the size of permission trees that 3rd party apps can define 333 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 334 335 // Suffix used during package installation when copying/moving 336 // package apks to install directory. 337 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 338 339 static final int SCAN_NO_DEX = 1<<1; 340 static final int SCAN_FORCE_DEX = 1<<2; 341 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 342 static final int SCAN_NEW_INSTALL = 1<<4; 343 static final int SCAN_NO_PATHS = 1<<5; 344 static final int SCAN_UPDATE_TIME = 1<<6; 345 static final int SCAN_DEFER_DEX = 1<<7; 346 static final int SCAN_BOOTING = 1<<8; 347 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 348 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 349 static final int SCAN_REPLACING = 1<<11; 350 static final int SCAN_REQUIRE_KNOWN = 1<<12; 351 static final int SCAN_MOVE = 1<<13; 352 static final int SCAN_INITIAL = 1<<14; 353 354 static final int REMOVE_CHATTY = 1<<16; 355 356 private static final int[] EMPTY_INT_ARRAY = new int[0]; 357 358 /** 359 * Timeout (in milliseconds) after which the watchdog should declare that 360 * our handler thread is wedged. The usual default for such things is one 361 * minute but we sometimes do very lengthy I/O operations on this thread, 362 * such as installing multi-gigabyte applications, so ours needs to be longer. 363 */ 364 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 365 366 /** 367 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 368 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 369 * settings entry if available, otherwise we use the hardcoded default. If it's been 370 * more than this long since the last fstrim, we force one during the boot sequence. 371 * 372 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 373 * one gets run at the next available charging+idle time. This final mandatory 374 * no-fstrim check kicks in only of the other scheduling criteria is never met. 375 */ 376 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 377 378 /** 379 * Whether verification is enabled by default. 380 */ 381 private static final boolean DEFAULT_VERIFY_ENABLE = true; 382 383 /** 384 * The default maximum time to wait for the verification agent to return in 385 * milliseconds. 386 */ 387 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 388 389 /** 390 * The default response for package verification timeout. 391 * 392 * This can be either PackageManager.VERIFICATION_ALLOW or 393 * PackageManager.VERIFICATION_REJECT. 394 */ 395 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 396 397 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 398 399 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 400 DEFAULT_CONTAINER_PACKAGE, 401 "com.android.defcontainer.DefaultContainerService"); 402 403 private static final String KILL_APP_REASON_GIDS_CHANGED = 404 "permission grant or revoke changed gids"; 405 406 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 407 "permissions revoked"; 408 409 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 410 411 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 412 413 /** Permission grant: not grant the permission. */ 414 private static final int GRANT_DENIED = 1; 415 416 /** Permission grant: grant the permission as an install permission. */ 417 private static final int GRANT_INSTALL = 2; 418 419 /** Permission grant: grant the permission as a runtime one. */ 420 private static final int GRANT_RUNTIME = 3; 421 422 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 423 private static final int GRANT_UPGRADE = 4; 424 425 /** Canonical intent used to identify what counts as a "web browser" app */ 426 private static final Intent sBrowserIntent; 427 static { 428 sBrowserIntent = new Intent(); 429 sBrowserIntent.setAction(Intent.ACTION_VIEW); 430 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 431 sBrowserIntent.setData(Uri.parse("http:")); 432 } 433 434 final ServiceThread mHandlerThread; 435 436 final PackageHandler mHandler; 437 438 /** 439 * Messages for {@link #mHandler} that need to wait for system ready before 440 * being dispatched. 441 */ 442 private ArrayList<Message> mPostSystemReadyMessages; 443 444 final int mSdkVersion = Build.VERSION.SDK_INT; 445 446 final Context mContext; 447 final boolean mFactoryTest; 448 final boolean mOnlyCore; 449 final DisplayMetrics mMetrics; 450 final int mDefParseFlags; 451 final String[] mSeparateProcesses; 452 final boolean mIsUpgrade; 453 454 /** The location for ASEC container files on internal storage. */ 455 final String mAsecInternalPath; 456 457 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 458 // LOCK HELD. Can be called with mInstallLock held. 459 @GuardedBy("mInstallLock") 460 final Installer mInstaller; 461 462 /** Directory where installed third-party apps stored */ 463 final File mAppInstallDir; 464 final File mEphemeralInstallDir; 465 466 /** 467 * Directory to which applications installed internally have their 468 * 32 bit native libraries copied. 469 */ 470 private File mAppLib32InstallDir; 471 472 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 473 // apps. 474 final File mDrmAppPrivateInstallDir; 475 476 // ---------------------------------------------------------------- 477 478 // Lock for state used when installing and doing other long running 479 // operations. Methods that must be called with this lock held have 480 // the suffix "LI". 481 final Object mInstallLock = new Object(); 482 483 // ---------------------------------------------------------------- 484 485 // Keys are String (package name), values are Package. This also serves 486 // as the lock for the global state. Methods that must be called with 487 // this lock held have the prefix "LP". 488 @GuardedBy("mPackages") 489 final ArrayMap<String, PackageParser.Package> mPackages = 490 new ArrayMap<String, PackageParser.Package>(); 491 492 // Tracks available target package names -> overlay package paths. 493 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 494 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 495 496 /** 497 * Tracks new system packages [received in an OTA] that we expect to 498 * find updated user-installed versions. Keys are package name, values 499 * are package location. 500 */ 501 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 502 503 /** 504 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 505 */ 506 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 507 /** 508 * Whether or not system app permissions should be promoted from install to runtime. 509 */ 510 boolean mPromoteSystemApps; 511 512 final Settings mSettings; 513 boolean mRestoredSettings; 514 515 // System configuration read by SystemConfig. 516 final int[] mGlobalGids; 517 final SparseArray<ArraySet<String>> mSystemPermissions; 518 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 519 520 // If mac_permissions.xml was found for seinfo labeling. 521 boolean mFoundPolicyFile; 522 523 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 524 525 public static final class SharedLibraryEntry { 526 public final String path; 527 public final String apk; 528 529 SharedLibraryEntry(String _path, String _apk) { 530 path = _path; 531 apk = _apk; 532 } 533 } 534 535 // Currently known shared libraries. 536 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 537 new ArrayMap<String, SharedLibraryEntry>(); 538 539 // All available activities, for your resolving pleasure. 540 final ActivityIntentResolver mActivities = 541 new ActivityIntentResolver(); 542 543 // All available receivers, for your resolving pleasure. 544 final ActivityIntentResolver mReceivers = 545 new ActivityIntentResolver(); 546 547 // All available services, for your resolving pleasure. 548 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 549 550 // All available providers, for your resolving pleasure. 551 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 552 553 // Mapping from provider base names (first directory in content URI codePath) 554 // to the provider information. 555 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 556 new ArrayMap<String, PackageParser.Provider>(); 557 558 // Mapping from instrumentation class names to info about them. 559 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 560 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 561 562 // Mapping from permission names to info about them. 563 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 564 new ArrayMap<String, PackageParser.PermissionGroup>(); 565 566 // Packages whose data we have transfered into another package, thus 567 // should no longer exist. 568 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 569 570 // Broadcast actions that are only available to the system. 571 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 572 573 /** List of packages waiting for verification. */ 574 final SparseArray<PackageVerificationState> mPendingVerification 575 = new SparseArray<PackageVerificationState>(); 576 577 /** Set of packages associated with each app op permission. */ 578 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 579 580 final PackageInstallerService mInstallerService; 581 582 private final PackageDexOptimizer mPackageDexOptimizer; 583 584 private AtomicInteger mNextMoveId = new AtomicInteger(); 585 private final MoveCallbacks mMoveCallbacks; 586 587 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 588 589 // Cache of users who need badging. 590 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 591 592 /** Token for keys in mPendingVerification. */ 593 private int mPendingVerificationToken = 0; 594 595 volatile boolean mSystemReady; 596 volatile boolean mSafeMode; 597 volatile boolean mHasSystemUidErrors; 598 599 ApplicationInfo mAndroidApplication; 600 final ActivityInfo mResolveActivity = new ActivityInfo(); 601 final ResolveInfo mResolveInfo = new ResolveInfo(); 602 ComponentName mResolveComponentName; 603 PackageParser.Package mPlatformPackage; 604 ComponentName mCustomResolverComponentName; 605 606 boolean mResolverReplaced = false; 607 608 private final @Nullable ComponentName mIntentFilterVerifierComponent; 609 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 610 611 private int mIntentFilterVerificationToken = 0; 612 613 /** Component that knows whether or not an ephemeral application exists */ 614 final ComponentName mEphemeralResolverComponent; 615 /** The service connection to the ephemeral resolver */ 616 final EphemeralResolverConnection mEphemeralResolverConnection; 617 618 /** Component used to install ephemeral applications */ 619 final ComponentName mEphemeralInstallerComponent; 620 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 621 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 622 623 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 624 = new SparseArray<IntentFilterVerificationState>(); 625 626 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 627 new DefaultPermissionGrantPolicy(this); 628 629 // List of packages names to keep cached, even if they are uninstalled for all users 630 private List<String> mKeepUninstalledPackages; 631 632 private boolean mUseJitProfiles = 633 SystemProperties.getBoolean("dalvik.vm.usejitprofiles", false); 634 635 private static class IFVerificationParams { 636 PackageParser.Package pkg; 637 boolean replacing; 638 int userId; 639 int verifierUid; 640 641 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 642 int _userId, int _verifierUid) { 643 pkg = _pkg; 644 replacing = _replacing; 645 userId = _userId; 646 replacing = _replacing; 647 verifierUid = _verifierUid; 648 } 649 } 650 651 private interface IntentFilterVerifier<T extends IntentFilter> { 652 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 653 T filter, String packageName); 654 void startVerifications(int userId); 655 void receiveVerificationResponse(int verificationId); 656 } 657 658 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 659 private Context mContext; 660 private ComponentName mIntentFilterVerifierComponent; 661 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 662 663 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 664 mContext = context; 665 mIntentFilterVerifierComponent = verifierComponent; 666 } 667 668 private String getDefaultScheme() { 669 return IntentFilter.SCHEME_HTTPS; 670 } 671 672 @Override 673 public void startVerifications(int userId) { 674 // Launch verifications requests 675 int count = mCurrentIntentFilterVerifications.size(); 676 for (int n=0; n<count; n++) { 677 int verificationId = mCurrentIntentFilterVerifications.get(n); 678 final IntentFilterVerificationState ivs = 679 mIntentFilterVerificationStates.get(verificationId); 680 681 String packageName = ivs.getPackageName(); 682 683 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 684 final int filterCount = filters.size(); 685 ArraySet<String> domainsSet = new ArraySet<>(); 686 for (int m=0; m<filterCount; m++) { 687 PackageParser.ActivityIntentInfo filter = filters.get(m); 688 domainsSet.addAll(filter.getHostsList()); 689 } 690 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 691 synchronized (mPackages) { 692 if (mSettings.createIntentFilterVerificationIfNeededLPw( 693 packageName, domainsList) != null) { 694 scheduleWriteSettingsLocked(); 695 } 696 } 697 sendVerificationRequest(userId, verificationId, ivs); 698 } 699 mCurrentIntentFilterVerifications.clear(); 700 } 701 702 private void sendVerificationRequest(int userId, int verificationId, 703 IntentFilterVerificationState ivs) { 704 705 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 706 verificationIntent.putExtra( 707 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 708 verificationId); 709 verificationIntent.putExtra( 710 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 711 getDefaultScheme()); 712 verificationIntent.putExtra( 713 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 714 ivs.getHostsString()); 715 verificationIntent.putExtra( 716 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 717 ivs.getPackageName()); 718 verificationIntent.setComponent(mIntentFilterVerifierComponent); 719 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 720 721 UserHandle user = new UserHandle(userId); 722 mContext.sendBroadcastAsUser(verificationIntent, user); 723 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 724 "Sending IntentFilter verification broadcast"); 725 } 726 727 public void receiveVerificationResponse(int verificationId) { 728 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 729 730 final boolean verified = ivs.isVerified(); 731 732 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 733 final int count = filters.size(); 734 if (DEBUG_DOMAIN_VERIFICATION) { 735 Slog.i(TAG, "Received verification response " + verificationId 736 + " for " + count + " filters, verified=" + verified); 737 } 738 for (int n=0; n<count; n++) { 739 PackageParser.ActivityIntentInfo filter = filters.get(n); 740 filter.setVerified(verified); 741 742 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 743 + " verified with result:" + verified + " and hosts:" 744 + ivs.getHostsString()); 745 } 746 747 mIntentFilterVerificationStates.remove(verificationId); 748 749 final String packageName = ivs.getPackageName(); 750 IntentFilterVerificationInfo ivi = null; 751 752 synchronized (mPackages) { 753 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 754 } 755 if (ivi == null) { 756 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 757 + verificationId + " packageName:" + packageName); 758 return; 759 } 760 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 761 "Updating IntentFilterVerificationInfo for package " + packageName 762 +" verificationId:" + verificationId); 763 764 synchronized (mPackages) { 765 if (verified) { 766 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 767 } else { 768 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 769 } 770 scheduleWriteSettingsLocked(); 771 772 final int userId = ivs.getUserId(); 773 if (userId != UserHandle.USER_ALL) { 774 final int userStatus = 775 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 776 777 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 778 boolean needUpdate = false; 779 780 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 781 // already been set by the User thru the Disambiguation dialog 782 switch (userStatus) { 783 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 784 if (verified) { 785 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 786 } else { 787 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 788 } 789 needUpdate = true; 790 break; 791 792 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 793 if (verified) { 794 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 795 needUpdate = true; 796 } 797 break; 798 799 default: 800 // Nothing to do 801 } 802 803 if (needUpdate) { 804 mSettings.updateIntentFilterVerificationStatusLPw( 805 packageName, updatedStatus, userId); 806 scheduleWritePackageRestrictionsLocked(userId); 807 } 808 } 809 } 810 } 811 812 @Override 813 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 814 ActivityIntentInfo filter, String packageName) { 815 if (!hasValidDomains(filter)) { 816 return false; 817 } 818 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 819 if (ivs == null) { 820 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 821 packageName); 822 } 823 if (DEBUG_DOMAIN_VERIFICATION) { 824 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 825 } 826 ivs.addFilter(filter); 827 return true; 828 } 829 830 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 831 int userId, int verificationId, String packageName) { 832 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 833 verifierUid, userId, packageName); 834 ivs.setPendingState(); 835 synchronized (mPackages) { 836 mIntentFilterVerificationStates.append(verificationId, ivs); 837 mCurrentIntentFilterVerifications.add(verificationId); 838 } 839 return ivs; 840 } 841 } 842 843 private static boolean hasValidDomains(ActivityIntentInfo filter) { 844 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 845 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 846 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 847 } 848 849 // Set of pending broadcasts for aggregating enable/disable of components. 850 static class PendingPackageBroadcasts { 851 // for each user id, a map of <package name -> components within that package> 852 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 853 854 public PendingPackageBroadcasts() { 855 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 856 } 857 858 public ArrayList<String> get(int userId, String packageName) { 859 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 860 return packages.get(packageName); 861 } 862 863 public void put(int userId, String packageName, ArrayList<String> components) { 864 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 865 packages.put(packageName, components); 866 } 867 868 public void remove(int userId, String packageName) { 869 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 870 if (packages != null) { 871 packages.remove(packageName); 872 } 873 } 874 875 public void remove(int userId) { 876 mUidMap.remove(userId); 877 } 878 879 public int userIdCount() { 880 return mUidMap.size(); 881 } 882 883 public int userIdAt(int n) { 884 return mUidMap.keyAt(n); 885 } 886 887 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 888 return mUidMap.get(userId); 889 } 890 891 public int size() { 892 // total number of pending broadcast entries across all userIds 893 int num = 0; 894 for (int i = 0; i< mUidMap.size(); i++) { 895 num += mUidMap.valueAt(i).size(); 896 } 897 return num; 898 } 899 900 public void clear() { 901 mUidMap.clear(); 902 } 903 904 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 905 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 906 if (map == null) { 907 map = new ArrayMap<String, ArrayList<String>>(); 908 mUidMap.put(userId, map); 909 } 910 return map; 911 } 912 } 913 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 914 915 // Service Connection to remote media container service to copy 916 // package uri's from external media onto secure containers 917 // or internal storage. 918 private IMediaContainerService mContainerService = null; 919 920 static final int SEND_PENDING_BROADCAST = 1; 921 static final int MCS_BOUND = 3; 922 static final int END_COPY = 4; 923 static final int INIT_COPY = 5; 924 static final int MCS_UNBIND = 6; 925 static final int START_CLEANING_PACKAGE = 7; 926 static final int FIND_INSTALL_LOC = 8; 927 static final int POST_INSTALL = 9; 928 static final int MCS_RECONNECT = 10; 929 static final int MCS_GIVE_UP = 11; 930 static final int UPDATED_MEDIA_STATUS = 12; 931 static final int WRITE_SETTINGS = 13; 932 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 933 static final int PACKAGE_VERIFIED = 15; 934 static final int CHECK_PENDING_VERIFICATION = 16; 935 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 936 static final int INTENT_FILTER_VERIFIED = 18; 937 938 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 939 940 // Delay time in millisecs 941 static final int BROADCAST_DELAY = 10 * 1000; 942 943 static UserManagerService sUserManager; 944 945 // Stores a list of users whose package restrictions file needs to be updated 946 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 947 948 final private DefaultContainerConnection mDefContainerConn = 949 new DefaultContainerConnection(); 950 class DefaultContainerConnection implements ServiceConnection { 951 public void onServiceConnected(ComponentName name, IBinder service) { 952 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 953 IMediaContainerService imcs = 954 IMediaContainerService.Stub.asInterface(service); 955 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 956 } 957 958 public void onServiceDisconnected(ComponentName name) { 959 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 960 } 961 } 962 963 // Recordkeeping of restore-after-install operations that are currently in flight 964 // between the Package Manager and the Backup Manager 965 static class PostInstallData { 966 public InstallArgs args; 967 public PackageInstalledInfo res; 968 969 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 970 args = _a; 971 res = _r; 972 } 973 } 974 975 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 976 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 977 978 // XML tags for backup/restore of various bits of state 979 private static final String TAG_PREFERRED_BACKUP = "pa"; 980 private static final String TAG_DEFAULT_APPS = "da"; 981 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 982 983 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 984 private static final String TAG_ALL_GRANTS = "rt-grants"; 985 private static final String TAG_GRANT = "grant"; 986 private static final String ATTR_PACKAGE_NAME = "pkg"; 987 988 private static final String TAG_PERMISSION = "perm"; 989 private static final String ATTR_PERMISSION_NAME = "name"; 990 private static final String ATTR_IS_GRANTED = "g"; 991 private static final String ATTR_USER_SET = "set"; 992 private static final String ATTR_USER_FIXED = "fixed"; 993 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 994 995 // System/policy permission grants are not backed up 996 private static final int SYSTEM_RUNTIME_GRANT_MASK = 997 FLAG_PERMISSION_POLICY_FIXED 998 | FLAG_PERMISSION_SYSTEM_FIXED 999 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1000 1001 // And we back up these user-adjusted states 1002 private static final int USER_RUNTIME_GRANT_MASK = 1003 FLAG_PERMISSION_USER_SET 1004 | FLAG_PERMISSION_USER_FIXED 1005 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1006 1007 final @Nullable String mRequiredVerifierPackage; 1008 final @Nullable String mRequiredInstallerPackage; 1009 1010 private final PackageUsage mPackageUsage = new PackageUsage(); 1011 1012 private class PackageUsage { 1013 private static final int WRITE_INTERVAL 1014 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1015 1016 private final Object mFileLock = new Object(); 1017 private final AtomicLong mLastWritten = new AtomicLong(0); 1018 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1019 1020 private boolean mIsHistoricalPackageUsageAvailable = true; 1021 1022 boolean isHistoricalPackageUsageAvailable() { 1023 return mIsHistoricalPackageUsageAvailable; 1024 } 1025 1026 void write(boolean force) { 1027 if (force) { 1028 writeInternal(); 1029 return; 1030 } 1031 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1032 && !DEBUG_DEXOPT) { 1033 return; 1034 } 1035 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1036 new Thread("PackageUsage_DiskWriter") { 1037 @Override 1038 public void run() { 1039 try { 1040 writeInternal(); 1041 } finally { 1042 mBackgroundWriteRunning.set(false); 1043 } 1044 } 1045 }.start(); 1046 } 1047 } 1048 1049 private void writeInternal() { 1050 synchronized (mPackages) { 1051 synchronized (mFileLock) { 1052 AtomicFile file = getFile(); 1053 FileOutputStream f = null; 1054 try { 1055 f = file.startWrite(); 1056 BufferedOutputStream out = new BufferedOutputStream(f); 1057 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1058 StringBuilder sb = new StringBuilder(); 1059 for (PackageParser.Package pkg : mPackages.values()) { 1060 if (pkg.mLastPackageUsageTimeInMills == 0) { 1061 continue; 1062 } 1063 sb.setLength(0); 1064 sb.append(pkg.packageName); 1065 sb.append(' '); 1066 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1067 sb.append('\n'); 1068 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1069 } 1070 out.flush(); 1071 file.finishWrite(f); 1072 } catch (IOException e) { 1073 if (f != null) { 1074 file.failWrite(f); 1075 } 1076 Log.e(TAG, "Failed to write package usage times", e); 1077 } 1078 } 1079 } 1080 mLastWritten.set(SystemClock.elapsedRealtime()); 1081 } 1082 1083 void readLP() { 1084 synchronized (mFileLock) { 1085 AtomicFile file = getFile(); 1086 BufferedInputStream in = null; 1087 try { 1088 in = new BufferedInputStream(file.openRead()); 1089 StringBuffer sb = new StringBuffer(); 1090 while (true) { 1091 String packageName = readToken(in, sb, ' '); 1092 if (packageName == null) { 1093 break; 1094 } 1095 String timeInMillisString = readToken(in, sb, '\n'); 1096 if (timeInMillisString == null) { 1097 throw new IOException("Failed to find last usage time for package " 1098 + packageName); 1099 } 1100 PackageParser.Package pkg = mPackages.get(packageName); 1101 if (pkg == null) { 1102 continue; 1103 } 1104 long timeInMillis; 1105 try { 1106 timeInMillis = Long.parseLong(timeInMillisString); 1107 } catch (NumberFormatException e) { 1108 throw new IOException("Failed to parse " + timeInMillisString 1109 + " as a long.", e); 1110 } 1111 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1112 } 1113 } catch (FileNotFoundException expected) { 1114 mIsHistoricalPackageUsageAvailable = false; 1115 } catch (IOException e) { 1116 Log.w(TAG, "Failed to read package usage times", e); 1117 } finally { 1118 IoUtils.closeQuietly(in); 1119 } 1120 } 1121 mLastWritten.set(SystemClock.elapsedRealtime()); 1122 } 1123 1124 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1125 throws IOException { 1126 sb.setLength(0); 1127 while (true) { 1128 int ch = in.read(); 1129 if (ch == -1) { 1130 if (sb.length() == 0) { 1131 return null; 1132 } 1133 throw new IOException("Unexpected EOF"); 1134 } 1135 if (ch == endOfToken) { 1136 return sb.toString(); 1137 } 1138 sb.append((char)ch); 1139 } 1140 } 1141 1142 private AtomicFile getFile() { 1143 File dataDir = Environment.getDataDirectory(); 1144 File systemDir = new File(dataDir, "system"); 1145 File fname = new File(systemDir, "package-usage.list"); 1146 return new AtomicFile(fname); 1147 } 1148 } 1149 1150 class PackageHandler extends Handler { 1151 private boolean mBound = false; 1152 final ArrayList<HandlerParams> mPendingInstalls = 1153 new ArrayList<HandlerParams>(); 1154 1155 private boolean connectToService() { 1156 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1157 " DefaultContainerService"); 1158 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1159 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1160 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1161 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1162 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1163 mBound = true; 1164 return true; 1165 } 1166 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1167 return false; 1168 } 1169 1170 private void disconnectService() { 1171 mContainerService = null; 1172 mBound = false; 1173 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1174 mContext.unbindService(mDefContainerConn); 1175 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1176 } 1177 1178 PackageHandler(Looper looper) { 1179 super(looper); 1180 } 1181 1182 public void handleMessage(Message msg) { 1183 try { 1184 doHandleMessage(msg); 1185 } finally { 1186 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1187 } 1188 } 1189 1190 void doHandleMessage(Message msg) { 1191 switch (msg.what) { 1192 case INIT_COPY: { 1193 HandlerParams params = (HandlerParams) msg.obj; 1194 int idx = mPendingInstalls.size(); 1195 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1196 // If a bind was already initiated we dont really 1197 // need to do anything. The pending install 1198 // will be processed later on. 1199 if (!mBound) { 1200 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1201 System.identityHashCode(mHandler)); 1202 // If this is the only one pending we might 1203 // have to bind to the service again. 1204 if (!connectToService()) { 1205 Slog.e(TAG, "Failed to bind to media container service"); 1206 params.serviceError(); 1207 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1208 System.identityHashCode(mHandler)); 1209 if (params.traceMethod != null) { 1210 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1211 params.traceCookie); 1212 } 1213 return; 1214 } else { 1215 // Once we bind to the service, the first 1216 // pending request will be processed. 1217 mPendingInstalls.add(idx, params); 1218 } 1219 } else { 1220 mPendingInstalls.add(idx, params); 1221 // Already bound to the service. Just make 1222 // sure we trigger off processing the first request. 1223 if (idx == 0) { 1224 mHandler.sendEmptyMessage(MCS_BOUND); 1225 } 1226 } 1227 break; 1228 } 1229 case MCS_BOUND: { 1230 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1231 if (msg.obj != null) { 1232 mContainerService = (IMediaContainerService) msg.obj; 1233 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1234 System.identityHashCode(mHandler)); 1235 } 1236 if (mContainerService == null) { 1237 if (!mBound) { 1238 // Something seriously wrong since we are not bound and we are not 1239 // waiting for connection. Bail out. 1240 Slog.e(TAG, "Cannot bind to media container service"); 1241 for (HandlerParams params : mPendingInstalls) { 1242 // Indicate service bind error 1243 params.serviceError(); 1244 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1245 System.identityHashCode(params)); 1246 if (params.traceMethod != null) { 1247 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1248 params.traceMethod, params.traceCookie); 1249 } 1250 return; 1251 } 1252 mPendingInstalls.clear(); 1253 } else { 1254 Slog.w(TAG, "Waiting to connect to media container service"); 1255 } 1256 } else if (mPendingInstalls.size() > 0) { 1257 HandlerParams params = mPendingInstalls.get(0); 1258 if (params != null) { 1259 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1260 System.identityHashCode(params)); 1261 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1262 if (params.startCopy()) { 1263 // We are done... look for more work or to 1264 // go idle. 1265 if (DEBUG_SD_INSTALL) Log.i(TAG, 1266 "Checking for more work or unbind..."); 1267 // Delete pending install 1268 if (mPendingInstalls.size() > 0) { 1269 mPendingInstalls.remove(0); 1270 } 1271 if (mPendingInstalls.size() == 0) { 1272 if (mBound) { 1273 if (DEBUG_SD_INSTALL) Log.i(TAG, 1274 "Posting delayed MCS_UNBIND"); 1275 removeMessages(MCS_UNBIND); 1276 Message ubmsg = obtainMessage(MCS_UNBIND); 1277 // Unbind after a little delay, to avoid 1278 // continual thrashing. 1279 sendMessageDelayed(ubmsg, 10000); 1280 } 1281 } else { 1282 // There are more pending requests in queue. 1283 // Just post MCS_BOUND message to trigger processing 1284 // of next pending install. 1285 if (DEBUG_SD_INSTALL) Log.i(TAG, 1286 "Posting MCS_BOUND for next work"); 1287 mHandler.sendEmptyMessage(MCS_BOUND); 1288 } 1289 } 1290 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1291 } 1292 } else { 1293 // Should never happen ideally. 1294 Slog.w(TAG, "Empty queue"); 1295 } 1296 break; 1297 } 1298 case MCS_RECONNECT: { 1299 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1300 if (mPendingInstalls.size() > 0) { 1301 if (mBound) { 1302 disconnectService(); 1303 } 1304 if (!connectToService()) { 1305 Slog.e(TAG, "Failed to bind to media container service"); 1306 for (HandlerParams params : mPendingInstalls) { 1307 // Indicate service bind error 1308 params.serviceError(); 1309 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1310 System.identityHashCode(params)); 1311 } 1312 mPendingInstalls.clear(); 1313 } 1314 } 1315 break; 1316 } 1317 case MCS_UNBIND: { 1318 // If there is no actual work left, then time to unbind. 1319 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1320 1321 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1322 if (mBound) { 1323 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1324 1325 disconnectService(); 1326 } 1327 } else if (mPendingInstalls.size() > 0) { 1328 // There are more pending requests in queue. 1329 // Just post MCS_BOUND message to trigger processing 1330 // of next pending install. 1331 mHandler.sendEmptyMessage(MCS_BOUND); 1332 } 1333 1334 break; 1335 } 1336 case MCS_GIVE_UP: { 1337 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1338 HandlerParams params = mPendingInstalls.remove(0); 1339 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1340 System.identityHashCode(params)); 1341 break; 1342 } 1343 case SEND_PENDING_BROADCAST: { 1344 String packages[]; 1345 ArrayList<String> components[]; 1346 int size = 0; 1347 int uids[]; 1348 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1349 synchronized (mPackages) { 1350 if (mPendingBroadcasts == null) { 1351 return; 1352 } 1353 size = mPendingBroadcasts.size(); 1354 if (size <= 0) { 1355 // Nothing to be done. Just return 1356 return; 1357 } 1358 packages = new String[size]; 1359 components = new ArrayList[size]; 1360 uids = new int[size]; 1361 int i = 0; // filling out the above arrays 1362 1363 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1364 int packageUserId = mPendingBroadcasts.userIdAt(n); 1365 Iterator<Map.Entry<String, ArrayList<String>>> it 1366 = mPendingBroadcasts.packagesForUserId(packageUserId) 1367 .entrySet().iterator(); 1368 while (it.hasNext() && i < size) { 1369 Map.Entry<String, ArrayList<String>> ent = it.next(); 1370 packages[i] = ent.getKey(); 1371 components[i] = ent.getValue(); 1372 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1373 uids[i] = (ps != null) 1374 ? UserHandle.getUid(packageUserId, ps.appId) 1375 : -1; 1376 i++; 1377 } 1378 } 1379 size = i; 1380 mPendingBroadcasts.clear(); 1381 } 1382 // Send broadcasts 1383 for (int i = 0; i < size; i++) { 1384 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1385 } 1386 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1387 break; 1388 } 1389 case START_CLEANING_PACKAGE: { 1390 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1391 final String packageName = (String)msg.obj; 1392 final int userId = msg.arg1; 1393 final boolean andCode = msg.arg2 != 0; 1394 synchronized (mPackages) { 1395 if (userId == UserHandle.USER_ALL) { 1396 int[] users = sUserManager.getUserIds(); 1397 for (int user : users) { 1398 mSettings.addPackageToCleanLPw( 1399 new PackageCleanItem(user, packageName, andCode)); 1400 } 1401 } else { 1402 mSettings.addPackageToCleanLPw( 1403 new PackageCleanItem(userId, packageName, andCode)); 1404 } 1405 } 1406 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1407 startCleaningPackages(); 1408 } break; 1409 case POST_INSTALL: { 1410 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1411 1412 PostInstallData data = mRunningInstalls.get(msg.arg1); 1413 mRunningInstalls.delete(msg.arg1); 1414 boolean deleteOld = false; 1415 1416 if (data != null) { 1417 InstallArgs args = data.args; 1418 PackageInstalledInfo res = data.res; 1419 1420 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1421 final String packageName = res.pkg.applicationInfo.packageName; 1422 res.removedInfo.sendBroadcast(false, true, false); 1423 Bundle extras = new Bundle(1); 1424 extras.putInt(Intent.EXTRA_UID, res.uid); 1425 1426 // Now that we successfully installed the package, grant runtime 1427 // permissions if requested before broadcasting the install. 1428 if ((args.installFlags 1429 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 1430 && res.pkg.applicationInfo.targetSdkVersion 1431 >= Build.VERSION_CODES.M) { 1432 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1433 args.installGrantPermissions); 1434 } 1435 1436 synchronized (mPackages) { 1437 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1438 } 1439 1440 // Determine the set of users who are adding this 1441 // package for the first time vs. those who are seeing 1442 // an update. 1443 int[] firstUsers; 1444 int[] updateUsers = new int[0]; 1445 if (res.origUsers == null || res.origUsers.length == 0) { 1446 firstUsers = res.newUsers; 1447 } else { 1448 firstUsers = new int[0]; 1449 for (int i=0; i<res.newUsers.length; i++) { 1450 int user = res.newUsers[i]; 1451 boolean isNew = true; 1452 for (int j=0; j<res.origUsers.length; j++) { 1453 if (res.origUsers[j] == user) { 1454 isNew = false; 1455 break; 1456 } 1457 } 1458 if (isNew) { 1459 int[] newFirst = new int[firstUsers.length+1]; 1460 System.arraycopy(firstUsers, 0, newFirst, 0, 1461 firstUsers.length); 1462 newFirst[firstUsers.length] = user; 1463 firstUsers = newFirst; 1464 } else { 1465 int[] newUpdate = new int[updateUsers.length+1]; 1466 System.arraycopy(updateUsers, 0, newUpdate, 0, 1467 updateUsers.length); 1468 newUpdate[updateUsers.length] = user; 1469 updateUsers = newUpdate; 1470 } 1471 } 1472 } 1473 // don't broadcast for ephemeral installs/updates 1474 final boolean isEphemeral = isEphemeral(res.pkg); 1475 if (!isEphemeral) { 1476 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1477 extras, 0 /*flags*/, null /*targetPackage*/, 1478 null /*finishedReceiver*/, firstUsers); 1479 } 1480 final boolean update = res.removedInfo.removedPackage != null; 1481 if (update) { 1482 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1483 } 1484 if (!isEphemeral) { 1485 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1486 extras, 0 /*flags*/, null /*targetPackage*/, 1487 null /*finishedReceiver*/, updateUsers); 1488 } 1489 if (update) { 1490 if (!isEphemeral) { 1491 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1492 packageName, extras, 0 /*flags*/, 1493 null /*targetPackage*/, null /*finishedReceiver*/, 1494 updateUsers); 1495 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1496 null /*package*/, null /*extras*/, 0 /*flags*/, 1497 packageName /*targetPackage*/, 1498 null /*finishedReceiver*/, updateUsers); 1499 } 1500 1501 // treat asec-hosted packages like removable media on upgrade 1502 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1503 if (DEBUG_INSTALL) { 1504 Slog.i(TAG, "upgrading pkg " + res.pkg 1505 + " is ASEC-hosted -> AVAILABLE"); 1506 } 1507 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1508 ArrayList<String> pkgList = new ArrayList<String>(1); 1509 pkgList.add(packageName); 1510 sendResourcesChangedBroadcast(true, true, 1511 pkgList,uidArray, null); 1512 } 1513 } 1514 if (res.removedInfo.args != null) { 1515 // Remove the replaced package's older resources safely now 1516 deleteOld = true; 1517 } 1518 1519 1520 // Work that needs to happen on first install within each user 1521 if (firstUsers.length > 0) { 1522 for (int userId : firstUsers) { 1523 synchronized (mPackages) { 1524 // If this app is a browser and it's newly-installed for 1525 // some users, clear any default-browser state in those 1526 // users. The app's nature doesn't depend on the user, 1527 // so we can just check its browser nature in any user 1528 // and generalize. 1529 if (packageIsBrowser(packageName, firstUsers[0])) { 1530 mSettings.setDefaultBrowserPackageNameLPw( 1531 null, userId); 1532 } 1533 1534 // We may also need to apply pending (restored) runtime 1535 // permission grants within these users. 1536 mSettings.applyPendingPermissionGrantsLPw( 1537 packageName, userId); 1538 } 1539 } 1540 } 1541 // Log current value of "unknown sources" setting 1542 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1543 getUnknownSourcesSettings()); 1544 } 1545 // Force a gc to clear up things 1546 Runtime.getRuntime().gc(); 1547 // We delete after a gc for applications on sdcard. 1548 if (deleteOld) { 1549 synchronized (mInstallLock) { 1550 res.removedInfo.args.doPostDeleteLI(true); 1551 } 1552 } 1553 if (args.observer != null) { 1554 try { 1555 Bundle extras = extrasForInstallResult(res); 1556 args.observer.onPackageInstalled(res.name, res.returnCode, 1557 res.returnMsg, extras); 1558 } catch (RemoteException e) { 1559 Slog.i(TAG, "Observer no longer exists."); 1560 } 1561 } 1562 if (args.traceMethod != null) { 1563 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1564 args.traceCookie); 1565 } 1566 return; 1567 } else { 1568 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1569 } 1570 1571 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1572 } break; 1573 case UPDATED_MEDIA_STATUS: { 1574 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1575 boolean reportStatus = msg.arg1 == 1; 1576 boolean doGc = msg.arg2 == 1; 1577 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1578 if (doGc) { 1579 // Force a gc to clear up stale containers. 1580 Runtime.getRuntime().gc(); 1581 } 1582 if (msg.obj != null) { 1583 @SuppressWarnings("unchecked") 1584 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1585 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1586 // Unload containers 1587 unloadAllContainers(args); 1588 } 1589 if (reportStatus) { 1590 try { 1591 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1592 PackageHelper.getMountService().finishMediaUpdate(); 1593 } catch (RemoteException e) { 1594 Log.e(TAG, "MountService not running?"); 1595 } 1596 } 1597 } break; 1598 case WRITE_SETTINGS: { 1599 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1600 synchronized (mPackages) { 1601 removeMessages(WRITE_SETTINGS); 1602 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1603 mSettings.writeLPr(); 1604 mDirtyUsers.clear(); 1605 } 1606 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1607 } break; 1608 case WRITE_PACKAGE_RESTRICTIONS: { 1609 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1610 synchronized (mPackages) { 1611 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1612 for (int userId : mDirtyUsers) { 1613 mSettings.writePackageRestrictionsLPr(userId); 1614 } 1615 mDirtyUsers.clear(); 1616 } 1617 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1618 } break; 1619 case CHECK_PENDING_VERIFICATION: { 1620 final int verificationId = msg.arg1; 1621 final PackageVerificationState state = mPendingVerification.get(verificationId); 1622 1623 if ((state != null) && !state.timeoutExtended()) { 1624 final InstallArgs args = state.getInstallArgs(); 1625 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1626 1627 Slog.i(TAG, "Verification timed out for " + originUri); 1628 mPendingVerification.remove(verificationId); 1629 1630 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1631 1632 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1633 Slog.i(TAG, "Continuing with installation of " + originUri); 1634 state.setVerifierResponse(Binder.getCallingUid(), 1635 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1636 broadcastPackageVerified(verificationId, originUri, 1637 PackageManager.VERIFICATION_ALLOW, 1638 state.getInstallArgs().getUser()); 1639 try { 1640 ret = args.copyApk(mContainerService, true); 1641 } catch (RemoteException e) { 1642 Slog.e(TAG, "Could not contact the ContainerService"); 1643 } 1644 } else { 1645 broadcastPackageVerified(verificationId, originUri, 1646 PackageManager.VERIFICATION_REJECT, 1647 state.getInstallArgs().getUser()); 1648 } 1649 1650 Trace.asyncTraceEnd( 1651 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1652 1653 processPendingInstall(args, ret); 1654 mHandler.sendEmptyMessage(MCS_UNBIND); 1655 } 1656 break; 1657 } 1658 case PACKAGE_VERIFIED: { 1659 final int verificationId = msg.arg1; 1660 1661 final PackageVerificationState state = mPendingVerification.get(verificationId); 1662 if (state == null) { 1663 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1664 break; 1665 } 1666 1667 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1668 1669 state.setVerifierResponse(response.callerUid, response.code); 1670 1671 if (state.isVerificationComplete()) { 1672 mPendingVerification.remove(verificationId); 1673 1674 final InstallArgs args = state.getInstallArgs(); 1675 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1676 1677 int ret; 1678 if (state.isInstallAllowed()) { 1679 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1680 broadcastPackageVerified(verificationId, originUri, 1681 response.code, state.getInstallArgs().getUser()); 1682 try { 1683 ret = args.copyApk(mContainerService, true); 1684 } catch (RemoteException e) { 1685 Slog.e(TAG, "Could not contact the ContainerService"); 1686 } 1687 } else { 1688 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1689 } 1690 1691 Trace.asyncTraceEnd( 1692 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1693 1694 processPendingInstall(args, ret); 1695 mHandler.sendEmptyMessage(MCS_UNBIND); 1696 } 1697 1698 break; 1699 } 1700 case START_INTENT_FILTER_VERIFICATIONS: { 1701 IFVerificationParams params = (IFVerificationParams) msg.obj; 1702 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1703 params.replacing, params.pkg); 1704 break; 1705 } 1706 case INTENT_FILTER_VERIFIED: { 1707 final int verificationId = msg.arg1; 1708 1709 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1710 verificationId); 1711 if (state == null) { 1712 Slog.w(TAG, "Invalid IntentFilter verification token " 1713 + verificationId + " received"); 1714 break; 1715 } 1716 1717 final int userId = state.getUserId(); 1718 1719 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1720 "Processing IntentFilter verification with token:" 1721 + verificationId + " and userId:" + userId); 1722 1723 final IntentFilterVerificationResponse response = 1724 (IntentFilterVerificationResponse) msg.obj; 1725 1726 state.setVerifierResponse(response.callerUid, response.code); 1727 1728 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1729 "IntentFilter verification with token:" + verificationId 1730 + " and userId:" + userId 1731 + " is settings verifier response with response code:" 1732 + response.code); 1733 1734 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1735 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1736 + response.getFailedDomainsString()); 1737 } 1738 1739 if (state.isVerificationComplete()) { 1740 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1741 } else { 1742 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1743 "IntentFilter verification with token:" + verificationId 1744 + " was not said to be complete"); 1745 } 1746 1747 break; 1748 } 1749 } 1750 } 1751 } 1752 1753 private StorageEventListener mStorageListener = new StorageEventListener() { 1754 @Override 1755 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1756 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1757 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1758 final String volumeUuid = vol.getFsUuid(); 1759 1760 // Clean up any users or apps that were removed or recreated 1761 // while this volume was missing 1762 reconcileUsers(volumeUuid); 1763 reconcileApps(volumeUuid); 1764 1765 // Clean up any install sessions that expired or were 1766 // cancelled while this volume was missing 1767 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1768 1769 loadPrivatePackages(vol); 1770 1771 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1772 unloadPrivatePackages(vol); 1773 } 1774 } 1775 1776 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1777 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1778 updateExternalMediaStatus(true, false); 1779 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1780 updateExternalMediaStatus(false, false); 1781 } 1782 } 1783 } 1784 1785 @Override 1786 public void onVolumeForgotten(String fsUuid) { 1787 if (TextUtils.isEmpty(fsUuid)) { 1788 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1789 return; 1790 } 1791 1792 // Remove any apps installed on the forgotten volume 1793 synchronized (mPackages) { 1794 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1795 for (PackageSetting ps : packages) { 1796 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1797 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1798 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1799 } 1800 1801 mSettings.onVolumeForgotten(fsUuid); 1802 mSettings.writeLPr(); 1803 } 1804 } 1805 }; 1806 1807 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1808 String[] grantedPermissions) { 1809 if (userId >= UserHandle.USER_SYSTEM) { 1810 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1811 } else if (userId == UserHandle.USER_ALL) { 1812 final int[] userIds; 1813 synchronized (mPackages) { 1814 userIds = UserManagerService.getInstance().getUserIds(); 1815 } 1816 for (int someUserId : userIds) { 1817 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1818 } 1819 } 1820 1821 // We could have touched GID membership, so flush out packages.list 1822 synchronized (mPackages) { 1823 mSettings.writePackageListLPr(); 1824 } 1825 } 1826 1827 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1828 String[] grantedPermissions) { 1829 SettingBase sb = (SettingBase) pkg.mExtras; 1830 if (sb == null) { 1831 return; 1832 } 1833 1834 PermissionsState permissionsState = sb.getPermissionsState(); 1835 1836 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1837 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1838 1839 synchronized (mPackages) { 1840 for (String permission : pkg.requestedPermissions) { 1841 BasePermission bp = mSettings.mPermissions.get(permission); 1842 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1843 && (grantedPermissions == null 1844 || ArrayUtils.contains(grantedPermissions, permission))) { 1845 final int flags = permissionsState.getPermissionFlags(permission, userId); 1846 // Installer cannot change immutable permissions. 1847 if ((flags & immutableFlags) == 0) { 1848 grantRuntimePermission(pkg.packageName, permission, userId); 1849 } 1850 } 1851 } 1852 } 1853 } 1854 1855 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1856 Bundle extras = null; 1857 switch (res.returnCode) { 1858 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1859 extras = new Bundle(); 1860 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1861 res.origPermission); 1862 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1863 res.origPackage); 1864 break; 1865 } 1866 case PackageManager.INSTALL_SUCCEEDED: { 1867 extras = new Bundle(); 1868 extras.putBoolean(Intent.EXTRA_REPLACING, 1869 res.removedInfo != null && res.removedInfo.removedPackage != null); 1870 break; 1871 } 1872 } 1873 return extras; 1874 } 1875 1876 void scheduleWriteSettingsLocked() { 1877 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1878 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1879 } 1880 } 1881 1882 void scheduleWritePackageRestrictionsLocked(int userId) { 1883 if (!sUserManager.exists(userId)) return; 1884 mDirtyUsers.add(userId); 1885 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1886 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1887 } 1888 } 1889 1890 public static PackageManagerService main(Context context, Installer installer, 1891 boolean factoryTest, boolean onlyCore) { 1892 PackageManagerService m = new PackageManagerService(context, installer, 1893 factoryTest, onlyCore); 1894 m.enableSystemUserPackages(); 1895 ServiceManager.addService("package", m); 1896 return m; 1897 } 1898 1899 private void enableSystemUserPackages() { 1900 if (!UserManager.isSplitSystemUser()) { 1901 return; 1902 } 1903 // For system user, enable apps based on the following conditions: 1904 // - app is whitelisted or belong to one of these groups: 1905 // -- system app which has no launcher icons 1906 // -- system app which has INTERACT_ACROSS_USERS permission 1907 // -- system IME app 1908 // - app is not in the blacklist 1909 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 1910 Set<String> enableApps = new ArraySet<>(); 1911 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 1912 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 1913 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 1914 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 1915 enableApps.addAll(wlApps); 1916 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 1917 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 1918 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 1919 enableApps.removeAll(blApps); 1920 Log.i(TAG, "Applications installed for system user: " + enableApps); 1921 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 1922 UserHandle.SYSTEM); 1923 final int allAppsSize = allAps.size(); 1924 synchronized (mPackages) { 1925 for (int i = 0; i < allAppsSize; i++) { 1926 String pName = allAps.get(i); 1927 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 1928 // Should not happen, but we shouldn't be failing if it does 1929 if (pkgSetting == null) { 1930 continue; 1931 } 1932 boolean install = enableApps.contains(pName); 1933 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 1934 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 1935 + " for system user"); 1936 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 1937 } 1938 } 1939 } 1940 } 1941 1942 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1943 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1944 Context.DISPLAY_SERVICE); 1945 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1946 } 1947 1948 public PackageManagerService(Context context, Installer installer, 1949 boolean factoryTest, boolean onlyCore) { 1950 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1951 SystemClock.uptimeMillis()); 1952 1953 if (mSdkVersion <= 0) { 1954 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1955 } 1956 1957 mContext = context; 1958 mFactoryTest = factoryTest; 1959 mOnlyCore = onlyCore; 1960 mMetrics = new DisplayMetrics(); 1961 mSettings = new Settings(mPackages); 1962 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1963 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1964 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1965 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1966 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1967 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1968 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1969 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1970 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1971 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1972 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1973 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1974 1975 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1976 if (separateProcesses != null && separateProcesses.length() > 0) { 1977 if ("*".equals(separateProcesses)) { 1978 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1979 mSeparateProcesses = null; 1980 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1981 } else { 1982 mDefParseFlags = 0; 1983 mSeparateProcesses = separateProcesses.split(","); 1984 Slog.w(TAG, "Running with debug.separate_processes: " 1985 + separateProcesses); 1986 } 1987 } else { 1988 mDefParseFlags = 0; 1989 mSeparateProcesses = null; 1990 } 1991 1992 mInstaller = installer; 1993 mPackageDexOptimizer = new PackageDexOptimizer(this); 1994 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1995 1996 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1997 FgThread.get().getLooper()); 1998 1999 getDefaultDisplayMetrics(context, mMetrics); 2000 2001 SystemConfig systemConfig = SystemConfig.getInstance(); 2002 mGlobalGids = systemConfig.getGlobalGids(); 2003 mSystemPermissions = systemConfig.getSystemPermissions(); 2004 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2005 2006 synchronized (mInstallLock) { 2007 // writer 2008 synchronized (mPackages) { 2009 mHandlerThread = new ServiceThread(TAG, 2010 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2011 mHandlerThread.start(); 2012 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2013 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2014 2015 File dataDir = Environment.getDataDirectory(); 2016 mAppInstallDir = new File(dataDir, "app"); 2017 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2018 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2019 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2020 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2021 2022 sUserManager = new UserManagerService(context, this, mPackages); 2023 2024 // Propagate permission configuration in to package manager. 2025 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2026 = systemConfig.getPermissions(); 2027 for (int i=0; i<permConfig.size(); i++) { 2028 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2029 BasePermission bp = mSettings.mPermissions.get(perm.name); 2030 if (bp == null) { 2031 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2032 mSettings.mPermissions.put(perm.name, bp); 2033 } 2034 if (perm.gids != null) { 2035 bp.setGids(perm.gids, perm.perUser); 2036 } 2037 } 2038 2039 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2040 for (int i=0; i<libConfig.size(); i++) { 2041 mSharedLibraries.put(libConfig.keyAt(i), 2042 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2043 } 2044 2045 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2046 2047 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2048 2049 String customResolverActivity = Resources.getSystem().getString( 2050 R.string.config_customResolverActivity); 2051 if (TextUtils.isEmpty(customResolverActivity)) { 2052 customResolverActivity = null; 2053 } else { 2054 mCustomResolverComponentName = ComponentName.unflattenFromString( 2055 customResolverActivity); 2056 } 2057 2058 long startTime = SystemClock.uptimeMillis(); 2059 2060 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2061 startTime); 2062 2063 // Set flag to monitor and not change apk file paths when 2064 // scanning install directories. 2065 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2066 2067 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2068 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2069 2070 if (bootClassPath == null) { 2071 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2072 } 2073 2074 if (systemServerClassPath == null) { 2075 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2076 } 2077 2078 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2079 final String[] dexCodeInstructionSets = 2080 getDexCodeInstructionSets( 2081 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2082 2083 /** 2084 * Ensure all external libraries have had dexopt run on them. 2085 */ 2086 if (mSharedLibraries.size() > 0) { 2087 // NOTE: For now, we're compiling these system "shared libraries" 2088 // (and framework jars) into all available architectures. It's possible 2089 // to compile them only when we come across an app that uses them (there's 2090 // already logic for that in scanPackageLI) but that adds some complexity. 2091 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2092 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2093 final String lib = libEntry.path; 2094 if (lib == null) { 2095 continue; 2096 } 2097 2098 try { 2099 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 2100 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2101 // Shared libraries do not have profiles so we perform a full 2102 // AOT compilation. 2103 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2104 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2105 StorageManager.UUID_PRIVATE_INTERNAL, 2106 false /*useProfiles*/); 2107 } 2108 } catch (FileNotFoundException e) { 2109 Slog.w(TAG, "Library not found: " + lib); 2110 } catch (IOException | InstallerException e) { 2111 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2112 + e.getMessage()); 2113 } 2114 } 2115 } 2116 } 2117 2118 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2119 2120 final VersionInfo ver = mSettings.getInternalVersion(); 2121 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2122 // when upgrading from pre-M, promote system app permissions from install to runtime 2123 mPromoteSystemApps = 2124 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2125 2126 // save off the names of pre-existing system packages prior to scanning; we don't 2127 // want to automatically grant runtime permissions for new system apps 2128 if (mPromoteSystemApps) { 2129 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2130 while (pkgSettingIter.hasNext()) { 2131 PackageSetting ps = pkgSettingIter.next(); 2132 if (isSystemApp(ps)) { 2133 mExistingSystemPackages.add(ps.name); 2134 } 2135 } 2136 } 2137 2138 // Collect vendor overlay packages. 2139 // (Do this before scanning any apps.) 2140 // For security and version matching reason, only consider 2141 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2142 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2143 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2144 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2145 2146 // Find base frameworks (resource packages without code). 2147 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2148 | PackageParser.PARSE_IS_SYSTEM_DIR 2149 | PackageParser.PARSE_IS_PRIVILEGED, 2150 scanFlags | SCAN_NO_DEX, 0); 2151 2152 // Collected privileged system packages. 2153 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2154 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2155 | PackageParser.PARSE_IS_SYSTEM_DIR 2156 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2157 2158 // Collect ordinary system packages. 2159 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2160 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2161 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2162 2163 // Collect all vendor packages. 2164 File vendorAppDir = new File("/vendor/app"); 2165 try { 2166 vendorAppDir = vendorAppDir.getCanonicalFile(); 2167 } catch (IOException e) { 2168 // failed to look up canonical path, continue with original one 2169 } 2170 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2171 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2172 2173 // Collect all OEM packages. 2174 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2175 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2176 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2177 2178 // Prune any system packages that no longer exist. 2179 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2180 if (!mOnlyCore) { 2181 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2182 while (psit.hasNext()) { 2183 PackageSetting ps = psit.next(); 2184 2185 /* 2186 * If this is not a system app, it can't be a 2187 * disable system app. 2188 */ 2189 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2190 continue; 2191 } 2192 2193 /* 2194 * If the package is scanned, it's not erased. 2195 */ 2196 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2197 if (scannedPkg != null) { 2198 /* 2199 * If the system app is both scanned and in the 2200 * disabled packages list, then it must have been 2201 * added via OTA. Remove it from the currently 2202 * scanned package so the previously user-installed 2203 * application can be scanned. 2204 */ 2205 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2206 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2207 + ps.name + "; removing system app. Last known codePath=" 2208 + ps.codePathString + ", installStatus=" + ps.installStatus 2209 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2210 + scannedPkg.mVersionCode); 2211 removePackageLI(ps, true); 2212 mExpectingBetter.put(ps.name, ps.codePath); 2213 } 2214 2215 continue; 2216 } 2217 2218 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2219 psit.remove(); 2220 logCriticalInfo(Log.WARN, "System package " + ps.name 2221 + " no longer exists; wiping its data"); 2222 removeDataDirsLI(null, ps.name); 2223 } else { 2224 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2225 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2226 possiblyDeletedUpdatedSystemApps.add(ps.name); 2227 } 2228 } 2229 } 2230 } 2231 2232 //look for any incomplete package installations 2233 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2234 //clean up list 2235 for(int i = 0; i < deletePkgsList.size(); i++) { 2236 //clean up here 2237 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2238 } 2239 //delete tmp files 2240 deleteTempPackageFiles(); 2241 2242 // Remove any shared userIDs that have no associated packages 2243 mSettings.pruneSharedUsersLPw(); 2244 2245 if (!mOnlyCore) { 2246 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2247 SystemClock.uptimeMillis()); 2248 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2249 2250 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2251 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2252 2253 scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL, 2254 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2255 2256 /** 2257 * Remove disable package settings for any updated system 2258 * apps that were removed via an OTA. If they're not a 2259 * previously-updated app, remove them completely. 2260 * Otherwise, just revoke their system-level permissions. 2261 */ 2262 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2263 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2264 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2265 2266 String msg; 2267 if (deletedPkg == null) { 2268 msg = "Updated system package " + deletedAppName 2269 + " no longer exists; wiping its data"; 2270 removeDataDirsLI(null, deletedAppName); 2271 } else { 2272 msg = "Updated system app + " + deletedAppName 2273 + " no longer present; removing system privileges for " 2274 + deletedAppName; 2275 2276 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2277 2278 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2279 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2280 } 2281 logCriticalInfo(Log.WARN, msg); 2282 } 2283 2284 /** 2285 * Make sure all system apps that we expected to appear on 2286 * the userdata partition actually showed up. If they never 2287 * appeared, crawl back and revive the system version. 2288 */ 2289 for (int i = 0; i < mExpectingBetter.size(); i++) { 2290 final String packageName = mExpectingBetter.keyAt(i); 2291 if (!mPackages.containsKey(packageName)) { 2292 final File scanFile = mExpectingBetter.valueAt(i); 2293 2294 logCriticalInfo(Log.WARN, "Expected better " + packageName 2295 + " but never showed up; reverting to system"); 2296 2297 final int reparseFlags; 2298 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2299 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2300 | PackageParser.PARSE_IS_SYSTEM_DIR 2301 | PackageParser.PARSE_IS_PRIVILEGED; 2302 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2303 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2304 | PackageParser.PARSE_IS_SYSTEM_DIR; 2305 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2306 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2307 | PackageParser.PARSE_IS_SYSTEM_DIR; 2308 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2309 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2310 | PackageParser.PARSE_IS_SYSTEM_DIR; 2311 } else { 2312 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2313 continue; 2314 } 2315 2316 mSettings.enableSystemPackageLPw(packageName); 2317 2318 try { 2319 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2320 } catch (PackageManagerException e) { 2321 Slog.e(TAG, "Failed to parse original system package: " 2322 + e.getMessage()); 2323 } 2324 } 2325 } 2326 } 2327 mExpectingBetter.clear(); 2328 2329 // Now that we know all of the shared libraries, update all clients to have 2330 // the correct library paths. 2331 updateAllSharedLibrariesLPw(); 2332 2333 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2334 // NOTE: We ignore potential failures here during a system scan (like 2335 // the rest of the commands above) because there's precious little we 2336 // can do about it. A settings error is reported, though. 2337 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2338 false /* boot complete */); 2339 } 2340 2341 // Now that we know all the packages we are keeping, 2342 // read and update their last usage times. 2343 mPackageUsage.readLP(); 2344 2345 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2346 SystemClock.uptimeMillis()); 2347 Slog.i(TAG, "Time to scan packages: " 2348 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2349 + " seconds"); 2350 2351 // If the platform SDK has changed since the last time we booted, 2352 // we need to re-grant app permission to catch any new ones that 2353 // appear. This is really a hack, and means that apps can in some 2354 // cases get permissions that the user didn't initially explicitly 2355 // allow... it would be nice to have some better way to handle 2356 // this situation. 2357 int updateFlags = UPDATE_PERMISSIONS_ALL; 2358 if (ver.sdkVersion != mSdkVersion) { 2359 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2360 + mSdkVersion + "; regranting permissions for internal storage"); 2361 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2362 } 2363 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2364 ver.sdkVersion = mSdkVersion; 2365 2366 // If this is the first boot or an update from pre-M, and it is a normal 2367 // boot, then we need to initialize the default preferred apps across 2368 // all defined users. 2369 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2370 for (UserInfo user : sUserManager.getUsers(true)) { 2371 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2372 applyFactoryDefaultBrowserLPw(user.id); 2373 primeDomainVerificationsLPw(user.id); 2374 } 2375 } 2376 2377 // Prepare storage for system user really early during boot, 2378 // since core system apps like SettingsProvider and SystemUI 2379 // can't wait for user to start 2380 final int flags; 2381 if (StorageManager.isFileBasedEncryptionEnabled()) { 2382 flags = Installer.FLAG_DE_STORAGE; 2383 } else { 2384 flags = Installer.FLAG_DE_STORAGE | Installer.FLAG_CE_STORAGE; 2385 } 2386 reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, flags); 2387 2388 // If this is first boot after an OTA, and a normal boot, then 2389 // we need to clear code cache directories. 2390 if (mIsUpgrade && !onlyCore) { 2391 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2392 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2393 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2394 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2395 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2396 } 2397 } 2398 ver.fingerprint = Build.FINGERPRINT; 2399 } 2400 2401 checkDefaultBrowser(); 2402 2403 // clear only after permissions and other defaults have been updated 2404 mExistingSystemPackages.clear(); 2405 mPromoteSystemApps = false; 2406 2407 // All the changes are done during package scanning. 2408 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2409 2410 // can downgrade to reader 2411 mSettings.writeLPr(); 2412 2413 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2414 SystemClock.uptimeMillis()); 2415 2416 if (!mOnlyCore) { 2417 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2418 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2419 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2420 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2421 mIntentFilterVerifierComponent); 2422 } else { 2423 mRequiredVerifierPackage = null; 2424 mRequiredInstallerPackage = null; 2425 mIntentFilterVerifierComponent = null; 2426 mIntentFilterVerifier = null; 2427 } 2428 2429 mInstallerService = new PackageInstallerService(context, this); 2430 2431 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2432 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2433 // both the installer and resolver must be present to enable ephemeral 2434 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2435 if (DEBUG_EPHEMERAL) { 2436 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2437 + " installer:" + ephemeralInstallerComponent); 2438 } 2439 mEphemeralResolverComponent = ephemeralResolverComponent; 2440 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2441 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2442 mEphemeralResolverConnection = 2443 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2444 } else { 2445 if (DEBUG_EPHEMERAL) { 2446 final String missingComponent = 2447 (ephemeralResolverComponent == null) 2448 ? (ephemeralInstallerComponent == null) 2449 ? "resolver and installer" 2450 : "resolver" 2451 : "installer"; 2452 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2453 } 2454 mEphemeralResolverComponent = null; 2455 mEphemeralInstallerComponent = null; 2456 mEphemeralResolverConnection = null; 2457 } 2458 2459 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2460 } // synchronized (mPackages) 2461 } // synchronized (mInstallLock) 2462 2463 // Now after opening every single application zip, make sure they 2464 // are all flushed. Not really needed, but keeps things nice and 2465 // tidy. 2466 Runtime.getRuntime().gc(); 2467 2468 // The initial scanning above does many calls into installd while 2469 // holding the mPackages lock, but we're mostly interested in yelling 2470 // once we have a booted system. 2471 mInstaller.setWarnIfHeld(mPackages); 2472 2473 // Expose private service for system components to use. 2474 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2475 } 2476 2477 @Override 2478 public boolean isFirstBoot() { 2479 return !mRestoredSettings; 2480 } 2481 2482 @Override 2483 public boolean isOnlyCoreApps() { 2484 return mOnlyCore; 2485 } 2486 2487 @Override 2488 public boolean isUpgrade() { 2489 return mIsUpgrade; 2490 } 2491 2492 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2493 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2494 2495 final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE, 2496 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2497 if (matches.size() == 1) { 2498 return matches.get(0).getComponentInfo().packageName; 2499 } else { 2500 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2501 return null; 2502 } 2503 } 2504 2505 private @NonNull String getRequiredInstallerLPr() { 2506 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2507 intent.addCategory(Intent.CATEGORY_DEFAULT); 2508 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2509 2510 final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE, 2511 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2512 if (matches.size() == 1) { 2513 return matches.get(0).getComponentInfo().packageName; 2514 } else { 2515 throw new RuntimeException("There must be exactly one installer; found " + matches); 2516 } 2517 } 2518 2519 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2520 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2521 2522 final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE, 2523 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2524 ResolveInfo best = null; 2525 final int N = matches.size(); 2526 for (int i = 0; i < N; i++) { 2527 final ResolveInfo cur = matches.get(i); 2528 final String packageName = cur.getComponentInfo().packageName; 2529 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2530 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2531 continue; 2532 } 2533 2534 if (best == null || cur.priority > best.priority) { 2535 best = cur; 2536 } 2537 } 2538 2539 if (best != null) { 2540 return best.getComponentInfo().getComponentName(); 2541 } else { 2542 throw new RuntimeException("There must be at least one intent filter verifier"); 2543 } 2544 } 2545 2546 private @Nullable ComponentName getEphemeralResolverLPr() { 2547 final String[] packageArray = 2548 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2549 if (packageArray.length == 0) { 2550 if (DEBUG_EPHEMERAL) { 2551 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2552 } 2553 return null; 2554 } 2555 2556 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2557 final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, null, 2558 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2559 2560 final int N = resolvers.size(); 2561 if (N == 0) { 2562 if (DEBUG_EPHEMERAL) { 2563 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2564 } 2565 return null; 2566 } 2567 2568 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2569 for (int i = 0; i < N; i++) { 2570 final ResolveInfo info = resolvers.get(i); 2571 2572 if (info.serviceInfo == null) { 2573 continue; 2574 } 2575 2576 final String packageName = info.serviceInfo.packageName; 2577 if (!possiblePackages.contains(packageName)) { 2578 if (DEBUG_EPHEMERAL) { 2579 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2580 + " pkg: " + packageName + ", info:" + info); 2581 } 2582 continue; 2583 } 2584 2585 if (DEBUG_EPHEMERAL) { 2586 Slog.v(TAG, "Ephemeral resolver found;" 2587 + " pkg: " + packageName + ", info:" + info); 2588 } 2589 return new ComponentName(packageName, info.serviceInfo.name); 2590 } 2591 if (DEBUG_EPHEMERAL) { 2592 Slog.v(TAG, "Ephemeral resolver NOT found"); 2593 } 2594 return null; 2595 } 2596 2597 private @Nullable ComponentName getEphemeralInstallerLPr() { 2598 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2599 intent.addCategory(Intent.CATEGORY_DEFAULT); 2600 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2601 2602 final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE, 2603 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2604 if (matches.size() == 0) { 2605 return null; 2606 } else if (matches.size() == 1) { 2607 return matches.get(0).getComponentInfo().getComponentName(); 2608 } else { 2609 throw new RuntimeException( 2610 "There must be at most one ephemeral installer; found " + matches); 2611 } 2612 } 2613 2614 private void primeDomainVerificationsLPw(int userId) { 2615 if (DEBUG_DOMAIN_VERIFICATION) { 2616 Slog.d(TAG, "Priming domain verifications in user " + userId); 2617 } 2618 2619 SystemConfig systemConfig = SystemConfig.getInstance(); 2620 ArraySet<String> packages = systemConfig.getLinkedApps(); 2621 ArraySet<String> domains = new ArraySet<String>(); 2622 2623 for (String packageName : packages) { 2624 PackageParser.Package pkg = mPackages.get(packageName); 2625 if (pkg != null) { 2626 if (!pkg.isSystemApp()) { 2627 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2628 continue; 2629 } 2630 2631 domains.clear(); 2632 for (PackageParser.Activity a : pkg.activities) { 2633 for (ActivityIntentInfo filter : a.intents) { 2634 if (hasValidDomains(filter)) { 2635 domains.addAll(filter.getHostsList()); 2636 } 2637 } 2638 } 2639 2640 if (domains.size() > 0) { 2641 if (DEBUG_DOMAIN_VERIFICATION) { 2642 Slog.v(TAG, " + " + packageName); 2643 } 2644 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2645 // state w.r.t. the formal app-linkage "no verification attempted" state; 2646 // and then 'always' in the per-user state actually used for intent resolution. 2647 final IntentFilterVerificationInfo ivi; 2648 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2649 new ArrayList<String>(domains)); 2650 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2651 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2652 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2653 } else { 2654 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2655 + "' does not handle web links"); 2656 } 2657 } else { 2658 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2659 } 2660 } 2661 2662 scheduleWritePackageRestrictionsLocked(userId); 2663 scheduleWriteSettingsLocked(); 2664 } 2665 2666 private void applyFactoryDefaultBrowserLPw(int userId) { 2667 // The default browser app's package name is stored in a string resource, 2668 // with a product-specific overlay used for vendor customization. 2669 String browserPkg = mContext.getResources().getString( 2670 com.android.internal.R.string.default_browser); 2671 if (!TextUtils.isEmpty(browserPkg)) { 2672 // non-empty string => required to be a known package 2673 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2674 if (ps == null) { 2675 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2676 browserPkg = null; 2677 } else { 2678 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2679 } 2680 } 2681 2682 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2683 // default. If there's more than one, just leave everything alone. 2684 if (browserPkg == null) { 2685 calculateDefaultBrowserLPw(userId); 2686 } 2687 } 2688 2689 private void calculateDefaultBrowserLPw(int userId) { 2690 List<String> allBrowsers = resolveAllBrowserApps(userId); 2691 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2692 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2693 } 2694 2695 private List<String> resolveAllBrowserApps(int userId) { 2696 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2697 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2698 PackageManager.MATCH_ALL, userId); 2699 2700 final int count = list.size(); 2701 List<String> result = new ArrayList<String>(count); 2702 for (int i=0; i<count; i++) { 2703 ResolveInfo info = list.get(i); 2704 if (info.activityInfo == null 2705 || !info.handleAllWebDataURI 2706 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2707 || result.contains(info.activityInfo.packageName)) { 2708 continue; 2709 } 2710 result.add(info.activityInfo.packageName); 2711 } 2712 2713 return result; 2714 } 2715 2716 private boolean packageIsBrowser(String packageName, int userId) { 2717 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2718 PackageManager.MATCH_ALL, userId); 2719 final int N = list.size(); 2720 for (int i = 0; i < N; i++) { 2721 ResolveInfo info = list.get(i); 2722 if (packageName.equals(info.activityInfo.packageName)) { 2723 return true; 2724 } 2725 } 2726 return false; 2727 } 2728 2729 private void checkDefaultBrowser() { 2730 final int myUserId = UserHandle.myUserId(); 2731 final String packageName = getDefaultBrowserPackageName(myUserId); 2732 if (packageName != null) { 2733 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2734 if (info == null) { 2735 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2736 synchronized (mPackages) { 2737 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2738 } 2739 } 2740 } 2741 } 2742 2743 @Override 2744 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2745 throws RemoteException { 2746 try { 2747 return super.onTransact(code, data, reply, flags); 2748 } catch (RuntimeException e) { 2749 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2750 Slog.wtf(TAG, "Package Manager Crash", e); 2751 } 2752 throw e; 2753 } 2754 } 2755 2756 void cleanupInstallFailedPackage(PackageSetting ps) { 2757 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2758 2759 removeDataDirsLI(ps.volumeUuid, ps.name); 2760 if (ps.codePath != null) { 2761 removeCodePathLI(ps.codePath); 2762 } 2763 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2764 if (ps.resourcePath.isDirectory()) { 2765 FileUtils.deleteContents(ps.resourcePath); 2766 } 2767 ps.resourcePath.delete(); 2768 } 2769 mSettings.removePackageLPw(ps.name); 2770 } 2771 2772 static int[] appendInts(int[] cur, int[] add) { 2773 if (add == null) return cur; 2774 if (cur == null) return add; 2775 final int N = add.length; 2776 for (int i=0; i<N; i++) { 2777 cur = appendInt(cur, add[i]); 2778 } 2779 return cur; 2780 } 2781 2782 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2783 if (!sUserManager.exists(userId)) return null; 2784 final PackageSetting ps = (PackageSetting) p.mExtras; 2785 if (ps == null) { 2786 return null; 2787 } 2788 2789 final PermissionsState permissionsState = ps.getPermissionsState(); 2790 2791 final int[] gids = permissionsState.computeGids(userId); 2792 final Set<String> permissions = permissionsState.getPermissions(userId); 2793 final PackageUserState state = ps.readUserState(userId); 2794 2795 return PackageParser.generatePackageInfo(p, gids, flags, 2796 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2797 } 2798 2799 @Override 2800 public void checkPackageStartable(String packageName, int userId) { 2801 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 2802 2803 synchronized (mPackages) { 2804 final PackageSetting ps = mSettings.mPackages.get(packageName); 2805 if (ps == null) { 2806 throw new SecurityException("Package " + packageName + " was not found!"); 2807 } 2808 2809 if (ps.frozen) { 2810 throw new SecurityException("Package " + packageName + " is currently frozen!"); 2811 } 2812 2813 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware() 2814 || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) { 2815 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 2816 } 2817 } 2818 } 2819 2820 @Override 2821 public boolean isPackageAvailable(String packageName, int userId) { 2822 if (!sUserManager.exists(userId)) return false; 2823 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2824 synchronized (mPackages) { 2825 PackageParser.Package p = mPackages.get(packageName); 2826 if (p != null) { 2827 final PackageSetting ps = (PackageSetting) p.mExtras; 2828 if (ps != null) { 2829 final PackageUserState state = ps.readUserState(userId); 2830 if (state != null) { 2831 return PackageParser.isAvailable(state); 2832 } 2833 } 2834 } 2835 } 2836 return false; 2837 } 2838 2839 @Override 2840 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2841 if (!sUserManager.exists(userId)) return null; 2842 flags = updateFlagsForPackage(flags, userId, packageName); 2843 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2844 // reader 2845 synchronized (mPackages) { 2846 PackageParser.Package p = mPackages.get(packageName); 2847 if (DEBUG_PACKAGE_INFO) 2848 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2849 if (p != null) { 2850 return generatePackageInfo(p, flags, userId); 2851 } 2852 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2853 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2854 } 2855 } 2856 return null; 2857 } 2858 2859 @Override 2860 public String[] currentToCanonicalPackageNames(String[] names) { 2861 String[] out = new String[names.length]; 2862 // reader 2863 synchronized (mPackages) { 2864 for (int i=names.length-1; i>=0; i--) { 2865 PackageSetting ps = mSettings.mPackages.get(names[i]); 2866 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2867 } 2868 } 2869 return out; 2870 } 2871 2872 @Override 2873 public String[] canonicalToCurrentPackageNames(String[] names) { 2874 String[] out = new String[names.length]; 2875 // reader 2876 synchronized (mPackages) { 2877 for (int i=names.length-1; i>=0; i--) { 2878 String cur = mSettings.mRenamedPackages.get(names[i]); 2879 out[i] = cur != null ? cur : names[i]; 2880 } 2881 } 2882 return out; 2883 } 2884 2885 @Override 2886 public int getPackageUid(String packageName, int flags, int userId) { 2887 if (!sUserManager.exists(userId)) return -1; 2888 flags = updateFlagsForPackage(flags, userId, packageName); 2889 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2890 2891 // reader 2892 synchronized (mPackages) { 2893 final PackageParser.Package p = mPackages.get(packageName); 2894 if (p != null && p.isMatch(flags)) { 2895 return UserHandle.getUid(userId, p.applicationInfo.uid); 2896 } 2897 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2898 final PackageSetting ps = mSettings.mPackages.get(packageName); 2899 if (ps != null && ps.isMatch(flags)) { 2900 return UserHandle.getUid(userId, ps.appId); 2901 } 2902 } 2903 } 2904 2905 return -1; 2906 } 2907 2908 @Override 2909 public int[] getPackageGids(String packageName, int flags, int userId) { 2910 if (!sUserManager.exists(userId)) return null; 2911 flags = updateFlagsForPackage(flags, userId, packageName); 2912 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2913 "getPackageGids"); 2914 2915 // reader 2916 synchronized (mPackages) { 2917 final PackageParser.Package p = mPackages.get(packageName); 2918 if (p != null && p.isMatch(flags)) { 2919 PackageSetting ps = (PackageSetting) p.mExtras; 2920 return ps.getPermissionsState().computeGids(userId); 2921 } 2922 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2923 final PackageSetting ps = mSettings.mPackages.get(packageName); 2924 if (ps != null && ps.isMatch(flags)) { 2925 return ps.getPermissionsState().computeGids(userId); 2926 } 2927 } 2928 } 2929 2930 return null; 2931 } 2932 2933 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 2934 if (bp.perm != null) { 2935 return PackageParser.generatePermissionInfo(bp.perm, flags); 2936 } 2937 PermissionInfo pi = new PermissionInfo(); 2938 pi.name = bp.name; 2939 pi.packageName = bp.sourcePackage; 2940 pi.nonLocalizedLabel = bp.name; 2941 pi.protectionLevel = bp.protectionLevel; 2942 return pi; 2943 } 2944 2945 @Override 2946 public PermissionInfo getPermissionInfo(String name, int flags) { 2947 // reader 2948 synchronized (mPackages) { 2949 final BasePermission p = mSettings.mPermissions.get(name); 2950 if (p != null) { 2951 return generatePermissionInfo(p, flags); 2952 } 2953 return null; 2954 } 2955 } 2956 2957 @Override 2958 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2959 // reader 2960 synchronized (mPackages) { 2961 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2962 for (BasePermission p : mSettings.mPermissions.values()) { 2963 if (group == null) { 2964 if (p.perm == null || p.perm.info.group == null) { 2965 out.add(generatePermissionInfo(p, flags)); 2966 } 2967 } else { 2968 if (p.perm != null && group.equals(p.perm.info.group)) { 2969 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2970 } 2971 } 2972 } 2973 2974 if (out.size() > 0) { 2975 return out; 2976 } 2977 return mPermissionGroups.containsKey(group) ? out : null; 2978 } 2979 } 2980 2981 @Override 2982 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2983 // reader 2984 synchronized (mPackages) { 2985 return PackageParser.generatePermissionGroupInfo( 2986 mPermissionGroups.get(name), flags); 2987 } 2988 } 2989 2990 @Override 2991 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2992 // reader 2993 synchronized (mPackages) { 2994 final int N = mPermissionGroups.size(); 2995 ArrayList<PermissionGroupInfo> out 2996 = new ArrayList<PermissionGroupInfo>(N); 2997 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2998 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2999 } 3000 return out; 3001 } 3002 } 3003 3004 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3005 int userId) { 3006 if (!sUserManager.exists(userId)) return null; 3007 PackageSetting ps = mSettings.mPackages.get(packageName); 3008 if (ps != null) { 3009 if (ps.pkg == null) { 3010 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 3011 flags, userId); 3012 if (pInfo != null) { 3013 return pInfo.applicationInfo; 3014 } 3015 return null; 3016 } 3017 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3018 ps.readUserState(userId), userId); 3019 } 3020 return null; 3021 } 3022 3023 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 3024 int userId) { 3025 if (!sUserManager.exists(userId)) return null; 3026 PackageSetting ps = mSettings.mPackages.get(packageName); 3027 if (ps != null) { 3028 PackageParser.Package pkg = ps.pkg; 3029 if (pkg == null) { 3030 if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) { 3031 return null; 3032 } 3033 // Only data remains, so we aren't worried about code paths 3034 pkg = new PackageParser.Package(packageName); 3035 pkg.applicationInfo.packageName = packageName; 3036 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 3037 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 3038 pkg.applicationInfo.uid = ps.appId; 3039 pkg.applicationInfo.initForUser(userId); 3040 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 3041 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 3042 } 3043 return generatePackageInfo(pkg, flags, userId); 3044 } 3045 return null; 3046 } 3047 3048 @Override 3049 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3050 if (!sUserManager.exists(userId)) return null; 3051 flags = updateFlagsForApplication(flags, userId, packageName); 3052 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 3053 // writer 3054 synchronized (mPackages) { 3055 PackageParser.Package p = mPackages.get(packageName); 3056 if (DEBUG_PACKAGE_INFO) Log.v( 3057 TAG, "getApplicationInfo " + packageName 3058 + ": " + p); 3059 if (p != null) { 3060 PackageSetting ps = mSettings.mPackages.get(packageName); 3061 if (ps == null) return null; 3062 // Note: isEnabledLP() does not apply here - always return info 3063 return PackageParser.generateApplicationInfo( 3064 p, flags, ps.readUserState(userId), userId); 3065 } 3066 if ("android".equals(packageName)||"system".equals(packageName)) { 3067 return mAndroidApplication; 3068 } 3069 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3070 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3071 } 3072 } 3073 return null; 3074 } 3075 3076 @Override 3077 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3078 final IPackageDataObserver observer) { 3079 mContext.enforceCallingOrSelfPermission( 3080 android.Manifest.permission.CLEAR_APP_CACHE, null); 3081 // Queue up an async operation since clearing cache may take a little while. 3082 mHandler.post(new Runnable() { 3083 public void run() { 3084 mHandler.removeCallbacks(this); 3085 boolean success = true; 3086 synchronized (mInstallLock) { 3087 try { 3088 mInstaller.freeCache(volumeUuid, freeStorageSize); 3089 } catch (InstallerException e) { 3090 Slog.w(TAG, "Couldn't clear application caches: " + e); 3091 success = false; 3092 } 3093 } 3094 if (observer != null) { 3095 try { 3096 observer.onRemoveCompleted(null, success); 3097 } catch (RemoteException e) { 3098 Slog.w(TAG, "RemoveException when invoking call back"); 3099 } 3100 } 3101 } 3102 }); 3103 } 3104 3105 @Override 3106 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3107 final IntentSender pi) { 3108 mContext.enforceCallingOrSelfPermission( 3109 android.Manifest.permission.CLEAR_APP_CACHE, null); 3110 // Queue up an async operation since clearing cache may take a little while. 3111 mHandler.post(new Runnable() { 3112 public void run() { 3113 mHandler.removeCallbacks(this); 3114 boolean success = true; 3115 synchronized (mInstallLock) { 3116 try { 3117 mInstaller.freeCache(volumeUuid, freeStorageSize); 3118 } catch (InstallerException e) { 3119 Slog.w(TAG, "Couldn't clear application caches: " + e); 3120 success = false; 3121 } 3122 } 3123 if(pi != null) { 3124 try { 3125 // Callback via pending intent 3126 int code = success ? 1 : 0; 3127 pi.sendIntent(null, code, null, 3128 null, null); 3129 } catch (SendIntentException e1) { 3130 Slog.i(TAG, "Failed to send pending intent"); 3131 } 3132 } 3133 } 3134 }); 3135 } 3136 3137 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3138 synchronized (mInstallLock) { 3139 try { 3140 mInstaller.freeCache(volumeUuid, freeStorageSize); 3141 } catch (InstallerException e) { 3142 throw new IOException("Failed to free enough space", e); 3143 } 3144 } 3145 } 3146 3147 /** 3148 * Return if the user key is currently unlocked. 3149 */ 3150 private boolean isUserKeyUnlocked(int userId) { 3151 if (StorageManager.isFileBasedEncryptionEnabled()) { 3152 final IMountService mount = IMountService.Stub 3153 .asInterface(ServiceManager.getService("mount")); 3154 if (mount == null) { 3155 Slog.w(TAG, "Early during boot, assuming locked"); 3156 return false; 3157 } 3158 final long token = Binder.clearCallingIdentity(); 3159 try { 3160 return mount.isUserKeyUnlocked(userId); 3161 } catch (RemoteException e) { 3162 throw e.rethrowAsRuntimeException(); 3163 } finally { 3164 Binder.restoreCallingIdentity(token); 3165 } 3166 } else { 3167 return true; 3168 } 3169 } 3170 3171 /** 3172 * Update given flags based on encryption status of current user. 3173 */ 3174 private int updateFlags(int flags, int userId) { 3175 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3176 | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) { 3177 // Caller expressed an explicit opinion about what encryption 3178 // aware/unaware components they want to see, so fall through and 3179 // give them what they want 3180 } else { 3181 // Caller expressed no opinion, so match based on user state 3182 if (isUserKeyUnlocked(userId)) { 3183 flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE; 3184 } else { 3185 flags |= PackageManager.MATCH_ENCRYPTION_AWARE; 3186 } 3187 } 3188 3189 // Safe mode means we should ignore any third-party apps 3190 if (mSafeMode) { 3191 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3192 } 3193 3194 return flags; 3195 } 3196 3197 /** 3198 * Update given flags when being used to request {@link PackageInfo}. 3199 */ 3200 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3201 boolean triaged = true; 3202 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3203 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3204 // Caller is asking for component details, so they'd better be 3205 // asking for specific encryption matching behavior, or be triaged 3206 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3207 | PackageManager.MATCH_ENCRYPTION_AWARE 3208 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3209 triaged = false; 3210 } 3211 } 3212 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3213 | PackageManager.MATCH_SYSTEM_ONLY 3214 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3215 triaged = false; 3216 } 3217 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3218 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3219 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3220 } 3221 return updateFlags(flags, userId); 3222 } 3223 3224 /** 3225 * Update given flags when being used to request {@link ApplicationInfo}. 3226 */ 3227 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3228 return updateFlagsForPackage(flags, userId, cookie); 3229 } 3230 3231 /** 3232 * Update given flags when being used to request {@link ComponentInfo}. 3233 */ 3234 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3235 if (cookie instanceof Intent) { 3236 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3237 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3238 } 3239 } 3240 3241 boolean triaged = true; 3242 // Caller is asking for component details, so they'd better be 3243 // asking for specific encryption matching behavior, or be triaged 3244 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3245 | PackageManager.MATCH_ENCRYPTION_AWARE 3246 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3247 triaged = false; 3248 } 3249 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3250 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3251 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3252 } 3253 return updateFlags(flags, userId); 3254 } 3255 3256 /** 3257 * Update given flags when being used to request {@link ResolveInfo}. 3258 */ 3259 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3260 return updateFlagsForComponent(flags, userId, cookie); 3261 } 3262 3263 @Override 3264 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3265 if (!sUserManager.exists(userId)) return null; 3266 flags = updateFlagsForComponent(flags, userId, component); 3267 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 3268 synchronized (mPackages) { 3269 PackageParser.Activity a = mActivities.mActivities.get(component); 3270 3271 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3272 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3273 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3274 if (ps == null) return null; 3275 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3276 userId); 3277 } 3278 if (mResolveComponentName.equals(component)) { 3279 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3280 new PackageUserState(), userId); 3281 } 3282 } 3283 return null; 3284 } 3285 3286 @Override 3287 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3288 String resolvedType) { 3289 synchronized (mPackages) { 3290 if (component.equals(mResolveComponentName)) { 3291 // The resolver supports EVERYTHING! 3292 return true; 3293 } 3294 PackageParser.Activity a = mActivities.mActivities.get(component); 3295 if (a == null) { 3296 return false; 3297 } 3298 for (int i=0; i<a.intents.size(); i++) { 3299 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3300 intent.getData(), intent.getCategories(), TAG) >= 0) { 3301 return true; 3302 } 3303 } 3304 return false; 3305 } 3306 } 3307 3308 @Override 3309 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3310 if (!sUserManager.exists(userId)) return null; 3311 flags = updateFlagsForComponent(flags, userId, component); 3312 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3313 synchronized (mPackages) { 3314 PackageParser.Activity a = mReceivers.mActivities.get(component); 3315 if (DEBUG_PACKAGE_INFO) Log.v( 3316 TAG, "getReceiverInfo " + component + ": " + a); 3317 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3318 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3319 if (ps == null) return null; 3320 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3321 userId); 3322 } 3323 } 3324 return null; 3325 } 3326 3327 @Override 3328 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3329 if (!sUserManager.exists(userId)) return null; 3330 flags = updateFlagsForComponent(flags, userId, component); 3331 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3332 synchronized (mPackages) { 3333 PackageParser.Service s = mServices.mServices.get(component); 3334 if (DEBUG_PACKAGE_INFO) Log.v( 3335 TAG, "getServiceInfo " + component + ": " + s); 3336 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3337 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3338 if (ps == null) return null; 3339 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3340 userId); 3341 } 3342 } 3343 return null; 3344 } 3345 3346 @Override 3347 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3348 if (!sUserManager.exists(userId)) return null; 3349 flags = updateFlagsForComponent(flags, userId, component); 3350 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3351 synchronized (mPackages) { 3352 PackageParser.Provider p = mProviders.mProviders.get(component); 3353 if (DEBUG_PACKAGE_INFO) Log.v( 3354 TAG, "getProviderInfo " + component + ": " + p); 3355 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3356 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3357 if (ps == null) return null; 3358 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3359 userId); 3360 } 3361 } 3362 return null; 3363 } 3364 3365 @Override 3366 public String[] getSystemSharedLibraryNames() { 3367 Set<String> libSet; 3368 synchronized (mPackages) { 3369 libSet = mSharedLibraries.keySet(); 3370 int size = libSet.size(); 3371 if (size > 0) { 3372 String[] libs = new String[size]; 3373 libSet.toArray(libs); 3374 return libs; 3375 } 3376 } 3377 return null; 3378 } 3379 3380 /** 3381 * @hide 3382 */ 3383 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3384 synchronized (mPackages) { 3385 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3386 if (lib != null && lib.apk != null) { 3387 return mPackages.get(lib.apk); 3388 } 3389 } 3390 return null; 3391 } 3392 3393 @Override 3394 public FeatureInfo[] getSystemAvailableFeatures() { 3395 Collection<FeatureInfo> featSet; 3396 synchronized (mPackages) { 3397 featSet = mAvailableFeatures.values(); 3398 int size = featSet.size(); 3399 if (size > 0) { 3400 FeatureInfo[] features = new FeatureInfo[size+1]; 3401 featSet.toArray(features); 3402 FeatureInfo fi = new FeatureInfo(); 3403 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3404 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3405 features[size] = fi; 3406 return features; 3407 } 3408 } 3409 return null; 3410 } 3411 3412 @Override 3413 public boolean hasSystemFeature(String name) { 3414 synchronized (mPackages) { 3415 return mAvailableFeatures.containsKey(name); 3416 } 3417 } 3418 3419 @Override 3420 public int checkPermission(String permName, String pkgName, int userId) { 3421 if (!sUserManager.exists(userId)) { 3422 return PackageManager.PERMISSION_DENIED; 3423 } 3424 3425 synchronized (mPackages) { 3426 final PackageParser.Package p = mPackages.get(pkgName); 3427 if (p != null && p.mExtras != null) { 3428 final PackageSetting ps = (PackageSetting) p.mExtras; 3429 final PermissionsState permissionsState = ps.getPermissionsState(); 3430 if (permissionsState.hasPermission(permName, userId)) { 3431 return PackageManager.PERMISSION_GRANTED; 3432 } 3433 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3434 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3435 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3436 return PackageManager.PERMISSION_GRANTED; 3437 } 3438 } 3439 } 3440 3441 return PackageManager.PERMISSION_DENIED; 3442 } 3443 3444 @Override 3445 public int checkUidPermission(String permName, int uid) { 3446 final int userId = UserHandle.getUserId(uid); 3447 3448 if (!sUserManager.exists(userId)) { 3449 return PackageManager.PERMISSION_DENIED; 3450 } 3451 3452 synchronized (mPackages) { 3453 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3454 if (obj != null) { 3455 final SettingBase ps = (SettingBase) obj; 3456 final PermissionsState permissionsState = ps.getPermissionsState(); 3457 if (permissionsState.hasPermission(permName, userId)) { 3458 return PackageManager.PERMISSION_GRANTED; 3459 } 3460 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3461 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3462 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3463 return PackageManager.PERMISSION_GRANTED; 3464 } 3465 } else { 3466 ArraySet<String> perms = mSystemPermissions.get(uid); 3467 if (perms != null) { 3468 if (perms.contains(permName)) { 3469 return PackageManager.PERMISSION_GRANTED; 3470 } 3471 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3472 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3473 return PackageManager.PERMISSION_GRANTED; 3474 } 3475 } 3476 } 3477 } 3478 3479 return PackageManager.PERMISSION_DENIED; 3480 } 3481 3482 @Override 3483 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3484 if (UserHandle.getCallingUserId() != userId) { 3485 mContext.enforceCallingPermission( 3486 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3487 "isPermissionRevokedByPolicy for user " + userId); 3488 } 3489 3490 if (checkPermission(permission, packageName, userId) 3491 == PackageManager.PERMISSION_GRANTED) { 3492 return false; 3493 } 3494 3495 final long identity = Binder.clearCallingIdentity(); 3496 try { 3497 final int flags = getPermissionFlags(permission, packageName, userId); 3498 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3499 } finally { 3500 Binder.restoreCallingIdentity(identity); 3501 } 3502 } 3503 3504 @Override 3505 public String getPermissionControllerPackageName() { 3506 synchronized (mPackages) { 3507 return mRequiredInstallerPackage; 3508 } 3509 } 3510 3511 /** 3512 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3513 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3514 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3515 * @param message the message to log on security exception 3516 */ 3517 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3518 boolean checkShell, String message) { 3519 if (userId < 0) { 3520 throw new IllegalArgumentException("Invalid userId " + userId); 3521 } 3522 if (checkShell) { 3523 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3524 } 3525 if (userId == UserHandle.getUserId(callingUid)) return; 3526 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3527 if (requireFullPermission) { 3528 mContext.enforceCallingOrSelfPermission( 3529 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3530 } else { 3531 try { 3532 mContext.enforceCallingOrSelfPermission( 3533 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3534 } catch (SecurityException se) { 3535 mContext.enforceCallingOrSelfPermission( 3536 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3537 } 3538 } 3539 } 3540 } 3541 3542 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3543 if (callingUid == Process.SHELL_UID) { 3544 if (userHandle >= 0 3545 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3546 throw new SecurityException("Shell does not have permission to access user " 3547 + userHandle); 3548 } else if (userHandle < 0) { 3549 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3550 + Debug.getCallers(3)); 3551 } 3552 } 3553 } 3554 3555 private BasePermission findPermissionTreeLP(String permName) { 3556 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3557 if (permName.startsWith(bp.name) && 3558 permName.length() > bp.name.length() && 3559 permName.charAt(bp.name.length()) == '.') { 3560 return bp; 3561 } 3562 } 3563 return null; 3564 } 3565 3566 private BasePermission checkPermissionTreeLP(String permName) { 3567 if (permName != null) { 3568 BasePermission bp = findPermissionTreeLP(permName); 3569 if (bp != null) { 3570 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3571 return bp; 3572 } 3573 throw new SecurityException("Calling uid " 3574 + Binder.getCallingUid() 3575 + " is not allowed to add to permission tree " 3576 + bp.name + " owned by uid " + bp.uid); 3577 } 3578 } 3579 throw new SecurityException("No permission tree found for " + permName); 3580 } 3581 3582 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3583 if (s1 == null) { 3584 return s2 == null; 3585 } 3586 if (s2 == null) { 3587 return false; 3588 } 3589 if (s1.getClass() != s2.getClass()) { 3590 return false; 3591 } 3592 return s1.equals(s2); 3593 } 3594 3595 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3596 if (pi1.icon != pi2.icon) return false; 3597 if (pi1.logo != pi2.logo) return false; 3598 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3599 if (!compareStrings(pi1.name, pi2.name)) return false; 3600 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3601 // We'll take care of setting this one. 3602 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3603 // These are not currently stored in settings. 3604 //if (!compareStrings(pi1.group, pi2.group)) return false; 3605 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3606 //if (pi1.labelRes != pi2.labelRes) return false; 3607 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3608 return true; 3609 } 3610 3611 int permissionInfoFootprint(PermissionInfo info) { 3612 int size = info.name.length(); 3613 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3614 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3615 return size; 3616 } 3617 3618 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3619 int size = 0; 3620 for (BasePermission perm : mSettings.mPermissions.values()) { 3621 if (perm.uid == tree.uid) { 3622 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3623 } 3624 } 3625 return size; 3626 } 3627 3628 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3629 // We calculate the max size of permissions defined by this uid and throw 3630 // if that plus the size of 'info' would exceed our stated maximum. 3631 if (tree.uid != Process.SYSTEM_UID) { 3632 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3633 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3634 throw new SecurityException("Permission tree size cap exceeded"); 3635 } 3636 } 3637 } 3638 3639 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3640 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3641 throw new SecurityException("Label must be specified in permission"); 3642 } 3643 BasePermission tree = checkPermissionTreeLP(info.name); 3644 BasePermission bp = mSettings.mPermissions.get(info.name); 3645 boolean added = bp == null; 3646 boolean changed = true; 3647 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3648 if (added) { 3649 enforcePermissionCapLocked(info, tree); 3650 bp = new BasePermission(info.name, tree.sourcePackage, 3651 BasePermission.TYPE_DYNAMIC); 3652 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3653 throw new SecurityException( 3654 "Not allowed to modify non-dynamic permission " 3655 + info.name); 3656 } else { 3657 if (bp.protectionLevel == fixedLevel 3658 && bp.perm.owner.equals(tree.perm.owner) 3659 && bp.uid == tree.uid 3660 && comparePermissionInfos(bp.perm.info, info)) { 3661 changed = false; 3662 } 3663 } 3664 bp.protectionLevel = fixedLevel; 3665 info = new PermissionInfo(info); 3666 info.protectionLevel = fixedLevel; 3667 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3668 bp.perm.info.packageName = tree.perm.info.packageName; 3669 bp.uid = tree.uid; 3670 if (added) { 3671 mSettings.mPermissions.put(info.name, bp); 3672 } 3673 if (changed) { 3674 if (!async) { 3675 mSettings.writeLPr(); 3676 } else { 3677 scheduleWriteSettingsLocked(); 3678 } 3679 } 3680 return added; 3681 } 3682 3683 @Override 3684 public boolean addPermission(PermissionInfo info) { 3685 synchronized (mPackages) { 3686 return addPermissionLocked(info, false); 3687 } 3688 } 3689 3690 @Override 3691 public boolean addPermissionAsync(PermissionInfo info) { 3692 synchronized (mPackages) { 3693 return addPermissionLocked(info, true); 3694 } 3695 } 3696 3697 @Override 3698 public void removePermission(String name) { 3699 synchronized (mPackages) { 3700 checkPermissionTreeLP(name); 3701 BasePermission bp = mSettings.mPermissions.get(name); 3702 if (bp != null) { 3703 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3704 throw new SecurityException( 3705 "Not allowed to modify non-dynamic permission " 3706 + name); 3707 } 3708 mSettings.mPermissions.remove(name); 3709 mSettings.writeLPr(); 3710 } 3711 } 3712 } 3713 3714 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3715 BasePermission bp) { 3716 int index = pkg.requestedPermissions.indexOf(bp.name); 3717 if (index == -1) { 3718 throw new SecurityException("Package " + pkg.packageName 3719 + " has not requested permission " + bp.name); 3720 } 3721 if (!bp.isRuntime() && !bp.isDevelopment()) { 3722 throw new SecurityException("Permission " + bp.name 3723 + " is not a changeable permission type"); 3724 } 3725 } 3726 3727 @Override 3728 public void grantRuntimePermission(String packageName, String name, final int userId) { 3729 if (!sUserManager.exists(userId)) { 3730 Log.e(TAG, "No such user:" + userId); 3731 return; 3732 } 3733 3734 mContext.enforceCallingOrSelfPermission( 3735 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3736 "grantRuntimePermission"); 3737 3738 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3739 "grantRuntimePermission"); 3740 3741 final int uid; 3742 final SettingBase sb; 3743 3744 synchronized (mPackages) { 3745 final PackageParser.Package pkg = mPackages.get(packageName); 3746 if (pkg == null) { 3747 throw new IllegalArgumentException("Unknown package: " + packageName); 3748 } 3749 3750 final BasePermission bp = mSettings.mPermissions.get(name); 3751 if (bp == null) { 3752 throw new IllegalArgumentException("Unknown permission: " + name); 3753 } 3754 3755 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3756 3757 // If a permission review is required for legacy apps we represent 3758 // their permissions as always granted runtime ones since we need 3759 // to keep the review required permission flag per user while an 3760 // install permission's state is shared across all users. 3761 if (Build.PERMISSIONS_REVIEW_REQUIRED 3762 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3763 && bp.isRuntime()) { 3764 return; 3765 } 3766 3767 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3768 sb = (SettingBase) pkg.mExtras; 3769 if (sb == null) { 3770 throw new IllegalArgumentException("Unknown package: " + packageName); 3771 } 3772 3773 final PermissionsState permissionsState = sb.getPermissionsState(); 3774 3775 final int flags = permissionsState.getPermissionFlags(name, userId); 3776 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3777 throw new SecurityException("Cannot grant system fixed permission " 3778 + name + " for package " + packageName); 3779 } 3780 3781 if (bp.isDevelopment()) { 3782 // Development permissions must be handled specially, since they are not 3783 // normal runtime permissions. For now they apply to all users. 3784 if (permissionsState.grantInstallPermission(bp) != 3785 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3786 scheduleWriteSettingsLocked(); 3787 } 3788 return; 3789 } 3790 3791 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 3792 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 3793 return; 3794 } 3795 3796 final int result = permissionsState.grantRuntimePermission(bp, userId); 3797 switch (result) { 3798 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3799 return; 3800 } 3801 3802 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3803 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3804 mHandler.post(new Runnable() { 3805 @Override 3806 public void run() { 3807 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3808 } 3809 }); 3810 } 3811 break; 3812 } 3813 3814 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3815 3816 // Not critical if that is lost - app has to request again. 3817 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3818 } 3819 3820 // Only need to do this if user is initialized. Otherwise it's a new user 3821 // and there are no processes running as the user yet and there's no need 3822 // to make an expensive call to remount processes for the changed permissions. 3823 if (READ_EXTERNAL_STORAGE.equals(name) 3824 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3825 final long token = Binder.clearCallingIdentity(); 3826 try { 3827 if (sUserManager.isInitialized(userId)) { 3828 MountServiceInternal mountServiceInternal = LocalServices.getService( 3829 MountServiceInternal.class); 3830 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3831 } 3832 } finally { 3833 Binder.restoreCallingIdentity(token); 3834 } 3835 } 3836 } 3837 3838 @Override 3839 public void revokeRuntimePermission(String packageName, String name, int userId) { 3840 if (!sUserManager.exists(userId)) { 3841 Log.e(TAG, "No such user:" + userId); 3842 return; 3843 } 3844 3845 mContext.enforceCallingOrSelfPermission( 3846 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3847 "revokeRuntimePermission"); 3848 3849 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3850 "revokeRuntimePermission"); 3851 3852 final int appId; 3853 3854 synchronized (mPackages) { 3855 final PackageParser.Package pkg = mPackages.get(packageName); 3856 if (pkg == null) { 3857 throw new IllegalArgumentException("Unknown package: " + packageName); 3858 } 3859 3860 final BasePermission bp = mSettings.mPermissions.get(name); 3861 if (bp == null) { 3862 throw new IllegalArgumentException("Unknown permission: " + name); 3863 } 3864 3865 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3866 3867 // If a permission review is required for legacy apps we represent 3868 // their permissions as always granted runtime ones since we need 3869 // to keep the review required permission flag per user while an 3870 // install permission's state is shared across all users. 3871 if (Build.PERMISSIONS_REVIEW_REQUIRED 3872 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3873 && bp.isRuntime()) { 3874 return; 3875 } 3876 3877 SettingBase sb = (SettingBase) pkg.mExtras; 3878 if (sb == null) { 3879 throw new IllegalArgumentException("Unknown package: " + packageName); 3880 } 3881 3882 final PermissionsState permissionsState = sb.getPermissionsState(); 3883 3884 final int flags = permissionsState.getPermissionFlags(name, userId); 3885 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3886 throw new SecurityException("Cannot revoke system fixed permission " 3887 + name + " for package " + packageName); 3888 } 3889 3890 if (bp.isDevelopment()) { 3891 // Development permissions must be handled specially, since they are not 3892 // normal runtime permissions. For now they apply to all users. 3893 if (permissionsState.revokeInstallPermission(bp) != 3894 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3895 scheduleWriteSettingsLocked(); 3896 } 3897 return; 3898 } 3899 3900 if (permissionsState.revokeRuntimePermission(bp, userId) == 3901 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3902 return; 3903 } 3904 3905 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3906 3907 // Critical, after this call app should never have the permission. 3908 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3909 3910 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3911 } 3912 3913 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3914 } 3915 3916 @Override 3917 public void resetRuntimePermissions() { 3918 mContext.enforceCallingOrSelfPermission( 3919 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3920 "revokeRuntimePermission"); 3921 3922 int callingUid = Binder.getCallingUid(); 3923 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3924 mContext.enforceCallingOrSelfPermission( 3925 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3926 "resetRuntimePermissions"); 3927 } 3928 3929 synchronized (mPackages) { 3930 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3931 for (int userId : UserManagerService.getInstance().getUserIds()) { 3932 final int packageCount = mPackages.size(); 3933 for (int i = 0; i < packageCount; i++) { 3934 PackageParser.Package pkg = mPackages.valueAt(i); 3935 if (!(pkg.mExtras instanceof PackageSetting)) { 3936 continue; 3937 } 3938 PackageSetting ps = (PackageSetting) pkg.mExtras; 3939 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3940 } 3941 } 3942 } 3943 } 3944 3945 @Override 3946 public int getPermissionFlags(String name, String packageName, int userId) { 3947 if (!sUserManager.exists(userId)) { 3948 return 0; 3949 } 3950 3951 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3952 3953 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3954 "getPermissionFlags"); 3955 3956 synchronized (mPackages) { 3957 final PackageParser.Package pkg = mPackages.get(packageName); 3958 if (pkg == null) { 3959 throw new IllegalArgumentException("Unknown package: " + packageName); 3960 } 3961 3962 final BasePermission bp = mSettings.mPermissions.get(name); 3963 if (bp == null) { 3964 throw new IllegalArgumentException("Unknown permission: " + name); 3965 } 3966 3967 SettingBase sb = (SettingBase) pkg.mExtras; 3968 if (sb == null) { 3969 throw new IllegalArgumentException("Unknown package: " + packageName); 3970 } 3971 3972 PermissionsState permissionsState = sb.getPermissionsState(); 3973 return permissionsState.getPermissionFlags(name, userId); 3974 } 3975 } 3976 3977 @Override 3978 public void updatePermissionFlags(String name, String packageName, int flagMask, 3979 int flagValues, int userId) { 3980 if (!sUserManager.exists(userId)) { 3981 return; 3982 } 3983 3984 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3985 3986 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3987 "updatePermissionFlags"); 3988 3989 // Only the system can change these flags and nothing else. 3990 if (getCallingUid() != Process.SYSTEM_UID) { 3991 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3992 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3993 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3994 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3995 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 3996 } 3997 3998 synchronized (mPackages) { 3999 final PackageParser.Package pkg = mPackages.get(packageName); 4000 if (pkg == null) { 4001 throw new IllegalArgumentException("Unknown package: " + packageName); 4002 } 4003 4004 final BasePermission bp = mSettings.mPermissions.get(name); 4005 if (bp == null) { 4006 throw new IllegalArgumentException("Unknown permission: " + name); 4007 } 4008 4009 SettingBase sb = (SettingBase) pkg.mExtras; 4010 if (sb == null) { 4011 throw new IllegalArgumentException("Unknown package: " + packageName); 4012 } 4013 4014 PermissionsState permissionsState = sb.getPermissionsState(); 4015 4016 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4017 4018 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4019 // Install and runtime permissions are stored in different places, 4020 // so figure out what permission changed and persist the change. 4021 if (permissionsState.getInstallPermissionState(name) != null) { 4022 scheduleWriteSettingsLocked(); 4023 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4024 || hadState) { 4025 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4026 } 4027 } 4028 } 4029 } 4030 4031 /** 4032 * Update the permission flags for all packages and runtime permissions of a user in order 4033 * to allow device or profile owner to remove POLICY_FIXED. 4034 */ 4035 @Override 4036 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4037 if (!sUserManager.exists(userId)) { 4038 return; 4039 } 4040 4041 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4042 4043 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 4044 "updatePermissionFlagsForAllApps"); 4045 4046 // Only the system can change system fixed flags. 4047 if (getCallingUid() != Process.SYSTEM_UID) { 4048 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4049 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4050 } 4051 4052 synchronized (mPackages) { 4053 boolean changed = false; 4054 final int packageCount = mPackages.size(); 4055 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4056 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4057 SettingBase sb = (SettingBase) pkg.mExtras; 4058 if (sb == null) { 4059 continue; 4060 } 4061 PermissionsState permissionsState = sb.getPermissionsState(); 4062 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4063 userId, flagMask, flagValues); 4064 } 4065 if (changed) { 4066 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4067 } 4068 } 4069 } 4070 4071 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4072 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4073 != PackageManager.PERMISSION_GRANTED 4074 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4075 != PackageManager.PERMISSION_GRANTED) { 4076 throw new SecurityException(message + " requires " 4077 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4078 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4079 } 4080 } 4081 4082 @Override 4083 public boolean shouldShowRequestPermissionRationale(String permissionName, 4084 String packageName, int userId) { 4085 if (UserHandle.getCallingUserId() != userId) { 4086 mContext.enforceCallingPermission( 4087 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4088 "canShowRequestPermissionRationale for user " + userId); 4089 } 4090 4091 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4092 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4093 return false; 4094 } 4095 4096 if (checkPermission(permissionName, packageName, userId) 4097 == PackageManager.PERMISSION_GRANTED) { 4098 return false; 4099 } 4100 4101 final int flags; 4102 4103 final long identity = Binder.clearCallingIdentity(); 4104 try { 4105 flags = getPermissionFlags(permissionName, 4106 packageName, userId); 4107 } finally { 4108 Binder.restoreCallingIdentity(identity); 4109 } 4110 4111 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4112 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4113 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4114 4115 if ((flags & fixedFlags) != 0) { 4116 return false; 4117 } 4118 4119 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4120 } 4121 4122 @Override 4123 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4124 mContext.enforceCallingOrSelfPermission( 4125 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4126 "addOnPermissionsChangeListener"); 4127 4128 synchronized (mPackages) { 4129 mOnPermissionChangeListeners.addListenerLocked(listener); 4130 } 4131 } 4132 4133 @Override 4134 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4135 synchronized (mPackages) { 4136 mOnPermissionChangeListeners.removeListenerLocked(listener); 4137 } 4138 } 4139 4140 @Override 4141 public boolean isProtectedBroadcast(String actionName) { 4142 synchronized (mPackages) { 4143 if (mProtectedBroadcasts.contains(actionName)) { 4144 return true; 4145 } else if (actionName != null) { 4146 // TODO: remove these terrible hacks 4147 if (actionName.startsWith("android.net.netmon.lingerExpired") 4148 || actionName.startsWith("com.android.server.sip.SipWakeupTimer")) { 4149 return true; 4150 } 4151 } 4152 } 4153 return false; 4154 } 4155 4156 @Override 4157 public int checkSignatures(String pkg1, String pkg2) { 4158 synchronized (mPackages) { 4159 final PackageParser.Package p1 = mPackages.get(pkg1); 4160 final PackageParser.Package p2 = mPackages.get(pkg2); 4161 if (p1 == null || p1.mExtras == null 4162 || p2 == null || p2.mExtras == null) { 4163 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4164 } 4165 return compareSignatures(p1.mSignatures, p2.mSignatures); 4166 } 4167 } 4168 4169 @Override 4170 public int checkUidSignatures(int uid1, int uid2) { 4171 // Map to base uids. 4172 uid1 = UserHandle.getAppId(uid1); 4173 uid2 = UserHandle.getAppId(uid2); 4174 // reader 4175 synchronized (mPackages) { 4176 Signature[] s1; 4177 Signature[] s2; 4178 Object obj = mSettings.getUserIdLPr(uid1); 4179 if (obj != null) { 4180 if (obj instanceof SharedUserSetting) { 4181 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4182 } else if (obj instanceof PackageSetting) { 4183 s1 = ((PackageSetting)obj).signatures.mSignatures; 4184 } else { 4185 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4186 } 4187 } else { 4188 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4189 } 4190 obj = mSettings.getUserIdLPr(uid2); 4191 if (obj != null) { 4192 if (obj instanceof SharedUserSetting) { 4193 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4194 } else if (obj instanceof PackageSetting) { 4195 s2 = ((PackageSetting)obj).signatures.mSignatures; 4196 } else { 4197 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4198 } 4199 } else { 4200 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4201 } 4202 return compareSignatures(s1, s2); 4203 } 4204 } 4205 4206 private void killUid(int appId, int userId, String reason) { 4207 final long identity = Binder.clearCallingIdentity(); 4208 try { 4209 IActivityManager am = ActivityManagerNative.getDefault(); 4210 if (am != null) { 4211 try { 4212 am.killUid(appId, userId, reason); 4213 } catch (RemoteException e) { 4214 /* ignore - same process */ 4215 } 4216 } 4217 } finally { 4218 Binder.restoreCallingIdentity(identity); 4219 } 4220 } 4221 4222 /** 4223 * Compares two sets of signatures. Returns: 4224 * <br /> 4225 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4226 * <br /> 4227 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4228 * <br /> 4229 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4230 * <br /> 4231 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4232 * <br /> 4233 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4234 */ 4235 static int compareSignatures(Signature[] s1, Signature[] s2) { 4236 if (s1 == null) { 4237 return s2 == null 4238 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4239 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4240 } 4241 4242 if (s2 == null) { 4243 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4244 } 4245 4246 if (s1.length != s2.length) { 4247 return PackageManager.SIGNATURE_NO_MATCH; 4248 } 4249 4250 // Since both signature sets are of size 1, we can compare without HashSets. 4251 if (s1.length == 1) { 4252 return s1[0].equals(s2[0]) ? 4253 PackageManager.SIGNATURE_MATCH : 4254 PackageManager.SIGNATURE_NO_MATCH; 4255 } 4256 4257 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4258 for (Signature sig : s1) { 4259 set1.add(sig); 4260 } 4261 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4262 for (Signature sig : s2) { 4263 set2.add(sig); 4264 } 4265 // Make sure s2 contains all signatures in s1. 4266 if (set1.equals(set2)) { 4267 return PackageManager.SIGNATURE_MATCH; 4268 } 4269 return PackageManager.SIGNATURE_NO_MATCH; 4270 } 4271 4272 /** 4273 * If the database version for this type of package (internal storage or 4274 * external storage) is less than the version where package signatures 4275 * were updated, return true. 4276 */ 4277 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4278 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4279 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4280 } 4281 4282 /** 4283 * Used for backward compatibility to make sure any packages with 4284 * certificate chains get upgraded to the new style. {@code existingSigs} 4285 * will be in the old format (since they were stored on disk from before the 4286 * system upgrade) and {@code scannedSigs} will be in the newer format. 4287 */ 4288 private int compareSignaturesCompat(PackageSignatures existingSigs, 4289 PackageParser.Package scannedPkg) { 4290 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4291 return PackageManager.SIGNATURE_NO_MATCH; 4292 } 4293 4294 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4295 for (Signature sig : existingSigs.mSignatures) { 4296 existingSet.add(sig); 4297 } 4298 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4299 for (Signature sig : scannedPkg.mSignatures) { 4300 try { 4301 Signature[] chainSignatures = sig.getChainSignatures(); 4302 for (Signature chainSig : chainSignatures) { 4303 scannedCompatSet.add(chainSig); 4304 } 4305 } catch (CertificateEncodingException e) { 4306 scannedCompatSet.add(sig); 4307 } 4308 } 4309 /* 4310 * Make sure the expanded scanned set contains all signatures in the 4311 * existing one. 4312 */ 4313 if (scannedCompatSet.equals(existingSet)) { 4314 // Migrate the old signatures to the new scheme. 4315 existingSigs.assignSignatures(scannedPkg.mSignatures); 4316 // The new KeySets will be re-added later in the scanning process. 4317 synchronized (mPackages) { 4318 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4319 } 4320 return PackageManager.SIGNATURE_MATCH; 4321 } 4322 return PackageManager.SIGNATURE_NO_MATCH; 4323 } 4324 4325 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4326 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4327 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4328 } 4329 4330 private int compareSignaturesRecover(PackageSignatures existingSigs, 4331 PackageParser.Package scannedPkg) { 4332 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4333 return PackageManager.SIGNATURE_NO_MATCH; 4334 } 4335 4336 String msg = null; 4337 try { 4338 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4339 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4340 + scannedPkg.packageName); 4341 return PackageManager.SIGNATURE_MATCH; 4342 } 4343 } catch (CertificateException e) { 4344 msg = e.getMessage(); 4345 } 4346 4347 logCriticalInfo(Log.INFO, 4348 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4349 return PackageManager.SIGNATURE_NO_MATCH; 4350 } 4351 4352 @Override 4353 public String[] getPackagesForUid(int uid) { 4354 uid = UserHandle.getAppId(uid); 4355 // reader 4356 synchronized (mPackages) { 4357 Object obj = mSettings.getUserIdLPr(uid); 4358 if (obj instanceof SharedUserSetting) { 4359 final SharedUserSetting sus = (SharedUserSetting) obj; 4360 final int N = sus.packages.size(); 4361 final String[] res = new String[N]; 4362 final Iterator<PackageSetting> it = sus.packages.iterator(); 4363 int i = 0; 4364 while (it.hasNext()) { 4365 res[i++] = it.next().name; 4366 } 4367 return res; 4368 } else if (obj instanceof PackageSetting) { 4369 final PackageSetting ps = (PackageSetting) obj; 4370 return new String[] { ps.name }; 4371 } 4372 } 4373 return null; 4374 } 4375 4376 @Override 4377 public String getNameForUid(int uid) { 4378 // reader 4379 synchronized (mPackages) { 4380 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4381 if (obj instanceof SharedUserSetting) { 4382 final SharedUserSetting sus = (SharedUserSetting) obj; 4383 return sus.name + ":" + sus.userId; 4384 } else if (obj instanceof PackageSetting) { 4385 final PackageSetting ps = (PackageSetting) obj; 4386 return ps.name; 4387 } 4388 } 4389 return null; 4390 } 4391 4392 @Override 4393 public int getUidForSharedUser(String sharedUserName) { 4394 if(sharedUserName == null) { 4395 return -1; 4396 } 4397 // reader 4398 synchronized (mPackages) { 4399 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4400 if (suid == null) { 4401 return -1; 4402 } 4403 return suid.userId; 4404 } 4405 } 4406 4407 @Override 4408 public int getFlagsForUid(int uid) { 4409 synchronized (mPackages) { 4410 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4411 if (obj instanceof SharedUserSetting) { 4412 final SharedUserSetting sus = (SharedUserSetting) obj; 4413 return sus.pkgFlags; 4414 } else if (obj instanceof PackageSetting) { 4415 final PackageSetting ps = (PackageSetting) obj; 4416 return ps.pkgFlags; 4417 } 4418 } 4419 return 0; 4420 } 4421 4422 @Override 4423 public int getPrivateFlagsForUid(int uid) { 4424 synchronized (mPackages) { 4425 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4426 if (obj instanceof SharedUserSetting) { 4427 final SharedUserSetting sus = (SharedUserSetting) obj; 4428 return sus.pkgPrivateFlags; 4429 } else if (obj instanceof PackageSetting) { 4430 final PackageSetting ps = (PackageSetting) obj; 4431 return ps.pkgPrivateFlags; 4432 } 4433 } 4434 return 0; 4435 } 4436 4437 @Override 4438 public boolean isUidPrivileged(int uid) { 4439 uid = UserHandle.getAppId(uid); 4440 // reader 4441 synchronized (mPackages) { 4442 Object obj = mSettings.getUserIdLPr(uid); 4443 if (obj instanceof SharedUserSetting) { 4444 final SharedUserSetting sus = (SharedUserSetting) obj; 4445 final Iterator<PackageSetting> it = sus.packages.iterator(); 4446 while (it.hasNext()) { 4447 if (it.next().isPrivileged()) { 4448 return true; 4449 } 4450 } 4451 } else if (obj instanceof PackageSetting) { 4452 final PackageSetting ps = (PackageSetting) obj; 4453 return ps.isPrivileged(); 4454 } 4455 } 4456 return false; 4457 } 4458 4459 @Override 4460 public String[] getAppOpPermissionPackages(String permissionName) { 4461 synchronized (mPackages) { 4462 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4463 if (pkgs == null) { 4464 return null; 4465 } 4466 return pkgs.toArray(new String[pkgs.size()]); 4467 } 4468 } 4469 4470 @Override 4471 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4472 int flags, int userId) { 4473 if (!sUserManager.exists(userId)) return null; 4474 flags = updateFlagsForResolve(flags, userId, intent); 4475 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4476 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4477 final ResolveInfo bestChoice = 4478 chooseBestActivity(intent, resolvedType, flags, query, userId); 4479 4480 if (isEphemeralAllowed(intent, query, userId)) { 4481 final EphemeralResolveInfo ai = 4482 getEphemeralResolveInfo(intent, resolvedType, userId); 4483 if (ai != null) { 4484 if (DEBUG_EPHEMERAL) { 4485 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4486 } 4487 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4488 bestChoice.ephemeralResolveInfo = ai; 4489 } 4490 } 4491 return bestChoice; 4492 } 4493 4494 @Override 4495 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4496 IntentFilter filter, int match, ComponentName activity) { 4497 final int userId = UserHandle.getCallingUserId(); 4498 if (DEBUG_PREFERRED) { 4499 Log.v(TAG, "setLastChosenActivity intent=" + intent 4500 + " resolvedType=" + resolvedType 4501 + " flags=" + flags 4502 + " filter=" + filter 4503 + " match=" + match 4504 + " activity=" + activity); 4505 filter.dump(new PrintStreamPrinter(System.out), " "); 4506 } 4507 intent.setComponent(null); 4508 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4509 // Find any earlier preferred or last chosen entries and nuke them 4510 findPreferredActivity(intent, resolvedType, 4511 flags, query, 0, false, true, false, userId); 4512 // Add the new activity as the last chosen for this filter 4513 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4514 "Setting last chosen"); 4515 } 4516 4517 @Override 4518 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4519 final int userId = UserHandle.getCallingUserId(); 4520 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4521 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4522 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4523 false, false, false, userId); 4524 } 4525 4526 4527 private boolean isEphemeralAllowed( 4528 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4529 // Short circuit and return early if possible. 4530 if (DISABLE_EPHEMERAL_APPS) { 4531 return false; 4532 } 4533 final int callingUser = UserHandle.getCallingUserId(); 4534 if (callingUser != UserHandle.USER_SYSTEM) { 4535 return false; 4536 } 4537 if (mEphemeralResolverConnection == null) { 4538 return false; 4539 } 4540 if (intent.getComponent() != null) { 4541 return false; 4542 } 4543 if (intent.getPackage() != null) { 4544 return false; 4545 } 4546 final boolean isWebUri = hasWebURI(intent); 4547 if (!isWebUri) { 4548 return false; 4549 } 4550 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4551 synchronized (mPackages) { 4552 final int count = resolvedActivites.size(); 4553 for (int n = 0; n < count; n++) { 4554 ResolveInfo info = resolvedActivites.get(n); 4555 String packageName = info.activityInfo.packageName; 4556 PackageSetting ps = mSettings.mPackages.get(packageName); 4557 if (ps != null) { 4558 // Try to get the status from User settings first 4559 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4560 int status = (int) (packedStatus >> 32); 4561 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4562 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4563 if (DEBUG_EPHEMERAL) { 4564 Slog.v(TAG, "DENY ephemeral apps;" 4565 + " pkg: " + packageName + ", status: " + status); 4566 } 4567 return false; 4568 } 4569 } 4570 } 4571 } 4572 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4573 return true; 4574 } 4575 4576 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4577 int userId) { 4578 MessageDigest digest = null; 4579 try { 4580 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4581 } catch (NoSuchAlgorithmException e) { 4582 // If we can't create a digest, ignore ephemeral apps. 4583 return null; 4584 } 4585 4586 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4587 final byte[] digestBytes = digest.digest(hostBytes); 4588 int shaPrefix = 4589 digestBytes[0] << 24 4590 | digestBytes[1] << 16 4591 | digestBytes[2] << 8 4592 | digestBytes[3] << 0; 4593 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4594 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4595 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4596 // No hash prefix match; there are no ephemeral apps for this domain. 4597 return null; 4598 } 4599 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4600 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4601 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4602 continue; 4603 } 4604 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4605 // No filters; this should never happen. 4606 if (filters.isEmpty()) { 4607 continue; 4608 } 4609 // We have a domain match; resolve the filters to see if anything matches. 4610 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4611 for (int j = filters.size() - 1; j >= 0; --j) { 4612 final EphemeralResolveIntentInfo intentInfo = 4613 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4614 ephemeralResolver.addFilter(intentInfo); 4615 } 4616 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4617 intent, resolvedType, false /*defaultOnly*/, userId); 4618 if (!matchedResolveInfoList.isEmpty()) { 4619 return matchedResolveInfoList.get(0); 4620 } 4621 } 4622 // Hash or filter mis-match; no ephemeral apps for this domain. 4623 return null; 4624 } 4625 4626 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4627 int flags, List<ResolveInfo> query, int userId) { 4628 if (query != null) { 4629 final int N = query.size(); 4630 if (N == 1) { 4631 return query.get(0); 4632 } else if (N > 1) { 4633 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4634 // If there is more than one activity with the same priority, 4635 // then let the user decide between them. 4636 ResolveInfo r0 = query.get(0); 4637 ResolveInfo r1 = query.get(1); 4638 if (DEBUG_INTENT_MATCHING || debug) { 4639 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4640 + r1.activityInfo.name + "=" + r1.priority); 4641 } 4642 // If the first activity has a higher priority, or a different 4643 // default, then it is always desirable to pick it. 4644 if (r0.priority != r1.priority 4645 || r0.preferredOrder != r1.preferredOrder 4646 || r0.isDefault != r1.isDefault) { 4647 return query.get(0); 4648 } 4649 // If we have saved a preference for a preferred activity for 4650 // this Intent, use that. 4651 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4652 flags, query, r0.priority, true, false, debug, userId); 4653 if (ri != null) { 4654 return ri; 4655 } 4656 ri = new ResolveInfo(mResolveInfo); 4657 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4658 ri.activityInfo.applicationInfo = new ApplicationInfo( 4659 ri.activityInfo.applicationInfo); 4660 if (userId != 0) { 4661 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4662 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4663 } 4664 // Make sure that the resolver is displayable in car mode 4665 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4666 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4667 return ri; 4668 } 4669 } 4670 return null; 4671 } 4672 4673 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4674 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4675 final int N = query.size(); 4676 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4677 .get(userId); 4678 // Get the list of persistent preferred activities that handle the intent 4679 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4680 List<PersistentPreferredActivity> pprefs = ppir != null 4681 ? ppir.queryIntent(intent, resolvedType, 4682 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4683 : null; 4684 if (pprefs != null && pprefs.size() > 0) { 4685 final int M = pprefs.size(); 4686 for (int i=0; i<M; i++) { 4687 final PersistentPreferredActivity ppa = pprefs.get(i); 4688 if (DEBUG_PREFERRED || debug) { 4689 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4690 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4691 + "\n component=" + ppa.mComponent); 4692 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4693 } 4694 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4695 flags | MATCH_DISABLED_COMPONENTS, userId); 4696 if (DEBUG_PREFERRED || debug) { 4697 Slog.v(TAG, "Found persistent preferred activity:"); 4698 if (ai != null) { 4699 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4700 } else { 4701 Slog.v(TAG, " null"); 4702 } 4703 } 4704 if (ai == null) { 4705 // This previously registered persistent preferred activity 4706 // component is no longer known. Ignore it and do NOT remove it. 4707 continue; 4708 } 4709 for (int j=0; j<N; j++) { 4710 final ResolveInfo ri = query.get(j); 4711 if (!ri.activityInfo.applicationInfo.packageName 4712 .equals(ai.applicationInfo.packageName)) { 4713 continue; 4714 } 4715 if (!ri.activityInfo.name.equals(ai.name)) { 4716 continue; 4717 } 4718 // Found a persistent preference that can handle the intent. 4719 if (DEBUG_PREFERRED || debug) { 4720 Slog.v(TAG, "Returning persistent preferred activity: " + 4721 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4722 } 4723 return ri; 4724 } 4725 } 4726 } 4727 return null; 4728 } 4729 4730 // TODO: handle preferred activities missing while user has amnesia 4731 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4732 List<ResolveInfo> query, int priority, boolean always, 4733 boolean removeMatches, boolean debug, int userId) { 4734 if (!sUserManager.exists(userId)) return null; 4735 flags = updateFlagsForResolve(flags, userId, intent); 4736 // writer 4737 synchronized (mPackages) { 4738 if (intent.getSelector() != null) { 4739 intent = intent.getSelector(); 4740 } 4741 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4742 4743 // Try to find a matching persistent preferred activity. 4744 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4745 debug, userId); 4746 4747 // If a persistent preferred activity matched, use it. 4748 if (pri != null) { 4749 return pri; 4750 } 4751 4752 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4753 // Get the list of preferred activities that handle the intent 4754 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4755 List<PreferredActivity> prefs = pir != null 4756 ? pir.queryIntent(intent, resolvedType, 4757 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4758 : null; 4759 if (prefs != null && prefs.size() > 0) { 4760 boolean changed = false; 4761 try { 4762 // First figure out how good the original match set is. 4763 // We will only allow preferred activities that came 4764 // from the same match quality. 4765 int match = 0; 4766 4767 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4768 4769 final int N = query.size(); 4770 for (int j=0; j<N; j++) { 4771 final ResolveInfo ri = query.get(j); 4772 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4773 + ": 0x" + Integer.toHexString(match)); 4774 if (ri.match > match) { 4775 match = ri.match; 4776 } 4777 } 4778 4779 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4780 + Integer.toHexString(match)); 4781 4782 match &= IntentFilter.MATCH_CATEGORY_MASK; 4783 final int M = prefs.size(); 4784 for (int i=0; i<M; i++) { 4785 final PreferredActivity pa = prefs.get(i); 4786 if (DEBUG_PREFERRED || debug) { 4787 Slog.v(TAG, "Checking PreferredActivity ds=" 4788 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4789 + "\n component=" + pa.mPref.mComponent); 4790 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4791 } 4792 if (pa.mPref.mMatch != match) { 4793 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4794 + Integer.toHexString(pa.mPref.mMatch)); 4795 continue; 4796 } 4797 // If it's not an "always" type preferred activity and that's what we're 4798 // looking for, skip it. 4799 if (always && !pa.mPref.mAlways) { 4800 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4801 continue; 4802 } 4803 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4804 flags | MATCH_DISABLED_COMPONENTS, userId); 4805 if (DEBUG_PREFERRED || debug) { 4806 Slog.v(TAG, "Found preferred activity:"); 4807 if (ai != null) { 4808 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4809 } else { 4810 Slog.v(TAG, " null"); 4811 } 4812 } 4813 if (ai == null) { 4814 // This previously registered preferred activity 4815 // component is no longer known. Most likely an update 4816 // to the app was installed and in the new version this 4817 // component no longer exists. Clean it up by removing 4818 // it from the preferred activities list, and skip it. 4819 Slog.w(TAG, "Removing dangling preferred activity: " 4820 + pa.mPref.mComponent); 4821 pir.removeFilter(pa); 4822 changed = true; 4823 continue; 4824 } 4825 for (int j=0; j<N; j++) { 4826 final ResolveInfo ri = query.get(j); 4827 if (!ri.activityInfo.applicationInfo.packageName 4828 .equals(ai.applicationInfo.packageName)) { 4829 continue; 4830 } 4831 if (!ri.activityInfo.name.equals(ai.name)) { 4832 continue; 4833 } 4834 4835 if (removeMatches) { 4836 pir.removeFilter(pa); 4837 changed = true; 4838 if (DEBUG_PREFERRED) { 4839 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4840 } 4841 break; 4842 } 4843 4844 // Okay we found a previously set preferred or last chosen app. 4845 // If the result set is different from when this 4846 // was created, we need to clear it and re-ask the 4847 // user their preference, if we're looking for an "always" type entry. 4848 if (always && !pa.mPref.sameSet(query)) { 4849 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4850 + intent + " type " + resolvedType); 4851 if (DEBUG_PREFERRED) { 4852 Slog.v(TAG, "Removing preferred activity since set changed " 4853 + pa.mPref.mComponent); 4854 } 4855 pir.removeFilter(pa); 4856 // Re-add the filter as a "last chosen" entry (!always) 4857 PreferredActivity lastChosen = new PreferredActivity( 4858 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4859 pir.addFilter(lastChosen); 4860 changed = true; 4861 return null; 4862 } 4863 4864 // Yay! Either the set matched or we're looking for the last chosen 4865 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4866 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4867 return ri; 4868 } 4869 } 4870 } finally { 4871 if (changed) { 4872 if (DEBUG_PREFERRED) { 4873 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4874 } 4875 scheduleWritePackageRestrictionsLocked(userId); 4876 } 4877 } 4878 } 4879 } 4880 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4881 return null; 4882 } 4883 4884 /* 4885 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4886 */ 4887 @Override 4888 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4889 int targetUserId) { 4890 mContext.enforceCallingOrSelfPermission( 4891 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4892 List<CrossProfileIntentFilter> matches = 4893 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4894 if (matches != null) { 4895 int size = matches.size(); 4896 for (int i = 0; i < size; i++) { 4897 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4898 } 4899 } 4900 if (hasWebURI(intent)) { 4901 // cross-profile app linking works only towards the parent. 4902 final UserInfo parent = getProfileParent(sourceUserId); 4903 synchronized(mPackages) { 4904 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4905 intent, resolvedType, 0, sourceUserId, parent.id); 4906 return xpDomainInfo != null; 4907 } 4908 } 4909 return false; 4910 } 4911 4912 private UserInfo getProfileParent(int userId) { 4913 final long identity = Binder.clearCallingIdentity(); 4914 try { 4915 return sUserManager.getProfileParent(userId); 4916 } finally { 4917 Binder.restoreCallingIdentity(identity); 4918 } 4919 } 4920 4921 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4922 String resolvedType, int userId) { 4923 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4924 if (resolver != null) { 4925 return resolver.queryIntent(intent, resolvedType, false, userId); 4926 } 4927 return null; 4928 } 4929 4930 @Override 4931 public List<ResolveInfo> queryIntentActivities(Intent intent, 4932 String resolvedType, int flags, int userId) { 4933 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4934 flags = updateFlagsForResolve(flags, userId, intent); 4935 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4936 ComponentName comp = intent.getComponent(); 4937 if (comp == null) { 4938 if (intent.getSelector() != null) { 4939 intent = intent.getSelector(); 4940 comp = intent.getComponent(); 4941 } 4942 } 4943 4944 if (comp != null) { 4945 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4946 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4947 if (ai != null) { 4948 final ResolveInfo ri = new ResolveInfo(); 4949 ri.activityInfo = ai; 4950 list.add(ri); 4951 } 4952 return list; 4953 } 4954 4955 // reader 4956 synchronized (mPackages) { 4957 final String pkgName = intent.getPackage(); 4958 if (pkgName == null) { 4959 List<CrossProfileIntentFilter> matchingFilters = 4960 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4961 // Check for results that need to skip the current profile. 4962 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4963 resolvedType, flags, userId); 4964 if (xpResolveInfo != null) { 4965 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4966 result.add(xpResolveInfo); 4967 return filterIfNotSystemUser(result, userId); 4968 } 4969 4970 // Check for results in the current profile. 4971 List<ResolveInfo> result = mActivities.queryIntent( 4972 intent, resolvedType, flags, userId); 4973 result = filterIfNotSystemUser(result, userId); 4974 4975 // Check for cross profile results. 4976 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 4977 xpResolveInfo = queryCrossProfileIntents( 4978 matchingFilters, intent, resolvedType, flags, userId, 4979 hasNonNegativePriorityResult); 4980 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4981 boolean isVisibleToUser = filterIfNotSystemUser( 4982 Collections.singletonList(xpResolveInfo), userId).size() > 0; 4983 if (isVisibleToUser) { 4984 result.add(xpResolveInfo); 4985 Collections.sort(result, mResolvePrioritySorter); 4986 } 4987 } 4988 if (hasWebURI(intent)) { 4989 CrossProfileDomainInfo xpDomainInfo = null; 4990 final UserInfo parent = getProfileParent(userId); 4991 if (parent != null) { 4992 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4993 flags, userId, parent.id); 4994 } 4995 if (xpDomainInfo != null) { 4996 if (xpResolveInfo != null) { 4997 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4998 // in the result. 4999 result.remove(xpResolveInfo); 5000 } 5001 if (result.size() == 0) { 5002 result.add(xpDomainInfo.resolveInfo); 5003 return result; 5004 } 5005 } else if (result.size() <= 1) { 5006 return result; 5007 } 5008 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5009 xpDomainInfo, userId); 5010 Collections.sort(result, mResolvePrioritySorter); 5011 } 5012 return result; 5013 } 5014 final PackageParser.Package pkg = mPackages.get(pkgName); 5015 if (pkg != null) { 5016 return filterIfNotSystemUser( 5017 mActivities.queryIntentForPackage( 5018 intent, resolvedType, flags, pkg.activities, userId), 5019 userId); 5020 } 5021 return new ArrayList<ResolveInfo>(); 5022 } 5023 } 5024 5025 private static class CrossProfileDomainInfo { 5026 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5027 ResolveInfo resolveInfo; 5028 /* Best domain verification status of the activities found in the other profile */ 5029 int bestDomainVerificationStatus; 5030 } 5031 5032 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5033 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5034 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5035 sourceUserId)) { 5036 return null; 5037 } 5038 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5039 resolvedType, flags, parentUserId); 5040 5041 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5042 return null; 5043 } 5044 CrossProfileDomainInfo result = null; 5045 int size = resultTargetUser.size(); 5046 for (int i = 0; i < size; i++) { 5047 ResolveInfo riTargetUser = resultTargetUser.get(i); 5048 // Intent filter verification is only for filters that specify a host. So don't return 5049 // those that handle all web uris. 5050 if (riTargetUser.handleAllWebDataURI) { 5051 continue; 5052 } 5053 String packageName = riTargetUser.activityInfo.packageName; 5054 PackageSetting ps = mSettings.mPackages.get(packageName); 5055 if (ps == null) { 5056 continue; 5057 } 5058 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5059 int status = (int)(verificationState >> 32); 5060 if (result == null) { 5061 result = new CrossProfileDomainInfo(); 5062 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5063 sourceUserId, parentUserId); 5064 result.bestDomainVerificationStatus = status; 5065 } else { 5066 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5067 result.bestDomainVerificationStatus); 5068 } 5069 } 5070 // Don't consider matches with status NEVER across profiles. 5071 if (result != null && result.bestDomainVerificationStatus 5072 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5073 return null; 5074 } 5075 return result; 5076 } 5077 5078 /** 5079 * Verification statuses are ordered from the worse to the best, except for 5080 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5081 */ 5082 private int bestDomainVerificationStatus(int status1, int status2) { 5083 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5084 return status2; 5085 } 5086 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5087 return status1; 5088 } 5089 return (int) MathUtils.max(status1, status2); 5090 } 5091 5092 private boolean isUserEnabled(int userId) { 5093 long callingId = Binder.clearCallingIdentity(); 5094 try { 5095 UserInfo userInfo = sUserManager.getUserInfo(userId); 5096 return userInfo != null && userInfo.isEnabled(); 5097 } finally { 5098 Binder.restoreCallingIdentity(callingId); 5099 } 5100 } 5101 5102 /** 5103 * Filter out activities with systemUserOnly flag set, when current user is not System. 5104 * 5105 * @return filtered list 5106 */ 5107 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5108 if (userId == UserHandle.USER_SYSTEM) { 5109 return resolveInfos; 5110 } 5111 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5112 ResolveInfo info = resolveInfos.get(i); 5113 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5114 resolveInfos.remove(i); 5115 } 5116 } 5117 return resolveInfos; 5118 } 5119 5120 /** 5121 * @param resolveInfos list of resolve infos in descending priority order 5122 * @return if the list contains a resolve info with non-negative priority 5123 */ 5124 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5125 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5126 } 5127 5128 private static boolean hasWebURI(Intent intent) { 5129 if (intent.getData() == null) { 5130 return false; 5131 } 5132 final String scheme = intent.getScheme(); 5133 if (TextUtils.isEmpty(scheme)) { 5134 return false; 5135 } 5136 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5137 } 5138 5139 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5140 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5141 int userId) { 5142 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5143 5144 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5145 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5146 candidates.size()); 5147 } 5148 5149 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5150 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5151 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5152 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5153 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5154 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5155 5156 synchronized (mPackages) { 5157 final int count = candidates.size(); 5158 // First, try to use linked apps. Partition the candidates into four lists: 5159 // one for the final results, one for the "do not use ever", one for "undefined status" 5160 // and finally one for "browser app type". 5161 for (int n=0; n<count; n++) { 5162 ResolveInfo info = candidates.get(n); 5163 String packageName = info.activityInfo.packageName; 5164 PackageSetting ps = mSettings.mPackages.get(packageName); 5165 if (ps != null) { 5166 // Add to the special match all list (Browser use case) 5167 if (info.handleAllWebDataURI) { 5168 matchAllList.add(info); 5169 continue; 5170 } 5171 // Try to get the status from User settings first 5172 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5173 int status = (int)(packedStatus >> 32); 5174 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5175 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5176 if (DEBUG_DOMAIN_VERIFICATION) { 5177 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5178 + " : linkgen=" + linkGeneration); 5179 } 5180 // Use link-enabled generation as preferredOrder, i.e. 5181 // prefer newly-enabled over earlier-enabled. 5182 info.preferredOrder = linkGeneration; 5183 alwaysList.add(info); 5184 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5185 if (DEBUG_DOMAIN_VERIFICATION) { 5186 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5187 } 5188 neverList.add(info); 5189 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5190 if (DEBUG_DOMAIN_VERIFICATION) { 5191 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5192 } 5193 alwaysAskList.add(info); 5194 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5195 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5196 if (DEBUG_DOMAIN_VERIFICATION) { 5197 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5198 } 5199 undefinedList.add(info); 5200 } 5201 } 5202 } 5203 5204 // We'll want to include browser possibilities in a few cases 5205 boolean includeBrowser = false; 5206 5207 // First try to add the "always" resolution(s) for the current user, if any 5208 if (alwaysList.size() > 0) { 5209 result.addAll(alwaysList); 5210 } else { 5211 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5212 result.addAll(undefinedList); 5213 // Maybe add one for the other profile. 5214 if (xpDomainInfo != null && ( 5215 xpDomainInfo.bestDomainVerificationStatus 5216 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5217 result.add(xpDomainInfo.resolveInfo); 5218 } 5219 includeBrowser = true; 5220 } 5221 5222 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5223 // If there were 'always' entries their preferred order has been set, so we also 5224 // back that off to make the alternatives equivalent 5225 if (alwaysAskList.size() > 0) { 5226 for (ResolveInfo i : result) { 5227 i.preferredOrder = 0; 5228 } 5229 result.addAll(alwaysAskList); 5230 includeBrowser = true; 5231 } 5232 5233 if (includeBrowser) { 5234 // Also add browsers (all of them or only the default one) 5235 if (DEBUG_DOMAIN_VERIFICATION) { 5236 Slog.v(TAG, " ...including browsers in candidate set"); 5237 } 5238 if ((matchFlags & MATCH_ALL) != 0) { 5239 result.addAll(matchAllList); 5240 } else { 5241 // Browser/generic handling case. If there's a default browser, go straight 5242 // to that (but only if there is no other higher-priority match). 5243 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5244 int maxMatchPrio = 0; 5245 ResolveInfo defaultBrowserMatch = null; 5246 final int numCandidates = matchAllList.size(); 5247 for (int n = 0; n < numCandidates; n++) { 5248 ResolveInfo info = matchAllList.get(n); 5249 // track the highest overall match priority... 5250 if (info.priority > maxMatchPrio) { 5251 maxMatchPrio = info.priority; 5252 } 5253 // ...and the highest-priority default browser match 5254 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5255 if (defaultBrowserMatch == null 5256 || (defaultBrowserMatch.priority < info.priority)) { 5257 if (debug) { 5258 Slog.v(TAG, "Considering default browser match " + info); 5259 } 5260 defaultBrowserMatch = info; 5261 } 5262 } 5263 } 5264 if (defaultBrowserMatch != null 5265 && defaultBrowserMatch.priority >= maxMatchPrio 5266 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5267 { 5268 if (debug) { 5269 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5270 } 5271 result.add(defaultBrowserMatch); 5272 } else { 5273 result.addAll(matchAllList); 5274 } 5275 } 5276 5277 // If there is nothing selected, add all candidates and remove the ones that the user 5278 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5279 if (result.size() == 0) { 5280 result.addAll(candidates); 5281 result.removeAll(neverList); 5282 } 5283 } 5284 } 5285 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5286 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5287 result.size()); 5288 for (ResolveInfo info : result) { 5289 Slog.v(TAG, " + " + info.activityInfo); 5290 } 5291 } 5292 return result; 5293 } 5294 5295 // Returns a packed value as a long: 5296 // 5297 // high 'int'-sized word: link status: undefined/ask/never/always. 5298 // low 'int'-sized word: relative priority among 'always' results. 5299 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5300 long result = ps.getDomainVerificationStatusForUser(userId); 5301 // if none available, get the master status 5302 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5303 if (ps.getIntentFilterVerificationInfo() != null) { 5304 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5305 } 5306 } 5307 return result; 5308 } 5309 5310 private ResolveInfo querySkipCurrentProfileIntents( 5311 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5312 int flags, int sourceUserId) { 5313 if (matchingFilters != null) { 5314 int size = matchingFilters.size(); 5315 for (int i = 0; i < size; i ++) { 5316 CrossProfileIntentFilter filter = matchingFilters.get(i); 5317 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5318 // Checking if there are activities in the target user that can handle the 5319 // intent. 5320 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5321 resolvedType, flags, sourceUserId); 5322 if (resolveInfo != null) { 5323 return resolveInfo; 5324 } 5325 } 5326 } 5327 } 5328 return null; 5329 } 5330 5331 // Return matching ResolveInfo in target user if any. 5332 private ResolveInfo queryCrossProfileIntents( 5333 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5334 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5335 if (matchingFilters != null) { 5336 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5337 // match the same intent. For performance reasons, it is better not to 5338 // run queryIntent twice for the same userId 5339 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5340 int size = matchingFilters.size(); 5341 for (int i = 0; i < size; i++) { 5342 CrossProfileIntentFilter filter = matchingFilters.get(i); 5343 int targetUserId = filter.getTargetUserId(); 5344 boolean skipCurrentProfile = 5345 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5346 boolean skipCurrentProfileIfNoMatchFound = 5347 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5348 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5349 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5350 // Checking if there are activities in the target user that can handle the 5351 // intent. 5352 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5353 resolvedType, flags, sourceUserId); 5354 if (resolveInfo != null) return resolveInfo; 5355 alreadyTriedUserIds.put(targetUserId, true); 5356 } 5357 } 5358 } 5359 return null; 5360 } 5361 5362 /** 5363 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5364 * will forward the intent to the filter's target user. 5365 * Otherwise, returns null. 5366 */ 5367 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5368 String resolvedType, int flags, int sourceUserId) { 5369 int targetUserId = filter.getTargetUserId(); 5370 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5371 resolvedType, flags, targetUserId); 5372 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5373 // If all the matches in the target profile are suspended, return null. 5374 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5375 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5376 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5377 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5378 targetUserId); 5379 } 5380 } 5381 } 5382 return null; 5383 } 5384 5385 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5386 int sourceUserId, int targetUserId) { 5387 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5388 long ident = Binder.clearCallingIdentity(); 5389 boolean targetIsProfile; 5390 try { 5391 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5392 } finally { 5393 Binder.restoreCallingIdentity(ident); 5394 } 5395 String className; 5396 if (targetIsProfile) { 5397 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5398 } else { 5399 className = FORWARD_INTENT_TO_PARENT; 5400 } 5401 ComponentName forwardingActivityComponentName = new ComponentName( 5402 mAndroidApplication.packageName, className); 5403 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5404 sourceUserId); 5405 if (!targetIsProfile) { 5406 forwardingActivityInfo.showUserIcon = targetUserId; 5407 forwardingResolveInfo.noResourceId = true; 5408 } 5409 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5410 forwardingResolveInfo.priority = 0; 5411 forwardingResolveInfo.preferredOrder = 0; 5412 forwardingResolveInfo.match = 0; 5413 forwardingResolveInfo.isDefault = true; 5414 forwardingResolveInfo.filter = filter; 5415 forwardingResolveInfo.targetUserId = targetUserId; 5416 return forwardingResolveInfo; 5417 } 5418 5419 @Override 5420 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5421 Intent[] specifics, String[] specificTypes, Intent intent, 5422 String resolvedType, int flags, int userId) { 5423 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5424 flags = updateFlagsForResolve(flags, userId, intent); 5425 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 5426 false, "query intent activity options"); 5427 final String resultsAction = intent.getAction(); 5428 5429 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 5430 | PackageManager.GET_RESOLVED_FILTER, userId); 5431 5432 if (DEBUG_INTENT_MATCHING) { 5433 Log.v(TAG, "Query " + intent + ": " + results); 5434 } 5435 5436 int specificsPos = 0; 5437 int N; 5438 5439 // todo: note that the algorithm used here is O(N^2). This 5440 // isn't a problem in our current environment, but if we start running 5441 // into situations where we have more than 5 or 10 matches then this 5442 // should probably be changed to something smarter... 5443 5444 // First we go through and resolve each of the specific items 5445 // that were supplied, taking care of removing any corresponding 5446 // duplicate items in the generic resolve list. 5447 if (specifics != null) { 5448 for (int i=0; i<specifics.length; i++) { 5449 final Intent sintent = specifics[i]; 5450 if (sintent == null) { 5451 continue; 5452 } 5453 5454 if (DEBUG_INTENT_MATCHING) { 5455 Log.v(TAG, "Specific #" + i + ": " + sintent); 5456 } 5457 5458 String action = sintent.getAction(); 5459 if (resultsAction != null && resultsAction.equals(action)) { 5460 // If this action was explicitly requested, then don't 5461 // remove things that have it. 5462 action = null; 5463 } 5464 5465 ResolveInfo ri = null; 5466 ActivityInfo ai = null; 5467 5468 ComponentName comp = sintent.getComponent(); 5469 if (comp == null) { 5470 ri = resolveIntent( 5471 sintent, 5472 specificTypes != null ? specificTypes[i] : null, 5473 flags, userId); 5474 if (ri == null) { 5475 continue; 5476 } 5477 if (ri == mResolveInfo) { 5478 // ACK! Must do something better with this. 5479 } 5480 ai = ri.activityInfo; 5481 comp = new ComponentName(ai.applicationInfo.packageName, 5482 ai.name); 5483 } else { 5484 ai = getActivityInfo(comp, flags, userId); 5485 if (ai == null) { 5486 continue; 5487 } 5488 } 5489 5490 // Look for any generic query activities that are duplicates 5491 // of this specific one, and remove them from the results. 5492 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5493 N = results.size(); 5494 int j; 5495 for (j=specificsPos; j<N; j++) { 5496 ResolveInfo sri = results.get(j); 5497 if ((sri.activityInfo.name.equals(comp.getClassName()) 5498 && sri.activityInfo.applicationInfo.packageName.equals( 5499 comp.getPackageName())) 5500 || (action != null && sri.filter.matchAction(action))) { 5501 results.remove(j); 5502 if (DEBUG_INTENT_MATCHING) Log.v( 5503 TAG, "Removing duplicate item from " + j 5504 + " due to specific " + specificsPos); 5505 if (ri == null) { 5506 ri = sri; 5507 } 5508 j--; 5509 N--; 5510 } 5511 } 5512 5513 // Add this specific item to its proper place. 5514 if (ri == null) { 5515 ri = new ResolveInfo(); 5516 ri.activityInfo = ai; 5517 } 5518 results.add(specificsPos, ri); 5519 ri.specificIndex = i; 5520 specificsPos++; 5521 } 5522 } 5523 5524 // Now we go through the remaining generic results and remove any 5525 // duplicate actions that are found here. 5526 N = results.size(); 5527 for (int i=specificsPos; i<N-1; i++) { 5528 final ResolveInfo rii = results.get(i); 5529 if (rii.filter == null) { 5530 continue; 5531 } 5532 5533 // Iterate over all of the actions of this result's intent 5534 // filter... typically this should be just one. 5535 final Iterator<String> it = rii.filter.actionsIterator(); 5536 if (it == null) { 5537 continue; 5538 } 5539 while (it.hasNext()) { 5540 final String action = it.next(); 5541 if (resultsAction != null && resultsAction.equals(action)) { 5542 // If this action was explicitly requested, then don't 5543 // remove things that have it. 5544 continue; 5545 } 5546 for (int j=i+1; j<N; j++) { 5547 final ResolveInfo rij = results.get(j); 5548 if (rij.filter != null && rij.filter.hasAction(action)) { 5549 results.remove(j); 5550 if (DEBUG_INTENT_MATCHING) Log.v( 5551 TAG, "Removing duplicate item from " + j 5552 + " due to action " + action + " at " + i); 5553 j--; 5554 N--; 5555 } 5556 } 5557 } 5558 5559 // If the caller didn't request filter information, drop it now 5560 // so we don't have to marshall/unmarshall it. 5561 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5562 rii.filter = null; 5563 } 5564 } 5565 5566 // Filter out the caller activity if so requested. 5567 if (caller != null) { 5568 N = results.size(); 5569 for (int i=0; i<N; i++) { 5570 ActivityInfo ainfo = results.get(i).activityInfo; 5571 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5572 && caller.getClassName().equals(ainfo.name)) { 5573 results.remove(i); 5574 break; 5575 } 5576 } 5577 } 5578 5579 // If the caller didn't request filter information, 5580 // drop them now so we don't have to 5581 // marshall/unmarshall it. 5582 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5583 N = results.size(); 5584 for (int i=0; i<N; i++) { 5585 results.get(i).filter = null; 5586 } 5587 } 5588 5589 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5590 return results; 5591 } 5592 5593 @Override 5594 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5595 int userId) { 5596 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5597 flags = updateFlagsForResolve(flags, userId, intent); 5598 ComponentName comp = intent.getComponent(); 5599 if (comp == null) { 5600 if (intent.getSelector() != null) { 5601 intent = intent.getSelector(); 5602 comp = intent.getComponent(); 5603 } 5604 } 5605 if (comp != null) { 5606 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5607 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5608 if (ai != null) { 5609 ResolveInfo ri = new ResolveInfo(); 5610 ri.activityInfo = ai; 5611 list.add(ri); 5612 } 5613 return list; 5614 } 5615 5616 // reader 5617 synchronized (mPackages) { 5618 String pkgName = intent.getPackage(); 5619 if (pkgName == null) { 5620 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5621 } 5622 final PackageParser.Package pkg = mPackages.get(pkgName); 5623 if (pkg != null) { 5624 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5625 userId); 5626 } 5627 return null; 5628 } 5629 } 5630 5631 @Override 5632 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5633 if (!sUserManager.exists(userId)) return null; 5634 flags = updateFlagsForResolve(flags, userId, intent); 5635 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5636 if (query != null) { 5637 if (query.size() >= 1) { 5638 // If there is more than one service with the same priority, 5639 // just arbitrarily pick the first one. 5640 return query.get(0); 5641 } 5642 } 5643 return null; 5644 } 5645 5646 @Override 5647 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5648 int userId) { 5649 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5650 flags = updateFlagsForResolve(flags, userId, intent); 5651 ComponentName comp = intent.getComponent(); 5652 if (comp == null) { 5653 if (intent.getSelector() != null) { 5654 intent = intent.getSelector(); 5655 comp = intent.getComponent(); 5656 } 5657 } 5658 if (comp != null) { 5659 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5660 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5661 if (si != null) { 5662 final ResolveInfo ri = new ResolveInfo(); 5663 ri.serviceInfo = si; 5664 list.add(ri); 5665 } 5666 return list; 5667 } 5668 5669 // reader 5670 synchronized (mPackages) { 5671 String pkgName = intent.getPackage(); 5672 if (pkgName == null) { 5673 return mServices.queryIntent(intent, resolvedType, flags, userId); 5674 } 5675 final PackageParser.Package pkg = mPackages.get(pkgName); 5676 if (pkg != null) { 5677 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5678 userId); 5679 } 5680 return null; 5681 } 5682 } 5683 5684 @Override 5685 public List<ResolveInfo> queryIntentContentProviders( 5686 Intent intent, String resolvedType, int flags, int userId) { 5687 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5688 flags = updateFlagsForResolve(flags, userId, intent); 5689 ComponentName comp = intent.getComponent(); 5690 if (comp == null) { 5691 if (intent.getSelector() != null) { 5692 intent = intent.getSelector(); 5693 comp = intent.getComponent(); 5694 } 5695 } 5696 if (comp != null) { 5697 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5698 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5699 if (pi != null) { 5700 final ResolveInfo ri = new ResolveInfo(); 5701 ri.providerInfo = pi; 5702 list.add(ri); 5703 } 5704 return list; 5705 } 5706 5707 // reader 5708 synchronized (mPackages) { 5709 String pkgName = intent.getPackage(); 5710 if (pkgName == null) { 5711 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5712 } 5713 final PackageParser.Package pkg = mPackages.get(pkgName); 5714 if (pkg != null) { 5715 return mProviders.queryIntentForPackage( 5716 intent, resolvedType, flags, pkg.providers, userId); 5717 } 5718 return null; 5719 } 5720 } 5721 5722 @Override 5723 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5724 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5725 flags = updateFlagsForPackage(flags, userId, null); 5726 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5727 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5728 5729 // writer 5730 synchronized (mPackages) { 5731 ArrayList<PackageInfo> list; 5732 if (listUninstalled) { 5733 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5734 for (PackageSetting ps : mSettings.mPackages.values()) { 5735 PackageInfo pi; 5736 if (ps.pkg != null) { 5737 pi = generatePackageInfo(ps.pkg, flags, userId); 5738 } else { 5739 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5740 } 5741 if (pi != null) { 5742 list.add(pi); 5743 } 5744 } 5745 } else { 5746 list = new ArrayList<PackageInfo>(mPackages.size()); 5747 for (PackageParser.Package p : mPackages.values()) { 5748 PackageInfo pi = generatePackageInfo(p, flags, userId); 5749 if (pi != null) { 5750 list.add(pi); 5751 } 5752 } 5753 } 5754 5755 return new ParceledListSlice<PackageInfo>(list); 5756 } 5757 } 5758 5759 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5760 String[] permissions, boolean[] tmp, int flags, int userId) { 5761 int numMatch = 0; 5762 final PermissionsState permissionsState = ps.getPermissionsState(); 5763 for (int i=0; i<permissions.length; i++) { 5764 final String permission = permissions[i]; 5765 if (permissionsState.hasPermission(permission, userId)) { 5766 tmp[i] = true; 5767 numMatch++; 5768 } else { 5769 tmp[i] = false; 5770 } 5771 } 5772 if (numMatch == 0) { 5773 return; 5774 } 5775 PackageInfo pi; 5776 if (ps.pkg != null) { 5777 pi = generatePackageInfo(ps.pkg, flags, userId); 5778 } else { 5779 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5780 } 5781 // The above might return null in cases of uninstalled apps or install-state 5782 // skew across users/profiles. 5783 if (pi != null) { 5784 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5785 if (numMatch == permissions.length) { 5786 pi.requestedPermissions = permissions; 5787 } else { 5788 pi.requestedPermissions = new String[numMatch]; 5789 numMatch = 0; 5790 for (int i=0; i<permissions.length; i++) { 5791 if (tmp[i]) { 5792 pi.requestedPermissions[numMatch] = permissions[i]; 5793 numMatch++; 5794 } 5795 } 5796 } 5797 } 5798 list.add(pi); 5799 } 5800 } 5801 5802 @Override 5803 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5804 String[] permissions, int flags, int userId) { 5805 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5806 flags = updateFlagsForPackage(flags, userId, permissions); 5807 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5808 5809 // writer 5810 synchronized (mPackages) { 5811 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5812 boolean[] tmpBools = new boolean[permissions.length]; 5813 if (listUninstalled) { 5814 for (PackageSetting ps : mSettings.mPackages.values()) { 5815 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5816 } 5817 } else { 5818 for (PackageParser.Package pkg : mPackages.values()) { 5819 PackageSetting ps = (PackageSetting)pkg.mExtras; 5820 if (ps != null) { 5821 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5822 userId); 5823 } 5824 } 5825 } 5826 5827 return new ParceledListSlice<PackageInfo>(list); 5828 } 5829 } 5830 5831 @Override 5832 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5833 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5834 flags = updateFlagsForApplication(flags, userId, null); 5835 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5836 5837 // writer 5838 synchronized (mPackages) { 5839 ArrayList<ApplicationInfo> list; 5840 if (listUninstalled) { 5841 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5842 for (PackageSetting ps : mSettings.mPackages.values()) { 5843 ApplicationInfo ai; 5844 if (ps.pkg != null) { 5845 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5846 ps.readUserState(userId), userId); 5847 } else { 5848 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5849 } 5850 if (ai != null) { 5851 list.add(ai); 5852 } 5853 } 5854 } else { 5855 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5856 for (PackageParser.Package p : mPackages.values()) { 5857 if (p.mExtras != null) { 5858 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5859 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5860 if (ai != null) { 5861 list.add(ai); 5862 } 5863 } 5864 } 5865 } 5866 5867 return new ParceledListSlice<ApplicationInfo>(list); 5868 } 5869 } 5870 5871 @Override 5872 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 5873 if (DISABLE_EPHEMERAL_APPS) { 5874 return null; 5875 } 5876 5877 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 5878 "getEphemeralApplications"); 5879 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5880 "getEphemeralApplications"); 5881 synchronized (mPackages) { 5882 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 5883 .getEphemeralApplicationsLPw(userId); 5884 if (ephemeralApps != null) { 5885 return new ParceledListSlice<>(ephemeralApps); 5886 } 5887 } 5888 return null; 5889 } 5890 5891 @Override 5892 public boolean isEphemeralApplication(String packageName, int userId) { 5893 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5894 "isEphemeral"); 5895 if (DISABLE_EPHEMERAL_APPS) { 5896 return false; 5897 } 5898 5899 if (!isCallerSameApp(packageName)) { 5900 return false; 5901 } 5902 synchronized (mPackages) { 5903 PackageParser.Package pkg = mPackages.get(packageName); 5904 if (pkg != null) { 5905 return pkg.applicationInfo.isEphemeralApp(); 5906 } 5907 } 5908 return false; 5909 } 5910 5911 @Override 5912 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 5913 if (DISABLE_EPHEMERAL_APPS) { 5914 return null; 5915 } 5916 5917 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5918 "getCookie"); 5919 if (!isCallerSameApp(packageName)) { 5920 return null; 5921 } 5922 synchronized (mPackages) { 5923 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 5924 packageName, userId); 5925 } 5926 } 5927 5928 @Override 5929 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 5930 if (DISABLE_EPHEMERAL_APPS) { 5931 return true; 5932 } 5933 5934 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5935 "setCookie"); 5936 if (!isCallerSameApp(packageName)) { 5937 return false; 5938 } 5939 synchronized (mPackages) { 5940 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 5941 packageName, cookie, userId); 5942 } 5943 } 5944 5945 @Override 5946 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 5947 if (DISABLE_EPHEMERAL_APPS) { 5948 return null; 5949 } 5950 5951 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 5952 "getEphemeralApplicationIcon"); 5953 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5954 "getEphemeralApplicationIcon"); 5955 synchronized (mPackages) { 5956 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 5957 packageName, userId); 5958 } 5959 } 5960 5961 private boolean isCallerSameApp(String packageName) { 5962 PackageParser.Package pkg = mPackages.get(packageName); 5963 return pkg != null 5964 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 5965 } 5966 5967 public List<ApplicationInfo> getPersistentApplications(int flags) { 5968 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5969 5970 // reader 5971 synchronized (mPackages) { 5972 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5973 final int userId = UserHandle.getCallingUserId(); 5974 while (i.hasNext()) { 5975 final PackageParser.Package p = i.next(); 5976 if (p.applicationInfo != null 5977 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5978 && (!mSafeMode || isSystemApp(p))) { 5979 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5980 if (ps != null) { 5981 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5982 ps.readUserState(userId), userId); 5983 if (ai != null) { 5984 finalList.add(ai); 5985 } 5986 } 5987 } 5988 } 5989 } 5990 5991 return finalList; 5992 } 5993 5994 @Override 5995 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5996 if (!sUserManager.exists(userId)) return null; 5997 flags = updateFlagsForComponent(flags, userId, name); 5998 // reader 5999 synchronized (mPackages) { 6000 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6001 PackageSetting ps = provider != null 6002 ? mSettings.mPackages.get(provider.owner.packageName) 6003 : null; 6004 return ps != null 6005 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6006 ? PackageParser.generateProviderInfo(provider, flags, 6007 ps.readUserState(userId), userId) 6008 : null; 6009 } 6010 } 6011 6012 /** 6013 * @deprecated 6014 */ 6015 @Deprecated 6016 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6017 // reader 6018 synchronized (mPackages) { 6019 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6020 .entrySet().iterator(); 6021 final int userId = UserHandle.getCallingUserId(); 6022 while (i.hasNext()) { 6023 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6024 PackageParser.Provider p = entry.getValue(); 6025 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6026 6027 if (ps != null && p.syncable 6028 && (!mSafeMode || (p.info.applicationInfo.flags 6029 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6030 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6031 ps.readUserState(userId), userId); 6032 if (info != null) { 6033 outNames.add(entry.getKey()); 6034 outInfo.add(info); 6035 } 6036 } 6037 } 6038 } 6039 } 6040 6041 @Override 6042 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6043 int uid, int flags) { 6044 final int userId = processName != null ? UserHandle.getUserId(uid) 6045 : UserHandle.getCallingUserId(); 6046 if (!sUserManager.exists(userId)) return null; 6047 flags = updateFlagsForComponent(flags, userId, processName); 6048 6049 ArrayList<ProviderInfo> finalList = null; 6050 // reader 6051 synchronized (mPackages) { 6052 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6053 while (i.hasNext()) { 6054 final PackageParser.Provider p = i.next(); 6055 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6056 if (ps != null && p.info.authority != null 6057 && (processName == null 6058 || (p.info.processName.equals(processName) 6059 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6060 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6061 if (finalList == null) { 6062 finalList = new ArrayList<ProviderInfo>(3); 6063 } 6064 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6065 ps.readUserState(userId), userId); 6066 if (info != null) { 6067 finalList.add(info); 6068 } 6069 } 6070 } 6071 } 6072 6073 if (finalList != null) { 6074 Collections.sort(finalList, mProviderInitOrderSorter); 6075 return new ParceledListSlice<ProviderInfo>(finalList); 6076 } 6077 6078 return null; 6079 } 6080 6081 @Override 6082 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6083 // reader 6084 synchronized (mPackages) { 6085 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6086 return PackageParser.generateInstrumentationInfo(i, flags); 6087 } 6088 } 6089 6090 @Override 6091 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 6092 int flags) { 6093 ArrayList<InstrumentationInfo> finalList = 6094 new ArrayList<InstrumentationInfo>(); 6095 6096 // reader 6097 synchronized (mPackages) { 6098 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6099 while (i.hasNext()) { 6100 final PackageParser.Instrumentation p = i.next(); 6101 if (targetPackage == null 6102 || targetPackage.equals(p.info.targetPackage)) { 6103 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6104 flags); 6105 if (ii != null) { 6106 finalList.add(ii); 6107 } 6108 } 6109 } 6110 } 6111 6112 return finalList; 6113 } 6114 6115 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6116 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6117 if (overlays == null) { 6118 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6119 return; 6120 } 6121 for (PackageParser.Package opkg : overlays.values()) { 6122 // Not much to do if idmap fails: we already logged the error 6123 // and we certainly don't want to abort installation of pkg simply 6124 // because an overlay didn't fit properly. For these reasons, 6125 // ignore the return value of createIdmapForPackagePairLI. 6126 createIdmapForPackagePairLI(pkg, opkg); 6127 } 6128 } 6129 6130 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6131 PackageParser.Package opkg) { 6132 if (!opkg.mTrustedOverlay) { 6133 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6134 opkg.baseCodePath + ": overlay not trusted"); 6135 return false; 6136 } 6137 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6138 if (overlaySet == null) { 6139 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6140 opkg.baseCodePath + " but target package has no known overlays"); 6141 return false; 6142 } 6143 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6144 // TODO: generate idmap for split APKs 6145 try { 6146 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6147 } catch (InstallerException e) { 6148 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6149 + opkg.baseCodePath); 6150 return false; 6151 } 6152 PackageParser.Package[] overlayArray = 6153 overlaySet.values().toArray(new PackageParser.Package[0]); 6154 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6155 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6156 return p1.mOverlayPriority - p2.mOverlayPriority; 6157 } 6158 }; 6159 Arrays.sort(overlayArray, cmp); 6160 6161 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6162 int i = 0; 6163 for (PackageParser.Package p : overlayArray) { 6164 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6165 } 6166 return true; 6167 } 6168 6169 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6170 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6171 try { 6172 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6173 } finally { 6174 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6175 } 6176 } 6177 6178 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6179 final File[] files = dir.listFiles(); 6180 if (ArrayUtils.isEmpty(files)) { 6181 Log.d(TAG, "No files in app dir " + dir); 6182 return; 6183 } 6184 6185 if (DEBUG_PACKAGE_SCANNING) { 6186 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6187 + " flags=0x" + Integer.toHexString(parseFlags)); 6188 } 6189 6190 for (File file : files) { 6191 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6192 && !PackageInstallerService.isStageName(file.getName()); 6193 if (!isPackage) { 6194 // Ignore entries which are not packages 6195 continue; 6196 } 6197 try { 6198 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6199 scanFlags, currentTime, null); 6200 } catch (PackageManagerException e) { 6201 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6202 6203 // Delete invalid userdata apps 6204 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6205 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6206 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6207 removeCodePathLI(file); 6208 } 6209 } 6210 } 6211 } 6212 6213 private static File getSettingsProblemFile() { 6214 File dataDir = Environment.getDataDirectory(); 6215 File systemDir = new File(dataDir, "system"); 6216 File fname = new File(systemDir, "uiderrors.txt"); 6217 return fname; 6218 } 6219 6220 static void reportSettingsProblem(int priority, String msg) { 6221 logCriticalInfo(priority, msg); 6222 } 6223 6224 static void logCriticalInfo(int priority, String msg) { 6225 Slog.println(priority, TAG, msg); 6226 EventLogTags.writePmCriticalInfo(msg); 6227 try { 6228 File fname = getSettingsProblemFile(); 6229 FileOutputStream out = new FileOutputStream(fname, true); 6230 PrintWriter pw = new FastPrintWriter(out); 6231 SimpleDateFormat formatter = new SimpleDateFormat(); 6232 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6233 pw.println(dateString + ": " + msg); 6234 pw.close(); 6235 FileUtils.setPermissions( 6236 fname.toString(), 6237 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6238 -1, -1); 6239 } catch (java.io.IOException e) { 6240 } 6241 } 6242 6243 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 6244 PackageParser.Package pkg, File srcFile, int parseFlags) 6245 throws PackageManagerException { 6246 if (ps != null 6247 && ps.codePath.equals(srcFile) 6248 && ps.timeStamp == srcFile.lastModified() 6249 && !isCompatSignatureUpdateNeeded(pkg) 6250 && !isRecoverSignatureUpdateNeeded(pkg)) { 6251 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6252 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6253 ArraySet<PublicKey> signingKs; 6254 synchronized (mPackages) { 6255 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6256 } 6257 if (ps.signatures.mSignatures != null 6258 && ps.signatures.mSignatures.length != 0 6259 && signingKs != null) { 6260 // Optimization: reuse the existing cached certificates 6261 // if the package appears to be unchanged. 6262 pkg.mSignatures = ps.signatures.mSignatures; 6263 pkg.mSigningKeys = signingKs; 6264 return; 6265 } 6266 6267 Slog.w(TAG, "PackageSetting for " + ps.name 6268 + " is missing signatures. Collecting certs again to recover them."); 6269 } else { 6270 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6271 } 6272 6273 try { 6274 pp.collectCertificates(pkg, parseFlags); 6275 } catch (PackageParserException e) { 6276 throw PackageManagerException.from(e); 6277 } 6278 } 6279 6280 /** 6281 * Traces a package scan. 6282 * @see #scanPackageLI(File, int, int, long, UserHandle) 6283 */ 6284 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6285 long currentTime, UserHandle user) throws PackageManagerException { 6286 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6287 try { 6288 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6289 } finally { 6290 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6291 } 6292 } 6293 6294 /** 6295 * Scans a package and returns the newly parsed package. 6296 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6297 */ 6298 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6299 long currentTime, UserHandle user) throws PackageManagerException { 6300 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6301 parseFlags |= mDefParseFlags; 6302 PackageParser pp = new PackageParser(); 6303 pp.setSeparateProcesses(mSeparateProcesses); 6304 pp.setOnlyCoreApps(mOnlyCore); 6305 pp.setDisplayMetrics(mMetrics); 6306 6307 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6308 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6309 } 6310 6311 final PackageParser.Package pkg; 6312 try { 6313 pkg = pp.parsePackage(scanFile, parseFlags); 6314 } catch (PackageParserException e) { 6315 throw PackageManagerException.from(e); 6316 } 6317 6318 PackageSetting ps = null; 6319 PackageSetting updatedPkg; 6320 // reader 6321 synchronized (mPackages) { 6322 // Look to see if we already know about this package. 6323 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6324 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6325 // This package has been renamed to its original name. Let's 6326 // use that. 6327 ps = mSettings.peekPackageLPr(oldName); 6328 } 6329 // If there was no original package, see one for the real package name. 6330 if (ps == null) { 6331 ps = mSettings.peekPackageLPr(pkg.packageName); 6332 } 6333 // Check to see if this package could be hiding/updating a system 6334 // package. Must look for it either under the original or real 6335 // package name depending on our state. 6336 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6337 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6338 } 6339 boolean updatedPkgBetter = false; 6340 // First check if this is a system package that may involve an update 6341 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6342 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6343 // it needs to drop FLAG_PRIVILEGED. 6344 if (locationIsPrivileged(scanFile)) { 6345 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6346 } else { 6347 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6348 } 6349 6350 if (ps != null && !ps.codePath.equals(scanFile)) { 6351 // The path has changed from what was last scanned... check the 6352 // version of the new path against what we have stored to determine 6353 // what to do. 6354 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6355 if (pkg.mVersionCode <= ps.versionCode) { 6356 // The system package has been updated and the code path does not match 6357 // Ignore entry. Skip it. 6358 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6359 + " ignored: updated version " + ps.versionCode 6360 + " better than this " + pkg.mVersionCode); 6361 if (!updatedPkg.codePath.equals(scanFile)) { 6362 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6363 + ps.name + " changing from " + updatedPkg.codePathString 6364 + " to " + scanFile); 6365 updatedPkg.codePath = scanFile; 6366 updatedPkg.codePathString = scanFile.toString(); 6367 updatedPkg.resourcePath = scanFile; 6368 updatedPkg.resourcePathString = scanFile.toString(); 6369 } 6370 updatedPkg.pkg = pkg; 6371 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6372 "Package " + ps.name + " at " + scanFile 6373 + " ignored: updated version " + ps.versionCode 6374 + " better than this " + pkg.mVersionCode); 6375 } else { 6376 // The current app on the system partition is better than 6377 // what we have updated to on the data partition; switch 6378 // back to the system partition version. 6379 // At this point, its safely assumed that package installation for 6380 // apps in system partition will go through. If not there won't be a working 6381 // version of the app 6382 // writer 6383 synchronized (mPackages) { 6384 // Just remove the loaded entries from package lists. 6385 mPackages.remove(ps.name); 6386 } 6387 6388 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6389 + " reverting from " + ps.codePathString 6390 + ": new version " + pkg.mVersionCode 6391 + " better than installed " + ps.versionCode); 6392 6393 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6394 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6395 synchronized (mInstallLock) { 6396 args.cleanUpResourcesLI(); 6397 } 6398 synchronized (mPackages) { 6399 mSettings.enableSystemPackageLPw(ps.name); 6400 } 6401 updatedPkgBetter = true; 6402 } 6403 } 6404 } 6405 6406 if (updatedPkg != null) { 6407 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6408 // initially 6409 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6410 6411 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6412 // flag set initially 6413 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6414 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6415 } 6416 } 6417 6418 // Verify certificates against what was last scanned 6419 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 6420 6421 /* 6422 * A new system app appeared, but we already had a non-system one of the 6423 * same name installed earlier. 6424 */ 6425 boolean shouldHideSystemApp = false; 6426 if (updatedPkg == null && ps != null 6427 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6428 /* 6429 * Check to make sure the signatures match first. If they don't, 6430 * wipe the installed application and its data. 6431 */ 6432 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6433 != PackageManager.SIGNATURE_MATCH) { 6434 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6435 + " signatures don't match existing userdata copy; removing"); 6436 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 6437 ps = null; 6438 } else { 6439 /* 6440 * If the newly-added system app is an older version than the 6441 * already installed version, hide it. It will be scanned later 6442 * and re-added like an update. 6443 */ 6444 if (pkg.mVersionCode <= ps.versionCode) { 6445 shouldHideSystemApp = true; 6446 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6447 + " but new version " + pkg.mVersionCode + " better than installed " 6448 + ps.versionCode + "; hiding system"); 6449 } else { 6450 /* 6451 * The newly found system app is a newer version that the 6452 * one previously installed. Simply remove the 6453 * already-installed application and replace it with our own 6454 * while keeping the application data. 6455 */ 6456 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6457 + " reverting from " + ps.codePathString + ": new version " 6458 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6459 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6460 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6461 synchronized (mInstallLock) { 6462 args.cleanUpResourcesLI(); 6463 } 6464 } 6465 } 6466 } 6467 6468 // The apk is forward locked (not public) if its code and resources 6469 // are kept in different files. (except for app in either system or 6470 // vendor path). 6471 // TODO grab this value from PackageSettings 6472 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6473 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6474 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6475 } 6476 } 6477 6478 // TODO: extend to support forward-locked splits 6479 String resourcePath = null; 6480 String baseResourcePath = null; 6481 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6482 if (ps != null && ps.resourcePathString != null) { 6483 resourcePath = ps.resourcePathString; 6484 baseResourcePath = ps.resourcePathString; 6485 } else { 6486 // Should not happen at all. Just log an error. 6487 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6488 } 6489 } else { 6490 resourcePath = pkg.codePath; 6491 baseResourcePath = pkg.baseCodePath; 6492 } 6493 6494 // Set application objects path explicitly. 6495 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 6496 pkg.applicationInfo.setCodePath(pkg.codePath); 6497 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 6498 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 6499 pkg.applicationInfo.setResourcePath(resourcePath); 6500 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 6501 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 6502 6503 // Note that we invoke the following method only if we are about to unpack an application 6504 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6505 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6506 6507 /* 6508 * If the system app should be overridden by a previously installed 6509 * data, hide the system app now and let the /data/app scan pick it up 6510 * again. 6511 */ 6512 if (shouldHideSystemApp) { 6513 synchronized (mPackages) { 6514 mSettings.disableSystemPackageLPw(pkg.packageName); 6515 } 6516 } 6517 6518 return scannedPkg; 6519 } 6520 6521 private static String fixProcessName(String defProcessName, 6522 String processName, int uid) { 6523 if (processName == null) { 6524 return defProcessName; 6525 } 6526 return processName; 6527 } 6528 6529 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6530 throws PackageManagerException { 6531 if (pkgSetting.signatures.mSignatures != null) { 6532 // Already existing package. Make sure signatures match 6533 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6534 == PackageManager.SIGNATURE_MATCH; 6535 if (!match) { 6536 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6537 == PackageManager.SIGNATURE_MATCH; 6538 } 6539 if (!match) { 6540 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6541 == PackageManager.SIGNATURE_MATCH; 6542 } 6543 if (!match) { 6544 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6545 + pkg.packageName + " signatures do not match the " 6546 + "previously installed version; ignoring!"); 6547 } 6548 } 6549 6550 // Check for shared user signatures 6551 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6552 // Already existing package. Make sure signatures match 6553 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6554 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6555 if (!match) { 6556 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6557 == PackageManager.SIGNATURE_MATCH; 6558 } 6559 if (!match) { 6560 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6561 == PackageManager.SIGNATURE_MATCH; 6562 } 6563 if (!match) { 6564 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6565 "Package " + pkg.packageName 6566 + " has no signatures that match those in shared user " 6567 + pkgSetting.sharedUser.name + "; ignoring!"); 6568 } 6569 } 6570 } 6571 6572 /** 6573 * Enforces that only the system UID or root's UID can call a method exposed 6574 * via Binder. 6575 * 6576 * @param message used as message if SecurityException is thrown 6577 * @throws SecurityException if the caller is not system or root 6578 */ 6579 private static final void enforceSystemOrRoot(String message) { 6580 final int uid = Binder.getCallingUid(); 6581 if (uid != Process.SYSTEM_UID && uid != 0) { 6582 throw new SecurityException(message); 6583 } 6584 } 6585 6586 @Override 6587 public void performFstrimIfNeeded() { 6588 enforceSystemOrRoot("Only the system can request fstrim"); 6589 6590 // Before everything else, see whether we need to fstrim. 6591 try { 6592 IMountService ms = PackageHelper.getMountService(); 6593 if (ms != null) { 6594 final boolean isUpgrade = isUpgrade(); 6595 boolean doTrim = isUpgrade; 6596 if (doTrim) { 6597 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6598 } else { 6599 final long interval = android.provider.Settings.Global.getLong( 6600 mContext.getContentResolver(), 6601 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6602 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6603 if (interval > 0) { 6604 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6605 if (timeSinceLast > interval) { 6606 doTrim = true; 6607 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6608 + "; running immediately"); 6609 } 6610 } 6611 } 6612 if (doTrim) { 6613 if (!isFirstBoot()) { 6614 try { 6615 ActivityManagerNative.getDefault().showBootMessage( 6616 mContext.getResources().getString( 6617 R.string.android_upgrading_fstrim), true); 6618 } catch (RemoteException e) { 6619 } 6620 } 6621 ms.runMaintenance(); 6622 } 6623 } else { 6624 Slog.e(TAG, "Mount service unavailable!"); 6625 } 6626 } catch (RemoteException e) { 6627 // Can't happen; MountService is local 6628 } 6629 } 6630 6631 @Override 6632 public void extractPackagesIfNeeded() { 6633 enforceSystemOrRoot("Only the system can request package extraction"); 6634 6635 // Extract pacakges only if profile-guided compilation is enabled because 6636 // otherwise BackgroundDexOptService will not dexopt them later. 6637 if (mUseJitProfiles) { 6638 ArraySet<String> pkgs = getOptimizablePackages(); 6639 if (pkgs != null) { 6640 for (String pkg : pkgs) { 6641 performDexOpt(pkg, null /* instructionSet */, false /* useProfiles */, 6642 true /* extractOnly */); 6643 } 6644 } 6645 } 6646 } 6647 6648 private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) { 6649 List<ResolveInfo> ris = null; 6650 try { 6651 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6652 intent, null, 0, userId); 6653 } catch (RemoteException e) { 6654 } 6655 ArraySet<String> pkgNames = new ArraySet<String>(); 6656 if (ris != null) { 6657 for (ResolveInfo ri : ris) { 6658 pkgNames.add(ri.activityInfo.packageName); 6659 } 6660 } 6661 return pkgNames; 6662 } 6663 6664 @Override 6665 public void notifyPackageUse(String packageName) { 6666 synchronized (mPackages) { 6667 PackageParser.Package p = mPackages.get(packageName); 6668 if (p == null) { 6669 return; 6670 } 6671 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6672 } 6673 } 6674 6675 // TODO: this is not used nor needed. Delete it. 6676 @Override 6677 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6678 return performDexOptTraced(packageName, instructionSet, false /* useProfiles */, 6679 false /* extractOnly */); 6680 } 6681 6682 public boolean performDexOpt(String packageName, String instructionSet, boolean useProfiles, 6683 boolean extractOnly) { 6684 return performDexOptTraced(packageName, instructionSet, useProfiles, extractOnly); 6685 } 6686 6687 private boolean performDexOptTraced(String packageName, String instructionSet, 6688 boolean useProfiles, boolean extractOnly) { 6689 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6690 try { 6691 return performDexOptInternal(packageName, instructionSet, useProfiles, extractOnly); 6692 } finally { 6693 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6694 } 6695 } 6696 6697 private boolean performDexOptInternal(String packageName, String instructionSet, 6698 boolean useProfiles, boolean extractOnly) { 6699 PackageParser.Package p; 6700 final String targetInstructionSet; 6701 synchronized (mPackages) { 6702 p = mPackages.get(packageName); 6703 if (p == null) { 6704 return false; 6705 } 6706 mPackageUsage.write(false); 6707 6708 targetInstructionSet = instructionSet != null ? instructionSet : 6709 getPrimaryInstructionSet(p.applicationInfo); 6710 if (!useProfiles && p.mDexOptPerformed.contains(targetInstructionSet)) { 6711 // Skip only if we do not use profiles since they might trigger a recompilation. 6712 return false; 6713 } 6714 } 6715 long callingId = Binder.clearCallingIdentity(); 6716 try { 6717 synchronized (mInstallLock) { 6718 final String[] instructionSets = new String[] { targetInstructionSet }; 6719 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6720 true /* inclDependencies */, useProfiles, extractOnly); 6721 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6722 } 6723 } finally { 6724 Binder.restoreCallingIdentity(callingId); 6725 } 6726 } 6727 6728 public ArraySet<String> getOptimizablePackages() { 6729 ArraySet<String> pkgs = new ArraySet<String>(); 6730 synchronized (mPackages) { 6731 for (PackageParser.Package p : mPackages.values()) { 6732 if (PackageDexOptimizer.canOptimizePackage(p)) { 6733 pkgs.add(p.packageName); 6734 } 6735 } 6736 } 6737 return pkgs; 6738 } 6739 6740 public void shutdown() { 6741 mPackageUsage.write(true); 6742 } 6743 6744 @Override 6745 public void forceDexOpt(String packageName) { 6746 enforceSystemOrRoot("forceDexOpt"); 6747 6748 PackageParser.Package pkg; 6749 synchronized (mPackages) { 6750 pkg = mPackages.get(packageName); 6751 if (pkg == null) { 6752 throw new IllegalArgumentException("Unknown package: " + packageName); 6753 } 6754 } 6755 6756 synchronized (mInstallLock) { 6757 final String[] instructionSets = new String[] { 6758 getPrimaryInstructionSet(pkg.applicationInfo) }; 6759 6760 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6761 6762 // Whoever is calling forceDexOpt wants a fully compiled package. 6763 // Don't use profiles since that may cause compilation to be skipped. 6764 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6765 true /* inclDependencies */, false /* useProfiles */, 6766 false /* extractOnly */); 6767 6768 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6769 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6770 throw new IllegalStateException("Failed to dexopt: " + res); 6771 } 6772 } 6773 } 6774 6775 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6776 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6777 Slog.w(TAG, "Unable to update from " + oldPkg.name 6778 + " to " + newPkg.packageName 6779 + ": old package not in system partition"); 6780 return false; 6781 } else if (mPackages.get(oldPkg.name) != null) { 6782 Slog.w(TAG, "Unable to update from " + oldPkg.name 6783 + " to " + newPkg.packageName 6784 + ": old package still exists"); 6785 return false; 6786 } 6787 return true; 6788 } 6789 6790 private boolean removeDataDirsLI(String volumeUuid, String packageName) { 6791 // TODO: triage flags as part of 26466827 6792 final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 6793 6794 boolean res = true; 6795 final int[] users = sUserManager.getUserIds(); 6796 for (int user : users) { 6797 try { 6798 mInstaller.destroyAppData(volumeUuid, packageName, user, flags); 6799 } catch (InstallerException e) { 6800 Slog.w(TAG, "Failed to delete data directory", e); 6801 res = false; 6802 } 6803 } 6804 return res; 6805 } 6806 6807 void removeCodePathLI(File codePath) { 6808 if (codePath.isDirectory()) { 6809 try { 6810 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 6811 } catch (InstallerException e) { 6812 Slog.w(TAG, "Failed to remove code path", e); 6813 } 6814 } else { 6815 codePath.delete(); 6816 } 6817 } 6818 6819 void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) { 6820 try { 6821 mInstaller.destroyAppData(volumeUuid, packageName, userId, flags); 6822 } catch (InstallerException e) { 6823 Slog.w(TAG, "Failed to destroy app data", e); 6824 } 6825 } 6826 6827 void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags, 6828 int appId, String seinfo) { 6829 try { 6830 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo); 6831 } catch (InstallerException e) { 6832 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 6833 } 6834 } 6835 6836 private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6837 // TODO: triage flags as part of 26466827 6838 final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 6839 6840 final int[] users = sUserManager.getUserIds(); 6841 for (int user : users) { 6842 try { 6843 mInstaller.clearAppData(volumeUuid, packageName, user, 6844 flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 6845 } catch (InstallerException e) { 6846 Slog.w(TAG, "Failed to delete code cache directory", e); 6847 } 6848 } 6849 } 6850 6851 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6852 PackageParser.Package changingLib) { 6853 if (file.path != null) { 6854 usesLibraryFiles.add(file.path); 6855 return; 6856 } 6857 PackageParser.Package p = mPackages.get(file.apk); 6858 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6859 // If we are doing this while in the middle of updating a library apk, 6860 // then we need to make sure to use that new apk for determining the 6861 // dependencies here. (We haven't yet finished committing the new apk 6862 // to the package manager state.) 6863 if (p == null || p.packageName.equals(changingLib.packageName)) { 6864 p = changingLib; 6865 } 6866 } 6867 if (p != null) { 6868 usesLibraryFiles.addAll(p.getAllCodePaths()); 6869 } 6870 } 6871 6872 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6873 PackageParser.Package changingLib) throws PackageManagerException { 6874 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6875 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6876 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6877 for (int i=0; i<N; i++) { 6878 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6879 if (file == null) { 6880 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6881 "Package " + pkg.packageName + " requires unavailable shared library " 6882 + pkg.usesLibraries.get(i) + "; failing!"); 6883 } 6884 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6885 } 6886 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6887 for (int i=0; i<N; i++) { 6888 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6889 if (file == null) { 6890 Slog.w(TAG, "Package " + pkg.packageName 6891 + " desires unavailable shared library " 6892 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6893 } else { 6894 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6895 } 6896 } 6897 N = usesLibraryFiles.size(); 6898 if (N > 0) { 6899 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6900 } else { 6901 pkg.usesLibraryFiles = null; 6902 } 6903 } 6904 } 6905 6906 private static boolean hasString(List<String> list, List<String> which) { 6907 if (list == null) { 6908 return false; 6909 } 6910 for (int i=list.size()-1; i>=0; i--) { 6911 for (int j=which.size()-1; j>=0; j--) { 6912 if (which.get(j).equals(list.get(i))) { 6913 return true; 6914 } 6915 } 6916 } 6917 return false; 6918 } 6919 6920 private void updateAllSharedLibrariesLPw() { 6921 for (PackageParser.Package pkg : mPackages.values()) { 6922 try { 6923 updateSharedLibrariesLPw(pkg, null); 6924 } catch (PackageManagerException e) { 6925 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6926 } 6927 } 6928 } 6929 6930 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6931 PackageParser.Package changingPkg) { 6932 ArrayList<PackageParser.Package> res = null; 6933 for (PackageParser.Package pkg : mPackages.values()) { 6934 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6935 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6936 if (res == null) { 6937 res = new ArrayList<PackageParser.Package>(); 6938 } 6939 res.add(pkg); 6940 try { 6941 updateSharedLibrariesLPw(pkg, changingPkg); 6942 } catch (PackageManagerException e) { 6943 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6944 } 6945 } 6946 } 6947 return res; 6948 } 6949 6950 /** 6951 * Derive the value of the {@code cpuAbiOverride} based on the provided 6952 * value and an optional stored value from the package settings. 6953 */ 6954 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6955 String cpuAbiOverride = null; 6956 6957 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6958 cpuAbiOverride = null; 6959 } else if (abiOverride != null) { 6960 cpuAbiOverride = abiOverride; 6961 } else if (settings != null) { 6962 cpuAbiOverride = settings.cpuAbiOverrideString; 6963 } 6964 6965 return cpuAbiOverride; 6966 } 6967 6968 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 6969 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6970 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6971 try { 6972 return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 6973 } finally { 6974 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6975 } 6976 } 6977 6978 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6979 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6980 boolean success = false; 6981 try { 6982 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6983 currentTime, user); 6984 success = true; 6985 return res; 6986 } finally { 6987 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6988 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6989 } 6990 } 6991 } 6992 6993 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6994 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6995 final File scanFile = new File(pkg.codePath); 6996 if (pkg.applicationInfo.getCodePath() == null || 6997 pkg.applicationInfo.getResourcePath() == null) { 6998 // Bail out. The resource and code paths haven't been set. 6999 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7000 "Code and resource paths haven't been set correctly"); 7001 } 7002 7003 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7004 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7005 } else { 7006 // Only allow system apps to be flagged as core apps. 7007 pkg.coreApp = false; 7008 } 7009 7010 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7011 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7012 } 7013 7014 if (mCustomResolverComponentName != null && 7015 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7016 setUpCustomResolverActivity(pkg); 7017 } 7018 7019 if (pkg.packageName.equals("android")) { 7020 synchronized (mPackages) { 7021 if (mAndroidApplication != null) { 7022 Slog.w(TAG, "*************************************************"); 7023 Slog.w(TAG, "Core android package being redefined. Skipping."); 7024 Slog.w(TAG, " file=" + scanFile); 7025 Slog.w(TAG, "*************************************************"); 7026 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7027 "Core android package being redefined. Skipping."); 7028 } 7029 7030 // Set up information for our fall-back user intent resolution activity. 7031 mPlatformPackage = pkg; 7032 pkg.mVersionCode = mSdkVersion; 7033 mAndroidApplication = pkg.applicationInfo; 7034 7035 if (!mResolverReplaced) { 7036 mResolveActivity.applicationInfo = mAndroidApplication; 7037 mResolveActivity.name = ResolverActivity.class.getName(); 7038 mResolveActivity.packageName = mAndroidApplication.packageName; 7039 mResolveActivity.processName = "system:ui"; 7040 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7041 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7042 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7043 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7044 mResolveActivity.exported = true; 7045 mResolveActivity.enabled = true; 7046 mResolveInfo.activityInfo = mResolveActivity; 7047 mResolveInfo.priority = 0; 7048 mResolveInfo.preferredOrder = 0; 7049 mResolveInfo.match = 0; 7050 mResolveComponentName = new ComponentName( 7051 mAndroidApplication.packageName, mResolveActivity.name); 7052 } 7053 } 7054 } 7055 7056 if (DEBUG_PACKAGE_SCANNING) { 7057 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7058 Log.d(TAG, "Scanning package " + pkg.packageName); 7059 } 7060 7061 if (mPackages.containsKey(pkg.packageName) 7062 || mSharedLibraries.containsKey(pkg.packageName)) { 7063 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7064 "Application package " + pkg.packageName 7065 + " already installed. Skipping duplicate."); 7066 } 7067 7068 // If we're only installing presumed-existing packages, require that the 7069 // scanned APK is both already known and at the path previously established 7070 // for it. Previously unknown packages we pick up normally, but if we have an 7071 // a priori expectation about this package's install presence, enforce it. 7072 // With a singular exception for new system packages. When an OTA contains 7073 // a new system package, we allow the codepath to change from a system location 7074 // to the user-installed location. If we don't allow this change, any newer, 7075 // user-installed version of the application will be ignored. 7076 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7077 if (mExpectingBetter.containsKey(pkg.packageName)) { 7078 logCriticalInfo(Log.WARN, 7079 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7080 } else { 7081 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7082 if (known != null) { 7083 if (DEBUG_PACKAGE_SCANNING) { 7084 Log.d(TAG, "Examining " + pkg.codePath 7085 + " and requiring known paths " + known.codePathString 7086 + " & " + known.resourcePathString); 7087 } 7088 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7089 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 7090 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7091 "Application package " + pkg.packageName 7092 + " found at " + pkg.applicationInfo.getCodePath() 7093 + " but expected at " + known.codePathString + "; ignoring."); 7094 } 7095 } 7096 } 7097 } 7098 7099 // Initialize package source and resource directories 7100 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7101 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7102 7103 SharedUserSetting suid = null; 7104 PackageSetting pkgSetting = null; 7105 7106 if (!isSystemApp(pkg)) { 7107 // Only system apps can use these features. 7108 pkg.mOriginalPackages = null; 7109 pkg.mRealPackage = null; 7110 pkg.mAdoptPermissions = null; 7111 } 7112 7113 // writer 7114 synchronized (mPackages) { 7115 if (pkg.mSharedUserId != null) { 7116 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7117 if (suid == null) { 7118 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7119 "Creating application package " + pkg.packageName 7120 + " for shared user failed"); 7121 } 7122 if (DEBUG_PACKAGE_SCANNING) { 7123 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7124 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7125 + "): packages=" + suid.packages); 7126 } 7127 } 7128 7129 // Check if we are renaming from an original package name. 7130 PackageSetting origPackage = null; 7131 String realName = null; 7132 if (pkg.mOriginalPackages != null) { 7133 // This package may need to be renamed to a previously 7134 // installed name. Let's check on that... 7135 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7136 if (pkg.mOriginalPackages.contains(renamed)) { 7137 // This package had originally been installed as the 7138 // original name, and we have already taken care of 7139 // transitioning to the new one. Just update the new 7140 // one to continue using the old name. 7141 realName = pkg.mRealPackage; 7142 if (!pkg.packageName.equals(renamed)) { 7143 // Callers into this function may have already taken 7144 // care of renaming the package; only do it here if 7145 // it is not already done. 7146 pkg.setPackageName(renamed); 7147 } 7148 7149 } else { 7150 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7151 if ((origPackage = mSettings.peekPackageLPr( 7152 pkg.mOriginalPackages.get(i))) != null) { 7153 // We do have the package already installed under its 7154 // original name... should we use it? 7155 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7156 // New package is not compatible with original. 7157 origPackage = null; 7158 continue; 7159 } else if (origPackage.sharedUser != null) { 7160 // Make sure uid is compatible between packages. 7161 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7162 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7163 + " to " + pkg.packageName + ": old uid " 7164 + origPackage.sharedUser.name 7165 + " differs from " + pkg.mSharedUserId); 7166 origPackage = null; 7167 continue; 7168 } 7169 } else { 7170 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7171 + pkg.packageName + " to old name " + origPackage.name); 7172 } 7173 break; 7174 } 7175 } 7176 } 7177 } 7178 7179 if (mTransferedPackages.contains(pkg.packageName)) { 7180 Slog.w(TAG, "Package " + pkg.packageName 7181 + " was transferred to another, but its .apk remains"); 7182 } 7183 7184 // Just create the setting, don't add it yet. For already existing packages 7185 // the PkgSetting exists already and doesn't have to be created. 7186 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7187 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7188 pkg.applicationInfo.primaryCpuAbi, 7189 pkg.applicationInfo.secondaryCpuAbi, 7190 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7191 user, false); 7192 if (pkgSetting == null) { 7193 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7194 "Creating application package " + pkg.packageName + " failed"); 7195 } 7196 7197 if (pkgSetting.origPackage != null) { 7198 // If we are first transitioning from an original package, 7199 // fix up the new package's name now. We need to do this after 7200 // looking up the package under its new name, so getPackageLP 7201 // can take care of fiddling things correctly. 7202 pkg.setPackageName(origPackage.name); 7203 7204 // File a report about this. 7205 String msg = "New package " + pkgSetting.realName 7206 + " renamed to replace old package " + pkgSetting.name; 7207 reportSettingsProblem(Log.WARN, msg); 7208 7209 // Make a note of it. 7210 mTransferedPackages.add(origPackage.name); 7211 7212 // No longer need to retain this. 7213 pkgSetting.origPackage = null; 7214 } 7215 7216 if (realName != null) { 7217 // Make a note of it. 7218 mTransferedPackages.add(pkg.packageName); 7219 } 7220 7221 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7222 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7223 } 7224 7225 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7226 // Check all shared libraries and map to their actual file path. 7227 // We only do this here for apps not on a system dir, because those 7228 // are the only ones that can fail an install due to this. We 7229 // will take care of the system apps by updating all of their 7230 // library paths after the scan is done. 7231 updateSharedLibrariesLPw(pkg, null); 7232 } 7233 7234 if (mFoundPolicyFile) { 7235 SELinuxMMAC.assignSeinfoValue(pkg); 7236 } 7237 7238 pkg.applicationInfo.uid = pkgSetting.appId; 7239 pkg.mExtras = pkgSetting; 7240 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7241 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7242 // We just determined the app is signed correctly, so bring 7243 // over the latest parsed certs. 7244 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7245 } else { 7246 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7247 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7248 "Package " + pkg.packageName + " upgrade keys do not match the " 7249 + "previously installed version"); 7250 } else { 7251 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7252 String msg = "System package " + pkg.packageName 7253 + " signature changed; retaining data."; 7254 reportSettingsProblem(Log.WARN, msg); 7255 } 7256 } 7257 } else { 7258 try { 7259 verifySignaturesLP(pkgSetting, pkg); 7260 // We just determined the app is signed correctly, so bring 7261 // over the latest parsed certs. 7262 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7263 } catch (PackageManagerException e) { 7264 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7265 throw e; 7266 } 7267 // The signature has changed, but this package is in the system 7268 // image... let's recover! 7269 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7270 // However... if this package is part of a shared user, but it 7271 // doesn't match the signature of the shared user, let's fail. 7272 // What this means is that you can't change the signatures 7273 // associated with an overall shared user, which doesn't seem all 7274 // that unreasonable. 7275 if (pkgSetting.sharedUser != null) { 7276 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7277 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7278 throw new PackageManagerException( 7279 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7280 "Signature mismatch for shared user: " 7281 + pkgSetting.sharedUser); 7282 } 7283 } 7284 // File a report about this. 7285 String msg = "System package " + pkg.packageName 7286 + " signature changed; retaining data."; 7287 reportSettingsProblem(Log.WARN, msg); 7288 } 7289 } 7290 // Verify that this new package doesn't have any content providers 7291 // that conflict with existing packages. Only do this if the 7292 // package isn't already installed, since we don't want to break 7293 // things that are installed. 7294 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7295 final int N = pkg.providers.size(); 7296 int i; 7297 for (i=0; i<N; i++) { 7298 PackageParser.Provider p = pkg.providers.get(i); 7299 if (p.info.authority != null) { 7300 String names[] = p.info.authority.split(";"); 7301 for (int j = 0; j < names.length; j++) { 7302 if (mProvidersByAuthority.containsKey(names[j])) { 7303 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7304 final String otherPackageName = 7305 ((other != null && other.getComponentName() != null) ? 7306 other.getComponentName().getPackageName() : "?"); 7307 throw new PackageManagerException( 7308 INSTALL_FAILED_CONFLICTING_PROVIDER, 7309 "Can't install because provider name " + names[j] 7310 + " (in package " + pkg.applicationInfo.packageName 7311 + ") is already used by " + otherPackageName); 7312 } 7313 } 7314 } 7315 } 7316 } 7317 7318 if (pkg.mAdoptPermissions != null) { 7319 // This package wants to adopt ownership of permissions from 7320 // another package. 7321 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7322 final String origName = pkg.mAdoptPermissions.get(i); 7323 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7324 if (orig != null) { 7325 if (verifyPackageUpdateLPr(orig, pkg)) { 7326 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7327 + pkg.packageName); 7328 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7329 } 7330 } 7331 } 7332 } 7333 } 7334 7335 final String pkgName = pkg.packageName; 7336 7337 final long scanFileTime = scanFile.lastModified(); 7338 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7339 pkg.applicationInfo.processName = fixProcessName( 7340 pkg.applicationInfo.packageName, 7341 pkg.applicationInfo.processName, 7342 pkg.applicationInfo.uid); 7343 7344 if (pkg != mPlatformPackage) { 7345 // Get all of our default paths setup 7346 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7347 } 7348 7349 final String path = scanFile.getPath(); 7350 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7351 7352 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7353 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7354 7355 // Some system apps still use directory structure for native libraries 7356 // in which case we might end up not detecting abi solely based on apk 7357 // structure. Try to detect abi based on directory structure. 7358 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7359 pkg.applicationInfo.primaryCpuAbi == null) { 7360 setBundledAppAbisAndRoots(pkg, pkgSetting); 7361 setNativeLibraryPaths(pkg); 7362 } 7363 7364 } else { 7365 if ((scanFlags & SCAN_MOVE) != 0) { 7366 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7367 // but we already have this packages package info in the PackageSetting. We just 7368 // use that and derive the native library path based on the new codepath. 7369 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7370 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7371 } 7372 7373 // Set native library paths again. For moves, the path will be updated based on the 7374 // ABIs we've determined above. For non-moves, the path will be updated based on the 7375 // ABIs we determined during compilation, but the path will depend on the final 7376 // package path (after the rename away from the stage path). 7377 setNativeLibraryPaths(pkg); 7378 } 7379 7380 // This is a special case for the "system" package, where the ABI is 7381 // dictated by the zygote configuration (and init.rc). We should keep track 7382 // of this ABI so that we can deal with "normal" applications that run under 7383 // the same UID correctly. 7384 if (mPlatformPackage == pkg) { 7385 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7386 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7387 } 7388 7389 // If there's a mismatch between the abi-override in the package setting 7390 // and the abiOverride specified for the install. Warn about this because we 7391 // would've already compiled the app without taking the package setting into 7392 // account. 7393 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7394 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7395 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7396 " for package " + pkg.packageName); 7397 } 7398 } 7399 7400 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7401 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7402 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7403 7404 // Copy the derived override back to the parsed package, so that we can 7405 // update the package settings accordingly. 7406 pkg.cpuAbiOverride = cpuAbiOverride; 7407 7408 if (DEBUG_ABI_SELECTION) { 7409 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7410 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7411 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7412 } 7413 7414 // Push the derived path down into PackageSettings so we know what to 7415 // clean up at uninstall time. 7416 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7417 7418 if (DEBUG_ABI_SELECTION) { 7419 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7420 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7421 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7422 } 7423 7424 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7425 // We don't do this here during boot because we can do it all 7426 // at once after scanning all existing packages. 7427 // 7428 // We also do this *before* we perform dexopt on this package, so that 7429 // we can avoid redundant dexopts, and also to make sure we've got the 7430 // code and package path correct. 7431 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7432 pkg, true /* boot complete */); 7433 } 7434 7435 if (mFactoryTest && pkg.requestedPermissions.contains( 7436 android.Manifest.permission.FACTORY_TEST)) { 7437 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7438 } 7439 7440 ArrayList<PackageParser.Package> clientLibPkgs = null; 7441 7442 // writer 7443 synchronized (mPackages) { 7444 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7445 // Only system apps can add new shared libraries. 7446 if (pkg.libraryNames != null) { 7447 for (int i=0; i<pkg.libraryNames.size(); i++) { 7448 String name = pkg.libraryNames.get(i); 7449 boolean allowed = false; 7450 if (pkg.isUpdatedSystemApp()) { 7451 // New library entries can only be added through the 7452 // system image. This is important to get rid of a lot 7453 // of nasty edge cases: for example if we allowed a non- 7454 // system update of the app to add a library, then uninstalling 7455 // the update would make the library go away, and assumptions 7456 // we made such as through app install filtering would now 7457 // have allowed apps on the device which aren't compatible 7458 // with it. Better to just have the restriction here, be 7459 // conservative, and create many fewer cases that can negatively 7460 // impact the user experience. 7461 final PackageSetting sysPs = mSettings 7462 .getDisabledSystemPkgLPr(pkg.packageName); 7463 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7464 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7465 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7466 allowed = true; 7467 break; 7468 } 7469 } 7470 } 7471 } else { 7472 allowed = true; 7473 } 7474 if (allowed) { 7475 if (!mSharedLibraries.containsKey(name)) { 7476 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7477 } else if (!name.equals(pkg.packageName)) { 7478 Slog.w(TAG, "Package " + pkg.packageName + " library " 7479 + name + " already exists; skipping"); 7480 } 7481 } else { 7482 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7483 + name + " that is not declared on system image; skipping"); 7484 } 7485 } 7486 if ((scanFlags & SCAN_BOOTING) == 0) { 7487 // If we are not booting, we need to update any applications 7488 // that are clients of our shared library. If we are booting, 7489 // this will all be done once the scan is complete. 7490 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7491 } 7492 } 7493 } 7494 } 7495 7496 // Request the ActivityManager to kill the process(only for existing packages) 7497 // so that we do not end up in a confused state while the user is still using the older 7498 // version of the application while the new one gets installed. 7499 if ((scanFlags & SCAN_REPLACING) != 0) { 7500 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7501 7502 killApplication(pkg.applicationInfo.packageName, 7503 pkg.applicationInfo.uid, "replace pkg"); 7504 7505 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7506 } 7507 7508 // Also need to kill any apps that are dependent on the library. 7509 if (clientLibPkgs != null) { 7510 for (int i=0; i<clientLibPkgs.size(); i++) { 7511 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7512 killApplication(clientPkg.applicationInfo.packageName, 7513 clientPkg.applicationInfo.uid, "update lib"); 7514 } 7515 } 7516 7517 // Make sure we're not adding any bogus keyset info 7518 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7519 ksms.assertScannedPackageValid(pkg); 7520 7521 // writer 7522 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7523 7524 boolean createIdmapFailed = false; 7525 synchronized (mPackages) { 7526 // We don't expect installation to fail beyond this point 7527 7528 // Add the new setting to mSettings 7529 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7530 // Add the new setting to mPackages 7531 mPackages.put(pkg.applicationInfo.packageName, pkg); 7532 // Make sure we don't accidentally delete its data. 7533 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7534 while (iter.hasNext()) { 7535 PackageCleanItem item = iter.next(); 7536 if (pkgName.equals(item.packageName)) { 7537 iter.remove(); 7538 } 7539 } 7540 7541 // Take care of first install / last update times. 7542 if (currentTime != 0) { 7543 if (pkgSetting.firstInstallTime == 0) { 7544 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7545 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7546 pkgSetting.lastUpdateTime = currentTime; 7547 } 7548 } else if (pkgSetting.firstInstallTime == 0) { 7549 // We need *something*. Take time time stamp of the file. 7550 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7551 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7552 if (scanFileTime != pkgSetting.timeStamp) { 7553 // A package on the system image has changed; consider this 7554 // to be an update. 7555 pkgSetting.lastUpdateTime = scanFileTime; 7556 } 7557 } 7558 7559 // Add the package's KeySets to the global KeySetManagerService 7560 ksms.addScannedPackageLPw(pkg); 7561 7562 int N = pkg.providers.size(); 7563 StringBuilder r = null; 7564 int i; 7565 for (i=0; i<N; i++) { 7566 PackageParser.Provider p = pkg.providers.get(i); 7567 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7568 p.info.processName, pkg.applicationInfo.uid); 7569 mProviders.addProvider(p); 7570 p.syncable = p.info.isSyncable; 7571 if (p.info.authority != null) { 7572 String names[] = p.info.authority.split(";"); 7573 p.info.authority = null; 7574 for (int j = 0; j < names.length; j++) { 7575 if (j == 1 && p.syncable) { 7576 // We only want the first authority for a provider to possibly be 7577 // syncable, so if we already added this provider using a different 7578 // authority clear the syncable flag. We copy the provider before 7579 // changing it because the mProviders object contains a reference 7580 // to a provider that we don't want to change. 7581 // Only do this for the second authority since the resulting provider 7582 // object can be the same for all future authorities for this provider. 7583 p = new PackageParser.Provider(p); 7584 p.syncable = false; 7585 } 7586 if (!mProvidersByAuthority.containsKey(names[j])) { 7587 mProvidersByAuthority.put(names[j], p); 7588 if (p.info.authority == null) { 7589 p.info.authority = names[j]; 7590 } else { 7591 p.info.authority = p.info.authority + ";" + names[j]; 7592 } 7593 if (DEBUG_PACKAGE_SCANNING) { 7594 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7595 Log.d(TAG, "Registered content provider: " + names[j] 7596 + ", className = " + p.info.name + ", isSyncable = " 7597 + p.info.isSyncable); 7598 } 7599 } else { 7600 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7601 Slog.w(TAG, "Skipping provider name " + names[j] + 7602 " (in package " + pkg.applicationInfo.packageName + 7603 "): name already used by " 7604 + ((other != null && other.getComponentName() != null) 7605 ? other.getComponentName().getPackageName() : "?")); 7606 } 7607 } 7608 } 7609 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7610 if (r == null) { 7611 r = new StringBuilder(256); 7612 } else { 7613 r.append(' '); 7614 } 7615 r.append(p.info.name); 7616 } 7617 } 7618 if (r != null) { 7619 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7620 } 7621 7622 N = pkg.services.size(); 7623 r = null; 7624 for (i=0; i<N; i++) { 7625 PackageParser.Service s = pkg.services.get(i); 7626 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7627 s.info.processName, pkg.applicationInfo.uid); 7628 mServices.addService(s); 7629 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7630 if (r == null) { 7631 r = new StringBuilder(256); 7632 } else { 7633 r.append(' '); 7634 } 7635 r.append(s.info.name); 7636 } 7637 } 7638 if (r != null) { 7639 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7640 } 7641 7642 N = pkg.receivers.size(); 7643 r = null; 7644 for (i=0; i<N; i++) { 7645 PackageParser.Activity a = pkg.receivers.get(i); 7646 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7647 a.info.processName, pkg.applicationInfo.uid); 7648 mReceivers.addActivity(a, "receiver"); 7649 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7650 if (r == null) { 7651 r = new StringBuilder(256); 7652 } else { 7653 r.append(' '); 7654 } 7655 r.append(a.info.name); 7656 } 7657 } 7658 if (r != null) { 7659 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7660 } 7661 7662 N = pkg.activities.size(); 7663 r = null; 7664 for (i=0; i<N; i++) { 7665 PackageParser.Activity a = pkg.activities.get(i); 7666 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7667 a.info.processName, pkg.applicationInfo.uid); 7668 mActivities.addActivity(a, "activity"); 7669 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7670 if (r == null) { 7671 r = new StringBuilder(256); 7672 } else { 7673 r.append(' '); 7674 } 7675 r.append(a.info.name); 7676 } 7677 } 7678 if (r != null) { 7679 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7680 } 7681 7682 N = pkg.permissionGroups.size(); 7683 r = null; 7684 for (i=0; i<N; i++) { 7685 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7686 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7687 if (cur == null) { 7688 mPermissionGroups.put(pg.info.name, pg); 7689 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7690 if (r == null) { 7691 r = new StringBuilder(256); 7692 } else { 7693 r.append(' '); 7694 } 7695 r.append(pg.info.name); 7696 } 7697 } else { 7698 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7699 + pg.info.packageName + " ignored: original from " 7700 + cur.info.packageName); 7701 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7702 if (r == null) { 7703 r = new StringBuilder(256); 7704 } else { 7705 r.append(' '); 7706 } 7707 r.append("DUP:"); 7708 r.append(pg.info.name); 7709 } 7710 } 7711 } 7712 if (r != null) { 7713 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7714 } 7715 7716 N = pkg.permissions.size(); 7717 r = null; 7718 for (i=0; i<N; i++) { 7719 PackageParser.Permission p = pkg.permissions.get(i); 7720 7721 // Assume by default that we did not install this permission into the system. 7722 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7723 7724 // Now that permission groups have a special meaning, we ignore permission 7725 // groups for legacy apps to prevent unexpected behavior. In particular, 7726 // permissions for one app being granted to someone just becuase they happen 7727 // to be in a group defined by another app (before this had no implications). 7728 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7729 p.group = mPermissionGroups.get(p.info.group); 7730 // Warn for a permission in an unknown group. 7731 if (p.info.group != null && p.group == null) { 7732 Slog.w(TAG, "Permission " + p.info.name + " from package " 7733 + p.info.packageName + " in an unknown group " + p.info.group); 7734 } 7735 } 7736 7737 ArrayMap<String, BasePermission> permissionMap = 7738 p.tree ? mSettings.mPermissionTrees 7739 : mSettings.mPermissions; 7740 BasePermission bp = permissionMap.get(p.info.name); 7741 7742 // Allow system apps to redefine non-system permissions 7743 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7744 final boolean currentOwnerIsSystem = (bp.perm != null 7745 && isSystemApp(bp.perm.owner)); 7746 if (isSystemApp(p.owner)) { 7747 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7748 // It's a built-in permission and no owner, take ownership now 7749 bp.packageSetting = pkgSetting; 7750 bp.perm = p; 7751 bp.uid = pkg.applicationInfo.uid; 7752 bp.sourcePackage = p.info.packageName; 7753 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7754 } else if (!currentOwnerIsSystem) { 7755 String msg = "New decl " + p.owner + " of permission " 7756 + p.info.name + " is system; overriding " + bp.sourcePackage; 7757 reportSettingsProblem(Log.WARN, msg); 7758 bp = null; 7759 } 7760 } 7761 } 7762 7763 if (bp == null) { 7764 bp = new BasePermission(p.info.name, p.info.packageName, 7765 BasePermission.TYPE_NORMAL); 7766 permissionMap.put(p.info.name, bp); 7767 } 7768 7769 if (bp.perm == null) { 7770 if (bp.sourcePackage == null 7771 || bp.sourcePackage.equals(p.info.packageName)) { 7772 BasePermission tree = findPermissionTreeLP(p.info.name); 7773 if (tree == null 7774 || tree.sourcePackage.equals(p.info.packageName)) { 7775 bp.packageSetting = pkgSetting; 7776 bp.perm = p; 7777 bp.uid = pkg.applicationInfo.uid; 7778 bp.sourcePackage = p.info.packageName; 7779 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7780 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7781 if (r == null) { 7782 r = new StringBuilder(256); 7783 } else { 7784 r.append(' '); 7785 } 7786 r.append(p.info.name); 7787 } 7788 } else { 7789 Slog.w(TAG, "Permission " + p.info.name + " from package " 7790 + p.info.packageName + " ignored: base tree " 7791 + tree.name + " is from package " 7792 + tree.sourcePackage); 7793 } 7794 } else { 7795 Slog.w(TAG, "Permission " + p.info.name + " from package " 7796 + p.info.packageName + " ignored: original from " 7797 + bp.sourcePackage); 7798 } 7799 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7800 if (r == null) { 7801 r = new StringBuilder(256); 7802 } else { 7803 r.append(' '); 7804 } 7805 r.append("DUP:"); 7806 r.append(p.info.name); 7807 } 7808 if (bp.perm == p) { 7809 bp.protectionLevel = p.info.protectionLevel; 7810 } 7811 } 7812 7813 if (r != null) { 7814 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7815 } 7816 7817 N = pkg.instrumentation.size(); 7818 r = null; 7819 for (i=0; i<N; i++) { 7820 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7821 a.info.packageName = pkg.applicationInfo.packageName; 7822 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7823 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7824 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7825 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7826 a.info.dataDir = pkg.applicationInfo.dataDir; 7827 a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir; 7828 a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir; 7829 7830 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7831 // need other information about the application, like the ABI and what not ? 7832 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7833 mInstrumentation.put(a.getComponentName(), a); 7834 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7835 if (r == null) { 7836 r = new StringBuilder(256); 7837 } else { 7838 r.append(' '); 7839 } 7840 r.append(a.info.name); 7841 } 7842 } 7843 if (r != null) { 7844 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7845 } 7846 7847 if (pkg.protectedBroadcasts != null) { 7848 N = pkg.protectedBroadcasts.size(); 7849 for (i=0; i<N; i++) { 7850 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7851 } 7852 } 7853 7854 pkgSetting.setTimeStamp(scanFileTime); 7855 7856 // Create idmap files for pairs of (packages, overlay packages). 7857 // Note: "android", ie framework-res.apk, is handled by native layers. 7858 if (pkg.mOverlayTarget != null) { 7859 // This is an overlay package. 7860 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7861 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7862 mOverlays.put(pkg.mOverlayTarget, 7863 new ArrayMap<String, PackageParser.Package>()); 7864 } 7865 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7866 map.put(pkg.packageName, pkg); 7867 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7868 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7869 createIdmapFailed = true; 7870 } 7871 } 7872 } else if (mOverlays.containsKey(pkg.packageName) && 7873 !pkg.packageName.equals("android")) { 7874 // This is a regular package, with one or more known overlay packages. 7875 createIdmapsForPackageLI(pkg); 7876 } 7877 } 7878 7879 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7880 7881 if (createIdmapFailed) { 7882 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7883 "scanPackageLI failed to createIdmap"); 7884 } 7885 return pkg; 7886 } 7887 7888 /** 7889 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7890 * is derived purely on the basis of the contents of {@code scanFile} and 7891 * {@code cpuAbiOverride}. 7892 * 7893 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7894 */ 7895 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7896 String cpuAbiOverride, boolean extractLibs) 7897 throws PackageManagerException { 7898 // TODO: We can probably be smarter about this stuff. For installed apps, 7899 // we can calculate this information at install time once and for all. For 7900 // system apps, we can probably assume that this information doesn't change 7901 // after the first boot scan. As things stand, we do lots of unnecessary work. 7902 7903 // Give ourselves some initial paths; we'll come back for another 7904 // pass once we've determined ABI below. 7905 setNativeLibraryPaths(pkg); 7906 7907 // We would never need to extract libs for forward-locked and external packages, 7908 // since the container service will do it for us. We shouldn't attempt to 7909 // extract libs from system app when it was not updated. 7910 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 7911 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 7912 extractLibs = false; 7913 } 7914 7915 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7916 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7917 7918 NativeLibraryHelper.Handle handle = null; 7919 try { 7920 handle = NativeLibraryHelper.Handle.create(pkg); 7921 // TODO(multiArch): This can be null for apps that didn't go through the 7922 // usual installation process. We can calculate it again, like we 7923 // do during install time. 7924 // 7925 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7926 // unnecessary. 7927 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7928 7929 // Null out the abis so that they can be recalculated. 7930 pkg.applicationInfo.primaryCpuAbi = null; 7931 pkg.applicationInfo.secondaryCpuAbi = null; 7932 if (isMultiArch(pkg.applicationInfo)) { 7933 // Warn if we've set an abiOverride for multi-lib packages.. 7934 // By definition, we need to copy both 32 and 64 bit libraries for 7935 // such packages. 7936 if (pkg.cpuAbiOverride != null 7937 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7938 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7939 } 7940 7941 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7942 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7943 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7944 if (extractLibs) { 7945 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7946 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7947 useIsaSpecificSubdirs); 7948 } else { 7949 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7950 } 7951 } 7952 7953 maybeThrowExceptionForMultiArchCopy( 7954 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7955 7956 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7957 if (extractLibs) { 7958 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7959 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7960 useIsaSpecificSubdirs); 7961 } else { 7962 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7963 } 7964 } 7965 7966 maybeThrowExceptionForMultiArchCopy( 7967 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7968 7969 if (abi64 >= 0) { 7970 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7971 } 7972 7973 if (abi32 >= 0) { 7974 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7975 if (abi64 >= 0) { 7976 pkg.applicationInfo.secondaryCpuAbi = abi; 7977 } else { 7978 pkg.applicationInfo.primaryCpuAbi = abi; 7979 } 7980 } 7981 } else { 7982 String[] abiList = (cpuAbiOverride != null) ? 7983 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7984 7985 // Enable gross and lame hacks for apps that are built with old 7986 // SDK tools. We must scan their APKs for renderscript bitcode and 7987 // not launch them if it's present. Don't bother checking on devices 7988 // that don't have 64 bit support. 7989 boolean needsRenderScriptOverride = false; 7990 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7991 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7992 abiList = Build.SUPPORTED_32_BIT_ABIS; 7993 needsRenderScriptOverride = true; 7994 } 7995 7996 final int copyRet; 7997 if (extractLibs) { 7998 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7999 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8000 } else { 8001 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8002 } 8003 8004 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8005 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8006 "Error unpackaging native libs for app, errorCode=" + copyRet); 8007 } 8008 8009 if (copyRet >= 0) { 8010 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8011 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8012 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8013 } else if (needsRenderScriptOverride) { 8014 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8015 } 8016 } 8017 } catch (IOException ioe) { 8018 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8019 } finally { 8020 IoUtils.closeQuietly(handle); 8021 } 8022 8023 // Now that we've calculated the ABIs and determined if it's an internal app, 8024 // we will go ahead and populate the nativeLibraryPath. 8025 setNativeLibraryPaths(pkg); 8026 } 8027 8028 /** 8029 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8030 * i.e, so that all packages can be run inside a single process if required. 8031 * 8032 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8033 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8034 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8035 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8036 * updating a package that belongs to a shared user. 8037 * 8038 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8039 * adds unnecessary complexity. 8040 */ 8041 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8042 PackageParser.Package scannedPackage, boolean bootComplete) { 8043 String requiredInstructionSet = null; 8044 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8045 requiredInstructionSet = VMRuntime.getInstructionSet( 8046 scannedPackage.applicationInfo.primaryCpuAbi); 8047 } 8048 8049 PackageSetting requirer = null; 8050 for (PackageSetting ps : packagesForUser) { 8051 // If packagesForUser contains scannedPackage, we skip it. This will happen 8052 // when scannedPackage is an update of an existing package. Without this check, 8053 // we will never be able to change the ABI of any package belonging to a shared 8054 // user, even if it's compatible with other packages. 8055 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8056 if (ps.primaryCpuAbiString == null) { 8057 continue; 8058 } 8059 8060 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8061 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8062 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8063 // this but there's not much we can do. 8064 String errorMessage = "Instruction set mismatch, " 8065 + ((requirer == null) ? "[caller]" : requirer) 8066 + " requires " + requiredInstructionSet + " whereas " + ps 8067 + " requires " + instructionSet; 8068 Slog.w(TAG, errorMessage); 8069 } 8070 8071 if (requiredInstructionSet == null) { 8072 requiredInstructionSet = instructionSet; 8073 requirer = ps; 8074 } 8075 } 8076 } 8077 8078 if (requiredInstructionSet != null) { 8079 String adjustedAbi; 8080 if (requirer != null) { 8081 // requirer != null implies that either scannedPackage was null or that scannedPackage 8082 // did not require an ABI, in which case we have to adjust scannedPackage to match 8083 // the ABI of the set (which is the same as requirer's ABI) 8084 adjustedAbi = requirer.primaryCpuAbiString; 8085 if (scannedPackage != null) { 8086 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8087 } 8088 } else { 8089 // requirer == null implies that we're updating all ABIs in the set to 8090 // match scannedPackage. 8091 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8092 } 8093 8094 for (PackageSetting ps : packagesForUser) { 8095 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8096 if (ps.primaryCpuAbiString != null) { 8097 continue; 8098 } 8099 8100 ps.primaryCpuAbiString = adjustedAbi; 8101 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8102 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8103 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8104 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8105 + " (requirer=" 8106 + (requirer == null ? "null" : requirer.pkg.packageName) 8107 + ", scannedPackage=" 8108 + (scannedPackage != null ? scannedPackage.packageName : "null") 8109 + ")"); 8110 try { 8111 mInstaller.rmdex(ps.codePathString, 8112 getDexCodeInstructionSet(getPreferredInstructionSet())); 8113 } catch (InstallerException ignored) { 8114 } 8115 } 8116 } 8117 } 8118 } 8119 } 8120 8121 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8122 synchronized (mPackages) { 8123 mResolverReplaced = true; 8124 // Set up information for custom user intent resolution activity. 8125 mResolveActivity.applicationInfo = pkg.applicationInfo; 8126 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8127 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8128 mResolveActivity.processName = pkg.applicationInfo.packageName; 8129 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8130 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8131 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8132 mResolveActivity.theme = 0; 8133 mResolveActivity.exported = true; 8134 mResolveActivity.enabled = true; 8135 mResolveInfo.activityInfo = mResolveActivity; 8136 mResolveInfo.priority = 0; 8137 mResolveInfo.preferredOrder = 0; 8138 mResolveInfo.match = 0; 8139 mResolveComponentName = mCustomResolverComponentName; 8140 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8141 mResolveComponentName); 8142 } 8143 } 8144 8145 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8146 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8147 8148 // Set up information for ephemeral installer activity 8149 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8150 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8151 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8152 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8153 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8154 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8155 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8156 mEphemeralInstallerActivity.theme = 0; 8157 mEphemeralInstallerActivity.exported = true; 8158 mEphemeralInstallerActivity.enabled = true; 8159 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8160 mEphemeralInstallerInfo.priority = 0; 8161 mEphemeralInstallerInfo.preferredOrder = 0; 8162 mEphemeralInstallerInfo.match = 0; 8163 8164 if (DEBUG_EPHEMERAL) { 8165 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8166 } 8167 } 8168 8169 private static String calculateBundledApkRoot(final String codePathString) { 8170 final File codePath = new File(codePathString); 8171 final File codeRoot; 8172 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8173 codeRoot = Environment.getRootDirectory(); 8174 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8175 codeRoot = Environment.getOemDirectory(); 8176 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8177 codeRoot = Environment.getVendorDirectory(); 8178 } else { 8179 // Unrecognized code path; take its top real segment as the apk root: 8180 // e.g. /something/app/blah.apk => /something 8181 try { 8182 File f = codePath.getCanonicalFile(); 8183 File parent = f.getParentFile(); // non-null because codePath is a file 8184 File tmp; 8185 while ((tmp = parent.getParentFile()) != null) { 8186 f = parent; 8187 parent = tmp; 8188 } 8189 codeRoot = f; 8190 Slog.w(TAG, "Unrecognized code path " 8191 + codePath + " - using " + codeRoot); 8192 } catch (IOException e) { 8193 // Can't canonicalize the code path -- shenanigans? 8194 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8195 return Environment.getRootDirectory().getPath(); 8196 } 8197 } 8198 return codeRoot.getPath(); 8199 } 8200 8201 /** 8202 * Derive and set the location of native libraries for the given package, 8203 * which varies depending on where and how the package was installed. 8204 */ 8205 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8206 final ApplicationInfo info = pkg.applicationInfo; 8207 final String codePath = pkg.codePath; 8208 final File codeFile = new File(codePath); 8209 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8210 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8211 8212 info.nativeLibraryRootDir = null; 8213 info.nativeLibraryRootRequiresIsa = false; 8214 info.nativeLibraryDir = null; 8215 info.secondaryNativeLibraryDir = null; 8216 8217 if (isApkFile(codeFile)) { 8218 // Monolithic install 8219 if (bundledApp) { 8220 // If "/system/lib64/apkname" exists, assume that is the per-package 8221 // native library directory to use; otherwise use "/system/lib/apkname". 8222 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8223 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8224 getPrimaryInstructionSet(info)); 8225 8226 // This is a bundled system app so choose the path based on the ABI. 8227 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8228 // is just the default path. 8229 final String apkName = deriveCodePathName(codePath); 8230 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8231 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8232 apkName).getAbsolutePath(); 8233 8234 if (info.secondaryCpuAbi != null) { 8235 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8236 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8237 secondaryLibDir, apkName).getAbsolutePath(); 8238 } 8239 } else if (asecApp) { 8240 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8241 .getAbsolutePath(); 8242 } else { 8243 final String apkName = deriveCodePathName(codePath); 8244 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8245 .getAbsolutePath(); 8246 } 8247 8248 info.nativeLibraryRootRequiresIsa = false; 8249 info.nativeLibraryDir = info.nativeLibraryRootDir; 8250 } else { 8251 // Cluster install 8252 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8253 info.nativeLibraryRootRequiresIsa = true; 8254 8255 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8256 getPrimaryInstructionSet(info)).getAbsolutePath(); 8257 8258 if (info.secondaryCpuAbi != null) { 8259 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8260 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8261 } 8262 } 8263 } 8264 8265 /** 8266 * Calculate the abis and roots for a bundled app. These can uniquely 8267 * be determined from the contents of the system partition, i.e whether 8268 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8269 * of this information, and instead assume that the system was built 8270 * sensibly. 8271 */ 8272 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8273 PackageSetting pkgSetting) { 8274 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8275 8276 // If "/system/lib64/apkname" exists, assume that is the per-package 8277 // native library directory to use; otherwise use "/system/lib/apkname". 8278 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8279 setBundledAppAbi(pkg, apkRoot, apkName); 8280 // pkgSetting might be null during rescan following uninstall of updates 8281 // to a bundled app, so accommodate that possibility. The settings in 8282 // that case will be established later from the parsed package. 8283 // 8284 // If the settings aren't null, sync them up with what we've just derived. 8285 // note that apkRoot isn't stored in the package settings. 8286 if (pkgSetting != null) { 8287 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8288 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8289 } 8290 } 8291 8292 /** 8293 * Deduces the ABI of a bundled app and sets the relevant fields on the 8294 * parsed pkg object. 8295 * 8296 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8297 * under which system libraries are installed. 8298 * @param apkName the name of the installed package. 8299 */ 8300 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8301 final File codeFile = new File(pkg.codePath); 8302 8303 final boolean has64BitLibs; 8304 final boolean has32BitLibs; 8305 if (isApkFile(codeFile)) { 8306 // Monolithic install 8307 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8308 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8309 } else { 8310 // Cluster install 8311 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8312 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8313 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8314 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8315 has64BitLibs = (new File(rootDir, isa)).exists(); 8316 } else { 8317 has64BitLibs = false; 8318 } 8319 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8320 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8321 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8322 has32BitLibs = (new File(rootDir, isa)).exists(); 8323 } else { 8324 has32BitLibs = false; 8325 } 8326 } 8327 8328 if (has64BitLibs && !has32BitLibs) { 8329 // The package has 64 bit libs, but not 32 bit libs. Its primary 8330 // ABI should be 64 bit. We can safely assume here that the bundled 8331 // native libraries correspond to the most preferred ABI in the list. 8332 8333 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8334 pkg.applicationInfo.secondaryCpuAbi = null; 8335 } else if (has32BitLibs && !has64BitLibs) { 8336 // The package has 32 bit libs but not 64 bit libs. Its primary 8337 // ABI should be 32 bit. 8338 8339 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8340 pkg.applicationInfo.secondaryCpuAbi = null; 8341 } else if (has32BitLibs && has64BitLibs) { 8342 // The application has both 64 and 32 bit bundled libraries. We check 8343 // here that the app declares multiArch support, and warn if it doesn't. 8344 // 8345 // We will be lenient here and record both ABIs. The primary will be the 8346 // ABI that's higher on the list, i.e, a device that's configured to prefer 8347 // 64 bit apps will see a 64 bit primary ABI, 8348 8349 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8350 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 8351 } 8352 8353 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8354 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8355 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8356 } else { 8357 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8358 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8359 } 8360 } else { 8361 pkg.applicationInfo.primaryCpuAbi = null; 8362 pkg.applicationInfo.secondaryCpuAbi = null; 8363 } 8364 } 8365 8366 private void killApplication(String pkgName, int appId, String reason) { 8367 // Request the ActivityManager to kill the process(only for existing packages) 8368 // so that we do not end up in a confused state while the user is still using the older 8369 // version of the application while the new one gets installed. 8370 IActivityManager am = ActivityManagerNative.getDefault(); 8371 if (am != null) { 8372 try { 8373 am.killApplicationWithAppId(pkgName, appId, reason); 8374 } catch (RemoteException e) { 8375 } 8376 } 8377 } 8378 8379 void removePackageLI(PackageSetting ps, boolean chatty) { 8380 if (DEBUG_INSTALL) { 8381 if (chatty) 8382 Log.d(TAG, "Removing package " + ps.name); 8383 } 8384 8385 // writer 8386 synchronized (mPackages) { 8387 mPackages.remove(ps.name); 8388 final PackageParser.Package pkg = ps.pkg; 8389 if (pkg != null) { 8390 cleanPackageDataStructuresLILPw(pkg, chatty); 8391 } 8392 } 8393 } 8394 8395 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8396 if (DEBUG_INSTALL) { 8397 if (chatty) 8398 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8399 } 8400 8401 // writer 8402 synchronized (mPackages) { 8403 mPackages.remove(pkg.applicationInfo.packageName); 8404 cleanPackageDataStructuresLILPw(pkg, chatty); 8405 } 8406 } 8407 8408 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8409 int N = pkg.providers.size(); 8410 StringBuilder r = null; 8411 int i; 8412 for (i=0; i<N; i++) { 8413 PackageParser.Provider p = pkg.providers.get(i); 8414 mProviders.removeProvider(p); 8415 if (p.info.authority == null) { 8416 8417 /* There was another ContentProvider with this authority when 8418 * this app was installed so this authority is null, 8419 * Ignore it as we don't have to unregister the provider. 8420 */ 8421 continue; 8422 } 8423 String names[] = p.info.authority.split(";"); 8424 for (int j = 0; j < names.length; j++) { 8425 if (mProvidersByAuthority.get(names[j]) == p) { 8426 mProvidersByAuthority.remove(names[j]); 8427 if (DEBUG_REMOVE) { 8428 if (chatty) 8429 Log.d(TAG, "Unregistered content provider: " + names[j] 8430 + ", className = " + p.info.name + ", isSyncable = " 8431 + p.info.isSyncable); 8432 } 8433 } 8434 } 8435 if (DEBUG_REMOVE && chatty) { 8436 if (r == null) { 8437 r = new StringBuilder(256); 8438 } else { 8439 r.append(' '); 8440 } 8441 r.append(p.info.name); 8442 } 8443 } 8444 if (r != null) { 8445 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8446 } 8447 8448 N = pkg.services.size(); 8449 r = null; 8450 for (i=0; i<N; i++) { 8451 PackageParser.Service s = pkg.services.get(i); 8452 mServices.removeService(s); 8453 if (chatty) { 8454 if (r == null) { 8455 r = new StringBuilder(256); 8456 } else { 8457 r.append(' '); 8458 } 8459 r.append(s.info.name); 8460 } 8461 } 8462 if (r != null) { 8463 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8464 } 8465 8466 N = pkg.receivers.size(); 8467 r = null; 8468 for (i=0; i<N; i++) { 8469 PackageParser.Activity a = pkg.receivers.get(i); 8470 mReceivers.removeActivity(a, "receiver"); 8471 if (DEBUG_REMOVE && chatty) { 8472 if (r == null) { 8473 r = new StringBuilder(256); 8474 } else { 8475 r.append(' '); 8476 } 8477 r.append(a.info.name); 8478 } 8479 } 8480 if (r != null) { 8481 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8482 } 8483 8484 N = pkg.activities.size(); 8485 r = null; 8486 for (i=0; i<N; i++) { 8487 PackageParser.Activity a = pkg.activities.get(i); 8488 mActivities.removeActivity(a, "activity"); 8489 if (DEBUG_REMOVE && chatty) { 8490 if (r == null) { 8491 r = new StringBuilder(256); 8492 } else { 8493 r.append(' '); 8494 } 8495 r.append(a.info.name); 8496 } 8497 } 8498 if (r != null) { 8499 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8500 } 8501 8502 N = pkg.permissions.size(); 8503 r = null; 8504 for (i=0; i<N; i++) { 8505 PackageParser.Permission p = pkg.permissions.get(i); 8506 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8507 if (bp == null) { 8508 bp = mSettings.mPermissionTrees.get(p.info.name); 8509 } 8510 if (bp != null && bp.perm == p) { 8511 bp.perm = null; 8512 if (DEBUG_REMOVE && chatty) { 8513 if (r == null) { 8514 r = new StringBuilder(256); 8515 } else { 8516 r.append(' '); 8517 } 8518 r.append(p.info.name); 8519 } 8520 } 8521 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8522 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 8523 if (appOpPkgs != null) { 8524 appOpPkgs.remove(pkg.packageName); 8525 } 8526 } 8527 } 8528 if (r != null) { 8529 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8530 } 8531 8532 N = pkg.requestedPermissions.size(); 8533 r = null; 8534 for (i=0; i<N; i++) { 8535 String perm = pkg.requestedPermissions.get(i); 8536 BasePermission bp = mSettings.mPermissions.get(perm); 8537 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8538 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 8539 if (appOpPkgs != null) { 8540 appOpPkgs.remove(pkg.packageName); 8541 if (appOpPkgs.isEmpty()) { 8542 mAppOpPermissionPackages.remove(perm); 8543 } 8544 } 8545 } 8546 } 8547 if (r != null) { 8548 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8549 } 8550 8551 N = pkg.instrumentation.size(); 8552 r = null; 8553 for (i=0; i<N; i++) { 8554 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8555 mInstrumentation.remove(a.getComponentName()); 8556 if (DEBUG_REMOVE && chatty) { 8557 if (r == null) { 8558 r = new StringBuilder(256); 8559 } else { 8560 r.append(' '); 8561 } 8562 r.append(a.info.name); 8563 } 8564 } 8565 if (r != null) { 8566 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8567 } 8568 8569 r = null; 8570 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8571 // Only system apps can hold shared libraries. 8572 if (pkg.libraryNames != null) { 8573 for (i=0; i<pkg.libraryNames.size(); i++) { 8574 String name = pkg.libraryNames.get(i); 8575 SharedLibraryEntry cur = mSharedLibraries.get(name); 8576 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8577 mSharedLibraries.remove(name); 8578 if (DEBUG_REMOVE && chatty) { 8579 if (r == null) { 8580 r = new StringBuilder(256); 8581 } else { 8582 r.append(' '); 8583 } 8584 r.append(name); 8585 } 8586 } 8587 } 8588 } 8589 } 8590 if (r != null) { 8591 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8592 } 8593 } 8594 8595 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8596 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8597 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8598 return true; 8599 } 8600 } 8601 return false; 8602 } 8603 8604 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8605 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8606 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8607 8608 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 8609 int flags) { 8610 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 8611 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 8612 } 8613 8614 private void updatePermissionsLPw(String changingPkg, 8615 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 8616 // Make sure there are no dangling permission trees. 8617 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8618 while (it.hasNext()) { 8619 final BasePermission bp = it.next(); 8620 if (bp.packageSetting == null) { 8621 // We may not yet have parsed the package, so just see if 8622 // we still know about its settings. 8623 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8624 } 8625 if (bp.packageSetting == null) { 8626 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8627 + " from package " + bp.sourcePackage); 8628 it.remove(); 8629 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8630 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8631 Slog.i(TAG, "Removing old permission tree: " + bp.name 8632 + " from package " + bp.sourcePackage); 8633 flags |= UPDATE_PERMISSIONS_ALL; 8634 it.remove(); 8635 } 8636 } 8637 } 8638 8639 // Make sure all dynamic permissions have been assigned to a package, 8640 // and make sure there are no dangling permissions. 8641 it = mSettings.mPermissions.values().iterator(); 8642 while (it.hasNext()) { 8643 final BasePermission bp = it.next(); 8644 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8645 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8646 + bp.name + " pkg=" + bp.sourcePackage 8647 + " info=" + bp.pendingInfo); 8648 if (bp.packageSetting == null && bp.pendingInfo != null) { 8649 final BasePermission tree = findPermissionTreeLP(bp.name); 8650 if (tree != null && tree.perm != null) { 8651 bp.packageSetting = tree.packageSetting; 8652 bp.perm = new PackageParser.Permission(tree.perm.owner, 8653 new PermissionInfo(bp.pendingInfo)); 8654 bp.perm.info.packageName = tree.perm.info.packageName; 8655 bp.perm.info.name = bp.name; 8656 bp.uid = tree.uid; 8657 } 8658 } 8659 } 8660 if (bp.packageSetting == null) { 8661 // We may not yet have parsed the package, so just see if 8662 // we still know about its settings. 8663 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8664 } 8665 if (bp.packageSetting == null) { 8666 Slog.w(TAG, "Removing dangling permission: " + bp.name 8667 + " from package " + bp.sourcePackage); 8668 it.remove(); 8669 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8670 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8671 Slog.i(TAG, "Removing old permission: " + bp.name 8672 + " from package " + bp.sourcePackage); 8673 flags |= UPDATE_PERMISSIONS_ALL; 8674 it.remove(); 8675 } 8676 } 8677 } 8678 8679 // Now update the permissions for all packages, in particular 8680 // replace the granted permissions of the system packages. 8681 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8682 for (PackageParser.Package pkg : mPackages.values()) { 8683 if (pkg != pkgInfo) { 8684 // Only replace for packages on requested volume 8685 final String volumeUuid = getVolumeUuidForPackage(pkg); 8686 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 8687 && Objects.equals(replaceVolumeUuid, volumeUuid); 8688 grantPermissionsLPw(pkg, replace, changingPkg); 8689 } 8690 } 8691 } 8692 8693 if (pkgInfo != null) { 8694 // Only replace for packages on requested volume 8695 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 8696 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 8697 && Objects.equals(replaceVolumeUuid, volumeUuid); 8698 grantPermissionsLPw(pkgInfo, replace, changingPkg); 8699 } 8700 } 8701 8702 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8703 String packageOfInterest) { 8704 // IMPORTANT: There are two types of permissions: install and runtime. 8705 // Install time permissions are granted when the app is installed to 8706 // all device users and users added in the future. Runtime permissions 8707 // are granted at runtime explicitly to specific users. Normal and signature 8708 // protected permissions are install time permissions. Dangerous permissions 8709 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8710 // otherwise they are runtime permissions. This function does not manage 8711 // runtime permissions except for the case an app targeting Lollipop MR1 8712 // being upgraded to target a newer SDK, in which case dangerous permissions 8713 // are transformed from install time to runtime ones. 8714 8715 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8716 if (ps == null) { 8717 return; 8718 } 8719 8720 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 8721 8722 PermissionsState permissionsState = ps.getPermissionsState(); 8723 PermissionsState origPermissions = permissionsState; 8724 8725 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8726 8727 boolean runtimePermissionsRevoked = false; 8728 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8729 8730 boolean changedInstallPermission = false; 8731 8732 if (replace) { 8733 ps.installPermissionsFixed = false; 8734 if (!ps.isSharedUser()) { 8735 origPermissions = new PermissionsState(permissionsState); 8736 permissionsState.reset(); 8737 } else { 8738 // We need to know only about runtime permission changes since the 8739 // calling code always writes the install permissions state but 8740 // the runtime ones are written only if changed. The only cases of 8741 // changed runtime permissions here are promotion of an install to 8742 // runtime and revocation of a runtime from a shared user. 8743 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 8744 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 8745 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 8746 runtimePermissionsRevoked = true; 8747 } 8748 } 8749 } 8750 8751 permissionsState.setGlobalGids(mGlobalGids); 8752 8753 final int N = pkg.requestedPermissions.size(); 8754 for (int i=0; i<N; i++) { 8755 final String name = pkg.requestedPermissions.get(i); 8756 final BasePermission bp = mSettings.mPermissions.get(name); 8757 8758 if (DEBUG_INSTALL) { 8759 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8760 } 8761 8762 if (bp == null || bp.packageSetting == null) { 8763 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8764 Slog.w(TAG, "Unknown permission " + name 8765 + " in package " + pkg.packageName); 8766 } 8767 continue; 8768 } 8769 8770 final String perm = bp.name; 8771 boolean allowedSig = false; 8772 int grant = GRANT_DENIED; 8773 8774 // Keep track of app op permissions. 8775 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8776 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8777 if (pkgs == null) { 8778 pkgs = new ArraySet<>(); 8779 mAppOpPermissionPackages.put(bp.name, pkgs); 8780 } 8781 pkgs.add(pkg.packageName); 8782 } 8783 8784 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8785 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 8786 >= Build.VERSION_CODES.M; 8787 switch (level) { 8788 case PermissionInfo.PROTECTION_NORMAL: { 8789 // For all apps normal permissions are install time ones. 8790 grant = GRANT_INSTALL; 8791 } break; 8792 8793 case PermissionInfo.PROTECTION_DANGEROUS: { 8794 // If a permission review is required for legacy apps we represent 8795 // their permissions as always granted runtime ones since we need 8796 // to keep the review required permission flag per user while an 8797 // install permission's state is shared across all users. 8798 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 8799 // For legacy apps dangerous permissions are install time ones. 8800 grant = GRANT_INSTALL; 8801 } else if (origPermissions.hasInstallPermission(bp.name)) { 8802 // For legacy apps that became modern, install becomes runtime. 8803 grant = GRANT_UPGRADE; 8804 } else if (mPromoteSystemApps 8805 && isSystemApp(ps) 8806 && mExistingSystemPackages.contains(ps.name)) { 8807 // For legacy system apps, install becomes runtime. 8808 // We cannot check hasInstallPermission() for system apps since those 8809 // permissions were granted implicitly and not persisted pre-M. 8810 grant = GRANT_UPGRADE; 8811 } else { 8812 // For modern apps keep runtime permissions unchanged. 8813 grant = GRANT_RUNTIME; 8814 } 8815 } break; 8816 8817 case PermissionInfo.PROTECTION_SIGNATURE: { 8818 // For all apps signature permissions are install time ones. 8819 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8820 if (allowedSig) { 8821 grant = GRANT_INSTALL; 8822 } 8823 } break; 8824 } 8825 8826 if (DEBUG_INSTALL) { 8827 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8828 } 8829 8830 if (grant != GRANT_DENIED) { 8831 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8832 // If this is an existing, non-system package, then 8833 // we can't add any new permissions to it. 8834 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8835 // Except... if this is a permission that was added 8836 // to the platform (note: need to only do this when 8837 // updating the platform). 8838 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8839 grant = GRANT_DENIED; 8840 } 8841 } 8842 } 8843 8844 switch (grant) { 8845 case GRANT_INSTALL: { 8846 // Revoke this as runtime permission to handle the case of 8847 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 8848 for (int userId : UserManagerService.getInstance().getUserIds()) { 8849 if (origPermissions.getRuntimePermissionState( 8850 bp.name, userId) != null) { 8851 // Revoke the runtime permission and clear the flags. 8852 origPermissions.revokeRuntimePermission(bp, userId); 8853 origPermissions.updatePermissionFlags(bp, userId, 8854 PackageManager.MASK_PERMISSION_FLAGS, 0); 8855 // If we revoked a permission permission, we have to write. 8856 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8857 changedRuntimePermissionUserIds, userId); 8858 } 8859 } 8860 // Grant an install permission. 8861 if (permissionsState.grantInstallPermission(bp) != 8862 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8863 changedInstallPermission = true; 8864 } 8865 } break; 8866 8867 case GRANT_RUNTIME: { 8868 // Grant previously granted runtime permissions. 8869 for (int userId : UserManagerService.getInstance().getUserIds()) { 8870 PermissionState permissionState = origPermissions 8871 .getRuntimePermissionState(bp.name, userId); 8872 int flags = permissionState != null 8873 ? permissionState.getFlags() : 0; 8874 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8875 if (permissionsState.grantRuntimePermission(bp, userId) == 8876 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8877 // If we cannot put the permission as it was, we have to write. 8878 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8879 changedRuntimePermissionUserIds, userId); 8880 } 8881 // If the app supports runtime permissions no need for a review. 8882 if (Build.PERMISSIONS_REVIEW_REQUIRED 8883 && appSupportsRuntimePermissions 8884 && (flags & PackageManager 8885 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 8886 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 8887 // Since we changed the flags, we have to write. 8888 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8889 changedRuntimePermissionUserIds, userId); 8890 } 8891 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 8892 && !appSupportsRuntimePermissions) { 8893 // For legacy apps that need a permission review, every new 8894 // runtime permission is granted but it is pending a review. 8895 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 8896 permissionsState.grantRuntimePermission(bp, userId); 8897 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 8898 // We changed the permission and flags, hence have to write. 8899 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8900 changedRuntimePermissionUserIds, userId); 8901 } 8902 } 8903 // Propagate the permission flags. 8904 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8905 } 8906 } break; 8907 8908 case GRANT_UPGRADE: { 8909 // Grant runtime permissions for a previously held install permission. 8910 PermissionState permissionState = origPermissions 8911 .getInstallPermissionState(bp.name); 8912 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8913 8914 if (origPermissions.revokeInstallPermission(bp) 8915 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8916 // We will be transferring the permission flags, so clear them. 8917 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8918 PackageManager.MASK_PERMISSION_FLAGS, 0); 8919 changedInstallPermission = true; 8920 } 8921 8922 // If the permission is not to be promoted to runtime we ignore it and 8923 // also its other flags as they are not applicable to install permissions. 8924 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8925 for (int userId : currentUserIds) { 8926 if (permissionsState.grantRuntimePermission(bp, userId) != 8927 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8928 // Transfer the permission flags. 8929 permissionsState.updatePermissionFlags(bp, userId, 8930 flags, flags); 8931 // If we granted the permission, we have to write. 8932 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8933 changedRuntimePermissionUserIds, userId); 8934 } 8935 } 8936 } 8937 } break; 8938 8939 default: { 8940 if (packageOfInterest == null 8941 || packageOfInterest.equals(pkg.packageName)) { 8942 Slog.w(TAG, "Not granting permission " + perm 8943 + " to package " + pkg.packageName 8944 + " because it was previously installed without"); 8945 } 8946 } break; 8947 } 8948 } else { 8949 if (permissionsState.revokeInstallPermission(bp) != 8950 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8951 // Also drop the permission flags. 8952 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8953 PackageManager.MASK_PERMISSION_FLAGS, 0); 8954 changedInstallPermission = true; 8955 Slog.i(TAG, "Un-granting permission " + perm 8956 + " from package " + pkg.packageName 8957 + " (protectionLevel=" + bp.protectionLevel 8958 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8959 + ")"); 8960 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8961 // Don't print warning for app op permissions, since it is fine for them 8962 // not to be granted, there is a UI for the user to decide. 8963 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8964 Slog.w(TAG, "Not granting permission " + perm 8965 + " to package " + pkg.packageName 8966 + " (protectionLevel=" + bp.protectionLevel 8967 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8968 + ")"); 8969 } 8970 } 8971 } 8972 } 8973 8974 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8975 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8976 // This is the first that we have heard about this package, so the 8977 // permissions we have now selected are fixed until explicitly 8978 // changed. 8979 ps.installPermissionsFixed = true; 8980 } 8981 8982 // Persist the runtime permissions state for users with changes. If permissions 8983 // were revoked because no app in the shared user declares them we have to 8984 // write synchronously to avoid losing runtime permissions state. 8985 for (int userId : changedRuntimePermissionUserIds) { 8986 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 8987 } 8988 8989 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8990 } 8991 8992 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8993 boolean allowed = false; 8994 final int NP = PackageParser.NEW_PERMISSIONS.length; 8995 for (int ip=0; ip<NP; ip++) { 8996 final PackageParser.NewPermissionInfo npi 8997 = PackageParser.NEW_PERMISSIONS[ip]; 8998 if (npi.name.equals(perm) 8999 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9000 allowed = true; 9001 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9002 + pkg.packageName); 9003 break; 9004 } 9005 } 9006 return allowed; 9007 } 9008 9009 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9010 BasePermission bp, PermissionsState origPermissions) { 9011 boolean allowed; 9012 allowed = (compareSignatures( 9013 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9014 == PackageManager.SIGNATURE_MATCH) 9015 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9016 == PackageManager.SIGNATURE_MATCH); 9017 if (!allowed && (bp.protectionLevel 9018 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9019 if (isSystemApp(pkg)) { 9020 // For updated system applications, a system permission 9021 // is granted only if it had been defined by the original application. 9022 if (pkg.isUpdatedSystemApp()) { 9023 final PackageSetting sysPs = mSettings 9024 .getDisabledSystemPkgLPr(pkg.packageName); 9025 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 9026 // If the original was granted this permission, we take 9027 // that grant decision as read and propagate it to the 9028 // update. 9029 if (sysPs.isPrivileged()) { 9030 allowed = true; 9031 } 9032 } else { 9033 // The system apk may have been updated with an older 9034 // version of the one on the data partition, but which 9035 // granted a new system permission that it didn't have 9036 // before. In this case we do want to allow the app to 9037 // now get the new permission if the ancestral apk is 9038 // privileged to get it. 9039 if (sysPs.pkg != null && sysPs.isPrivileged()) { 9040 for (int j=0; 9041 j<sysPs.pkg.requestedPermissions.size(); j++) { 9042 if (perm.equals( 9043 sysPs.pkg.requestedPermissions.get(j))) { 9044 allowed = true; 9045 break; 9046 } 9047 } 9048 } 9049 } 9050 } else { 9051 allowed = isPrivilegedApp(pkg); 9052 } 9053 } 9054 } 9055 if (!allowed) { 9056 if (!allowed && (bp.protectionLevel 9057 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9058 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9059 // If this was a previously normal/dangerous permission that got moved 9060 // to a system permission as part of the runtime permission redesign, then 9061 // we still want to blindly grant it to old apps. 9062 allowed = true; 9063 } 9064 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9065 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9066 // If this permission is to be granted to the system installer and 9067 // this app is an installer, then it gets the permission. 9068 allowed = true; 9069 } 9070 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9071 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9072 // If this permission is to be granted to the system verifier and 9073 // this app is a verifier, then it gets the permission. 9074 allowed = true; 9075 } 9076 if (!allowed && (bp.protectionLevel 9077 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9078 && isSystemApp(pkg)) { 9079 // Any pre-installed system app is allowed to get this permission. 9080 allowed = true; 9081 } 9082 if (!allowed && (bp.protectionLevel 9083 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9084 // For development permissions, a development permission 9085 // is granted only if it was already granted. 9086 allowed = origPermissions.hasInstallPermission(perm); 9087 } 9088 } 9089 return allowed; 9090 } 9091 9092 final class ActivityIntentResolver 9093 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9094 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9095 boolean defaultOnly, int userId) { 9096 if (!sUserManager.exists(userId)) return null; 9097 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9098 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9099 } 9100 9101 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9102 int userId) { 9103 if (!sUserManager.exists(userId)) return null; 9104 mFlags = flags; 9105 return super.queryIntent(intent, resolvedType, 9106 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9107 } 9108 9109 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9110 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9111 if (!sUserManager.exists(userId)) return null; 9112 if (packageActivities == null) { 9113 return null; 9114 } 9115 mFlags = flags; 9116 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9117 final int N = packageActivities.size(); 9118 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9119 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9120 9121 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9122 for (int i = 0; i < N; ++i) { 9123 intentFilters = packageActivities.get(i).intents; 9124 if (intentFilters != null && intentFilters.size() > 0) { 9125 PackageParser.ActivityIntentInfo[] array = 9126 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9127 intentFilters.toArray(array); 9128 listCut.add(array); 9129 } 9130 } 9131 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9132 } 9133 9134 public final void addActivity(PackageParser.Activity a, String type) { 9135 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 9136 mActivities.put(a.getComponentName(), a); 9137 if (DEBUG_SHOW_INFO) 9138 Log.v( 9139 TAG, " " + type + " " + 9140 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 9141 if (DEBUG_SHOW_INFO) 9142 Log.v(TAG, " Class=" + a.info.name); 9143 final int NI = a.intents.size(); 9144 for (int j=0; j<NI; j++) { 9145 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9146 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 9147 intent.setPriority(0); 9148 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 9149 + a.className + " with priority > 0, forcing to 0"); 9150 } 9151 if (DEBUG_SHOW_INFO) { 9152 Log.v(TAG, " IntentFilter:"); 9153 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9154 } 9155 if (!intent.debugCheck()) { 9156 Log.w(TAG, "==> For Activity " + a.info.name); 9157 } 9158 addFilter(intent); 9159 } 9160 } 9161 9162 public final void removeActivity(PackageParser.Activity a, String type) { 9163 mActivities.remove(a.getComponentName()); 9164 if (DEBUG_SHOW_INFO) { 9165 Log.v(TAG, " " + type + " " 9166 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 9167 : a.info.name) + ":"); 9168 Log.v(TAG, " Class=" + a.info.name); 9169 } 9170 final int NI = a.intents.size(); 9171 for (int j=0; j<NI; j++) { 9172 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9173 if (DEBUG_SHOW_INFO) { 9174 Log.v(TAG, " IntentFilter:"); 9175 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9176 } 9177 removeFilter(intent); 9178 } 9179 } 9180 9181 @Override 9182 protected boolean allowFilterResult( 9183 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 9184 ActivityInfo filterAi = filter.activity.info; 9185 for (int i=dest.size()-1; i>=0; i--) { 9186 ActivityInfo destAi = dest.get(i).activityInfo; 9187 if (destAi.name == filterAi.name 9188 && destAi.packageName == filterAi.packageName) { 9189 return false; 9190 } 9191 } 9192 return true; 9193 } 9194 9195 @Override 9196 protected ActivityIntentInfo[] newArray(int size) { 9197 return new ActivityIntentInfo[size]; 9198 } 9199 9200 @Override 9201 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 9202 if (!sUserManager.exists(userId)) return true; 9203 PackageParser.Package p = filter.activity.owner; 9204 if (p != null) { 9205 PackageSetting ps = (PackageSetting)p.mExtras; 9206 if (ps != null) { 9207 // System apps are never considered stopped for purposes of 9208 // filtering, because there may be no way for the user to 9209 // actually re-launch them. 9210 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 9211 && ps.getStopped(userId); 9212 } 9213 } 9214 return false; 9215 } 9216 9217 @Override 9218 protected boolean isPackageForFilter(String packageName, 9219 PackageParser.ActivityIntentInfo info) { 9220 return packageName.equals(info.activity.owner.packageName); 9221 } 9222 9223 @Override 9224 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 9225 int match, int userId) { 9226 if (!sUserManager.exists(userId)) return null; 9227 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 9228 return null; 9229 } 9230 final PackageParser.Activity activity = info.activity; 9231 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 9232 if (ps == null) { 9233 return null; 9234 } 9235 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 9236 ps.readUserState(userId), userId); 9237 if (ai == null) { 9238 return null; 9239 } 9240 final ResolveInfo res = new ResolveInfo(); 9241 res.activityInfo = ai; 9242 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9243 res.filter = info; 9244 } 9245 if (info != null) { 9246 res.handleAllWebDataURI = info.handleAllWebDataURI(); 9247 } 9248 res.priority = info.getPriority(); 9249 res.preferredOrder = activity.owner.mPreferredOrder; 9250 //System.out.println("Result: " + res.activityInfo.className + 9251 // " = " + res.priority); 9252 res.match = match; 9253 res.isDefault = info.hasDefault; 9254 res.labelRes = info.labelRes; 9255 res.nonLocalizedLabel = info.nonLocalizedLabel; 9256 if (userNeedsBadging(userId)) { 9257 res.noResourceId = true; 9258 } else { 9259 res.icon = info.icon; 9260 } 9261 res.iconResourceId = info.icon; 9262 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9263 return res; 9264 } 9265 9266 @Override 9267 protected void sortResults(List<ResolveInfo> results) { 9268 Collections.sort(results, mResolvePrioritySorter); 9269 } 9270 9271 @Override 9272 protected void dumpFilter(PrintWriter out, String prefix, 9273 PackageParser.ActivityIntentInfo filter) { 9274 out.print(prefix); out.print( 9275 Integer.toHexString(System.identityHashCode(filter.activity))); 9276 out.print(' '); 9277 filter.activity.printComponentShortName(out); 9278 out.print(" filter "); 9279 out.println(Integer.toHexString(System.identityHashCode(filter))); 9280 } 9281 9282 @Override 9283 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9284 return filter.activity; 9285 } 9286 9287 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9288 PackageParser.Activity activity = (PackageParser.Activity)label; 9289 out.print(prefix); out.print( 9290 Integer.toHexString(System.identityHashCode(activity))); 9291 out.print(' '); 9292 activity.printComponentShortName(out); 9293 if (count > 1) { 9294 out.print(" ("); out.print(count); out.print(" filters)"); 9295 } 9296 out.println(); 9297 } 9298 9299// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9300// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9301// final List<ResolveInfo> retList = Lists.newArrayList(); 9302// while (i.hasNext()) { 9303// final ResolveInfo resolveInfo = i.next(); 9304// if (isEnabledLP(resolveInfo.activityInfo)) { 9305// retList.add(resolveInfo); 9306// } 9307// } 9308// return retList; 9309// } 9310 9311 // Keys are String (activity class name), values are Activity. 9312 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9313 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9314 private int mFlags; 9315 } 9316 9317 private final class ServiceIntentResolver 9318 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9319 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9320 boolean defaultOnly, int userId) { 9321 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9322 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9323 } 9324 9325 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9326 int userId) { 9327 if (!sUserManager.exists(userId)) return null; 9328 mFlags = flags; 9329 return super.queryIntent(intent, resolvedType, 9330 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9331 } 9332 9333 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9334 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9335 if (!sUserManager.exists(userId)) return null; 9336 if (packageServices == null) { 9337 return null; 9338 } 9339 mFlags = flags; 9340 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9341 final int N = packageServices.size(); 9342 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9343 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9344 9345 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9346 for (int i = 0; i < N; ++i) { 9347 intentFilters = packageServices.get(i).intents; 9348 if (intentFilters != null && intentFilters.size() > 0) { 9349 PackageParser.ServiceIntentInfo[] array = 9350 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9351 intentFilters.toArray(array); 9352 listCut.add(array); 9353 } 9354 } 9355 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9356 } 9357 9358 public final void addService(PackageParser.Service s) { 9359 mServices.put(s.getComponentName(), s); 9360 if (DEBUG_SHOW_INFO) { 9361 Log.v(TAG, " " 9362 + (s.info.nonLocalizedLabel != null 9363 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9364 Log.v(TAG, " Class=" + s.info.name); 9365 } 9366 final int NI = s.intents.size(); 9367 int j; 9368 for (j=0; j<NI; j++) { 9369 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9370 if (DEBUG_SHOW_INFO) { 9371 Log.v(TAG, " IntentFilter:"); 9372 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9373 } 9374 if (!intent.debugCheck()) { 9375 Log.w(TAG, "==> For Service " + s.info.name); 9376 } 9377 addFilter(intent); 9378 } 9379 } 9380 9381 public final void removeService(PackageParser.Service s) { 9382 mServices.remove(s.getComponentName()); 9383 if (DEBUG_SHOW_INFO) { 9384 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9385 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9386 Log.v(TAG, " Class=" + s.info.name); 9387 } 9388 final int NI = s.intents.size(); 9389 int j; 9390 for (j=0; j<NI; j++) { 9391 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9392 if (DEBUG_SHOW_INFO) { 9393 Log.v(TAG, " IntentFilter:"); 9394 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9395 } 9396 removeFilter(intent); 9397 } 9398 } 9399 9400 @Override 9401 protected boolean allowFilterResult( 9402 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9403 ServiceInfo filterSi = filter.service.info; 9404 for (int i=dest.size()-1; i>=0; i--) { 9405 ServiceInfo destAi = dest.get(i).serviceInfo; 9406 if (destAi.name == filterSi.name 9407 && destAi.packageName == filterSi.packageName) { 9408 return false; 9409 } 9410 } 9411 return true; 9412 } 9413 9414 @Override 9415 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9416 return new PackageParser.ServiceIntentInfo[size]; 9417 } 9418 9419 @Override 9420 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9421 if (!sUserManager.exists(userId)) return true; 9422 PackageParser.Package p = filter.service.owner; 9423 if (p != null) { 9424 PackageSetting ps = (PackageSetting)p.mExtras; 9425 if (ps != null) { 9426 // System apps are never considered stopped for purposes of 9427 // filtering, because there may be no way for the user to 9428 // actually re-launch them. 9429 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9430 && ps.getStopped(userId); 9431 } 9432 } 9433 return false; 9434 } 9435 9436 @Override 9437 protected boolean isPackageForFilter(String packageName, 9438 PackageParser.ServiceIntentInfo info) { 9439 return packageName.equals(info.service.owner.packageName); 9440 } 9441 9442 @Override 9443 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9444 int match, int userId) { 9445 if (!sUserManager.exists(userId)) return null; 9446 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9447 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 9448 return null; 9449 } 9450 final PackageParser.Service service = info.service; 9451 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9452 if (ps == null) { 9453 return null; 9454 } 9455 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9456 ps.readUserState(userId), userId); 9457 if (si == null) { 9458 return null; 9459 } 9460 final ResolveInfo res = new ResolveInfo(); 9461 res.serviceInfo = si; 9462 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9463 res.filter = filter; 9464 } 9465 res.priority = info.getPriority(); 9466 res.preferredOrder = service.owner.mPreferredOrder; 9467 res.match = match; 9468 res.isDefault = info.hasDefault; 9469 res.labelRes = info.labelRes; 9470 res.nonLocalizedLabel = info.nonLocalizedLabel; 9471 res.icon = info.icon; 9472 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9473 return res; 9474 } 9475 9476 @Override 9477 protected void sortResults(List<ResolveInfo> results) { 9478 Collections.sort(results, mResolvePrioritySorter); 9479 } 9480 9481 @Override 9482 protected void dumpFilter(PrintWriter out, String prefix, 9483 PackageParser.ServiceIntentInfo filter) { 9484 out.print(prefix); out.print( 9485 Integer.toHexString(System.identityHashCode(filter.service))); 9486 out.print(' '); 9487 filter.service.printComponentShortName(out); 9488 out.print(" filter "); 9489 out.println(Integer.toHexString(System.identityHashCode(filter))); 9490 } 9491 9492 @Override 9493 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9494 return filter.service; 9495 } 9496 9497 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9498 PackageParser.Service service = (PackageParser.Service)label; 9499 out.print(prefix); out.print( 9500 Integer.toHexString(System.identityHashCode(service))); 9501 out.print(' '); 9502 service.printComponentShortName(out); 9503 if (count > 1) { 9504 out.print(" ("); out.print(count); out.print(" filters)"); 9505 } 9506 out.println(); 9507 } 9508 9509// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9510// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9511// final List<ResolveInfo> retList = Lists.newArrayList(); 9512// while (i.hasNext()) { 9513// final ResolveInfo resolveInfo = (ResolveInfo) i; 9514// if (isEnabledLP(resolveInfo.serviceInfo)) { 9515// retList.add(resolveInfo); 9516// } 9517// } 9518// return retList; 9519// } 9520 9521 // Keys are String (activity class name), values are Activity. 9522 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9523 = new ArrayMap<ComponentName, PackageParser.Service>(); 9524 private int mFlags; 9525 }; 9526 9527 private final class ProviderIntentResolver 9528 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9529 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9530 boolean defaultOnly, int userId) { 9531 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9532 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9533 } 9534 9535 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9536 int userId) { 9537 if (!sUserManager.exists(userId)) 9538 return null; 9539 mFlags = flags; 9540 return super.queryIntent(intent, resolvedType, 9541 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9542 } 9543 9544 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9545 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9546 if (!sUserManager.exists(userId)) 9547 return null; 9548 if (packageProviders == null) { 9549 return null; 9550 } 9551 mFlags = flags; 9552 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9553 final int N = packageProviders.size(); 9554 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9555 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9556 9557 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9558 for (int i = 0; i < N; ++i) { 9559 intentFilters = packageProviders.get(i).intents; 9560 if (intentFilters != null && intentFilters.size() > 0) { 9561 PackageParser.ProviderIntentInfo[] array = 9562 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9563 intentFilters.toArray(array); 9564 listCut.add(array); 9565 } 9566 } 9567 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9568 } 9569 9570 public final void addProvider(PackageParser.Provider p) { 9571 if (mProviders.containsKey(p.getComponentName())) { 9572 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9573 return; 9574 } 9575 9576 mProviders.put(p.getComponentName(), p); 9577 if (DEBUG_SHOW_INFO) { 9578 Log.v(TAG, " " 9579 + (p.info.nonLocalizedLabel != null 9580 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9581 Log.v(TAG, " Class=" + p.info.name); 9582 } 9583 final int NI = p.intents.size(); 9584 int j; 9585 for (j = 0; j < NI; j++) { 9586 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9587 if (DEBUG_SHOW_INFO) { 9588 Log.v(TAG, " IntentFilter:"); 9589 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9590 } 9591 if (!intent.debugCheck()) { 9592 Log.w(TAG, "==> For Provider " + p.info.name); 9593 } 9594 addFilter(intent); 9595 } 9596 } 9597 9598 public final void removeProvider(PackageParser.Provider p) { 9599 mProviders.remove(p.getComponentName()); 9600 if (DEBUG_SHOW_INFO) { 9601 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9602 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9603 Log.v(TAG, " Class=" + p.info.name); 9604 } 9605 final int NI = p.intents.size(); 9606 int j; 9607 for (j = 0; j < NI; j++) { 9608 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9609 if (DEBUG_SHOW_INFO) { 9610 Log.v(TAG, " IntentFilter:"); 9611 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9612 } 9613 removeFilter(intent); 9614 } 9615 } 9616 9617 @Override 9618 protected boolean allowFilterResult( 9619 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9620 ProviderInfo filterPi = filter.provider.info; 9621 for (int i = dest.size() - 1; i >= 0; i--) { 9622 ProviderInfo destPi = dest.get(i).providerInfo; 9623 if (destPi.name == filterPi.name 9624 && destPi.packageName == filterPi.packageName) { 9625 return false; 9626 } 9627 } 9628 return true; 9629 } 9630 9631 @Override 9632 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9633 return new PackageParser.ProviderIntentInfo[size]; 9634 } 9635 9636 @Override 9637 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9638 if (!sUserManager.exists(userId)) 9639 return true; 9640 PackageParser.Package p = filter.provider.owner; 9641 if (p != null) { 9642 PackageSetting ps = (PackageSetting) p.mExtras; 9643 if (ps != null) { 9644 // System apps are never considered stopped for purposes of 9645 // filtering, because there may be no way for the user to 9646 // actually re-launch them. 9647 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9648 && ps.getStopped(userId); 9649 } 9650 } 9651 return false; 9652 } 9653 9654 @Override 9655 protected boolean isPackageForFilter(String packageName, 9656 PackageParser.ProviderIntentInfo info) { 9657 return packageName.equals(info.provider.owner.packageName); 9658 } 9659 9660 @Override 9661 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9662 int match, int userId) { 9663 if (!sUserManager.exists(userId)) 9664 return null; 9665 final PackageParser.ProviderIntentInfo info = filter; 9666 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 9667 return null; 9668 } 9669 final PackageParser.Provider provider = info.provider; 9670 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9671 if (ps == null) { 9672 return null; 9673 } 9674 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9675 ps.readUserState(userId), userId); 9676 if (pi == null) { 9677 return null; 9678 } 9679 final ResolveInfo res = new ResolveInfo(); 9680 res.providerInfo = pi; 9681 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9682 res.filter = filter; 9683 } 9684 res.priority = info.getPriority(); 9685 res.preferredOrder = provider.owner.mPreferredOrder; 9686 res.match = match; 9687 res.isDefault = info.hasDefault; 9688 res.labelRes = info.labelRes; 9689 res.nonLocalizedLabel = info.nonLocalizedLabel; 9690 res.icon = info.icon; 9691 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9692 return res; 9693 } 9694 9695 @Override 9696 protected void sortResults(List<ResolveInfo> results) { 9697 Collections.sort(results, mResolvePrioritySorter); 9698 } 9699 9700 @Override 9701 protected void dumpFilter(PrintWriter out, String prefix, 9702 PackageParser.ProviderIntentInfo filter) { 9703 out.print(prefix); 9704 out.print( 9705 Integer.toHexString(System.identityHashCode(filter.provider))); 9706 out.print(' '); 9707 filter.provider.printComponentShortName(out); 9708 out.print(" filter "); 9709 out.println(Integer.toHexString(System.identityHashCode(filter))); 9710 } 9711 9712 @Override 9713 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9714 return filter.provider; 9715 } 9716 9717 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9718 PackageParser.Provider provider = (PackageParser.Provider)label; 9719 out.print(prefix); out.print( 9720 Integer.toHexString(System.identityHashCode(provider))); 9721 out.print(' '); 9722 provider.printComponentShortName(out); 9723 if (count > 1) { 9724 out.print(" ("); out.print(count); out.print(" filters)"); 9725 } 9726 out.println(); 9727 } 9728 9729 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9730 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9731 private int mFlags; 9732 } 9733 9734 private static final class EphemeralIntentResolver 9735 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 9736 @Override 9737 protected EphemeralResolveIntentInfo[] newArray(int size) { 9738 return new EphemeralResolveIntentInfo[size]; 9739 } 9740 9741 @Override 9742 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 9743 return true; 9744 } 9745 9746 @Override 9747 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 9748 int userId) { 9749 if (!sUserManager.exists(userId)) { 9750 return null; 9751 } 9752 return info.getEphemeralResolveInfo(); 9753 } 9754 } 9755 9756 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9757 new Comparator<ResolveInfo>() { 9758 public int compare(ResolveInfo r1, ResolveInfo r2) { 9759 int v1 = r1.priority; 9760 int v2 = r2.priority; 9761 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9762 if (v1 != v2) { 9763 return (v1 > v2) ? -1 : 1; 9764 } 9765 v1 = r1.preferredOrder; 9766 v2 = r2.preferredOrder; 9767 if (v1 != v2) { 9768 return (v1 > v2) ? -1 : 1; 9769 } 9770 if (r1.isDefault != r2.isDefault) { 9771 return r1.isDefault ? -1 : 1; 9772 } 9773 v1 = r1.match; 9774 v2 = r2.match; 9775 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9776 if (v1 != v2) { 9777 return (v1 > v2) ? -1 : 1; 9778 } 9779 if (r1.system != r2.system) { 9780 return r1.system ? -1 : 1; 9781 } 9782 if (r1.activityInfo != null) { 9783 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 9784 } 9785 if (r1.serviceInfo != null) { 9786 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 9787 } 9788 if (r1.providerInfo != null) { 9789 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 9790 } 9791 return 0; 9792 } 9793 }; 9794 9795 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9796 new Comparator<ProviderInfo>() { 9797 public int compare(ProviderInfo p1, ProviderInfo p2) { 9798 final int v1 = p1.initOrder; 9799 final int v2 = p2.initOrder; 9800 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9801 } 9802 }; 9803 9804 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 9805 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 9806 final int[] userIds) { 9807 mHandler.post(new Runnable() { 9808 @Override 9809 public void run() { 9810 try { 9811 final IActivityManager am = ActivityManagerNative.getDefault(); 9812 if (am == null) return; 9813 final int[] resolvedUserIds; 9814 if (userIds == null) { 9815 resolvedUserIds = am.getRunningUserIds(); 9816 } else { 9817 resolvedUserIds = userIds; 9818 } 9819 for (int id : resolvedUserIds) { 9820 final Intent intent = new Intent(action, 9821 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9822 if (extras != null) { 9823 intent.putExtras(extras); 9824 } 9825 if (targetPkg != null) { 9826 intent.setPackage(targetPkg); 9827 } 9828 // Modify the UID when posting to other users 9829 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9830 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9831 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9832 intent.putExtra(Intent.EXTRA_UID, uid); 9833 } 9834 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9835 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 9836 if (DEBUG_BROADCASTS) { 9837 RuntimeException here = new RuntimeException("here"); 9838 here.fillInStackTrace(); 9839 Slog.d(TAG, "Sending to user " + id + ": " 9840 + intent.toShortString(false, true, false, false) 9841 + " " + intent.getExtras(), here); 9842 } 9843 am.broadcastIntent(null, intent, null, finishedReceiver, 9844 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9845 null, finishedReceiver != null, false, id); 9846 } 9847 } catch (RemoteException ex) { 9848 } 9849 } 9850 }); 9851 } 9852 9853 /** 9854 * Check if the external storage media is available. This is true if there 9855 * is a mounted external storage medium or if the external storage is 9856 * emulated. 9857 */ 9858 private boolean isExternalMediaAvailable() { 9859 return mMediaMounted || Environment.isExternalStorageEmulated(); 9860 } 9861 9862 @Override 9863 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9864 // writer 9865 synchronized (mPackages) { 9866 if (!isExternalMediaAvailable()) { 9867 // If the external storage is no longer mounted at this point, 9868 // the caller may not have been able to delete all of this 9869 // packages files and can not delete any more. Bail. 9870 return null; 9871 } 9872 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9873 if (lastPackage != null) { 9874 pkgs.remove(lastPackage); 9875 } 9876 if (pkgs.size() > 0) { 9877 return pkgs.get(0); 9878 } 9879 } 9880 return null; 9881 } 9882 9883 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9884 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9885 userId, andCode ? 1 : 0, packageName); 9886 if (mSystemReady) { 9887 msg.sendToTarget(); 9888 } else { 9889 if (mPostSystemReadyMessages == null) { 9890 mPostSystemReadyMessages = new ArrayList<>(); 9891 } 9892 mPostSystemReadyMessages.add(msg); 9893 } 9894 } 9895 9896 void startCleaningPackages() { 9897 // reader 9898 synchronized (mPackages) { 9899 if (!isExternalMediaAvailable()) { 9900 return; 9901 } 9902 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9903 return; 9904 } 9905 } 9906 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9907 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9908 IActivityManager am = ActivityManagerNative.getDefault(); 9909 if (am != null) { 9910 try { 9911 am.startService(null, intent, null, mContext.getOpPackageName(), 9912 UserHandle.USER_SYSTEM); 9913 } catch (RemoteException e) { 9914 } 9915 } 9916 } 9917 9918 @Override 9919 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9920 int installFlags, String installerPackageName, VerificationParams verificationParams, 9921 String packageAbiOverride) { 9922 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9923 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9924 } 9925 9926 @Override 9927 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9928 int installFlags, String installerPackageName, VerificationParams verificationParams, 9929 String packageAbiOverride, int userId) { 9930 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9931 9932 final int callingUid = Binder.getCallingUid(); 9933 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9934 9935 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9936 try { 9937 if (observer != null) { 9938 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9939 } 9940 } catch (RemoteException re) { 9941 } 9942 return; 9943 } 9944 9945 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9946 installFlags |= PackageManager.INSTALL_FROM_ADB; 9947 9948 } else { 9949 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9950 // about installerPackageName. 9951 9952 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9953 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9954 } 9955 9956 UserHandle user; 9957 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9958 user = UserHandle.ALL; 9959 } else { 9960 user = new UserHandle(userId); 9961 } 9962 9963 // Only system components can circumvent runtime permissions when installing. 9964 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9965 && mContext.checkCallingOrSelfPermission(Manifest.permission 9966 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9967 throw new SecurityException("You need the " 9968 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9969 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9970 } 9971 9972 verificationParams.setInstallerUid(callingUid); 9973 9974 final File originFile = new File(originPath); 9975 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9976 9977 final Message msg = mHandler.obtainMessage(INIT_COPY); 9978 final InstallParams params = new InstallParams(origin, null, observer, installFlags, 9979 installerPackageName, null, verificationParams, user, packageAbiOverride, null); 9980 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 9981 msg.obj = params; 9982 9983 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 9984 System.identityHashCode(msg.obj)); 9985 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9986 System.identityHashCode(msg.obj)); 9987 9988 mHandler.sendMessage(msg); 9989 } 9990 9991 void installStage(String packageName, File stagedDir, String stagedCid, 9992 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 9993 String installerPackageName, int installerUid, UserHandle user) { 9994 if (DEBUG_EPHEMERAL) { 9995 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 9996 Slog.d(TAG, "Ephemeral install of " + packageName); 9997 } 9998 } 9999 final VerificationParams verifParams = new VerificationParams( 10000 null, sessionParams.originatingUri, sessionParams.referrerUri, 10001 sessionParams.originatingUid); 10002 verifParams.setInstallerUid(installerUid); 10003 10004 final OriginInfo origin; 10005 if (stagedDir != null) { 10006 origin = OriginInfo.fromStagedFile(stagedDir); 10007 } else { 10008 origin = OriginInfo.fromStagedContainer(stagedCid); 10009 } 10010 10011 final Message msg = mHandler.obtainMessage(INIT_COPY); 10012 final InstallParams params = new InstallParams(origin, null, observer, 10013 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 10014 verifParams, user, sessionParams.abiOverride, 10015 sessionParams.grantedRuntimePermissions); 10016 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 10017 msg.obj = params; 10018 10019 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 10020 System.identityHashCode(msg.obj)); 10021 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10022 System.identityHashCode(msg.obj)); 10023 10024 mHandler.sendMessage(msg); 10025 } 10026 10027 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 10028 Bundle extras = new Bundle(1); 10029 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 10030 10031 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 10032 packageName, extras, 0, null, null, new int[] {userId}); 10033 try { 10034 IActivityManager am = ActivityManagerNative.getDefault(); 10035 final boolean isSystem = 10036 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 10037 if (isSystem && am.isUserRunning(userId, 0)) { 10038 // The just-installed/enabled app is bundled on the system, so presumed 10039 // to be able to run automatically without needing an explicit launch. 10040 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 10041 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 10042 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 10043 .setPackage(packageName); 10044 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 10045 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 10046 } 10047 } catch (RemoteException e) { 10048 // shouldn't happen 10049 Slog.w(TAG, "Unable to bootstrap installed package", e); 10050 } 10051 } 10052 10053 @Override 10054 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 10055 int userId) { 10056 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10057 PackageSetting pkgSetting; 10058 final int uid = Binder.getCallingUid(); 10059 enforceCrossUserPermission(uid, userId, true, true, 10060 "setApplicationHiddenSetting for user " + userId); 10061 10062 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 10063 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 10064 return false; 10065 } 10066 10067 long callingId = Binder.clearCallingIdentity(); 10068 try { 10069 boolean sendAdded = false; 10070 boolean sendRemoved = false; 10071 // writer 10072 synchronized (mPackages) { 10073 pkgSetting = mSettings.mPackages.get(packageName); 10074 if (pkgSetting == null) { 10075 return false; 10076 } 10077 if (pkgSetting.getHidden(userId) != hidden) { 10078 pkgSetting.setHidden(hidden, userId); 10079 mSettings.writePackageRestrictionsLPr(userId); 10080 if (hidden) { 10081 sendRemoved = true; 10082 } else { 10083 sendAdded = true; 10084 } 10085 } 10086 } 10087 if (sendAdded) { 10088 sendPackageAddedForUser(packageName, pkgSetting, userId); 10089 return true; 10090 } 10091 if (sendRemoved) { 10092 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 10093 "hiding pkg"); 10094 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 10095 return true; 10096 } 10097 } finally { 10098 Binder.restoreCallingIdentity(callingId); 10099 } 10100 return false; 10101 } 10102 10103 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 10104 int userId) { 10105 final PackageRemovedInfo info = new PackageRemovedInfo(); 10106 info.removedPackage = packageName; 10107 info.removedUsers = new int[] {userId}; 10108 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 10109 info.sendBroadcast(false, false, false); 10110 } 10111 10112 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 10113 if (pkgList.length > 0) { 10114 Bundle extras = new Bundle(1); 10115 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 10116 10117 sendPackageBroadcast( 10118 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 10119 : Intent.ACTION_PACKAGES_UNSUSPENDED, 10120 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 10121 new int[] {userId}); 10122 } 10123 } 10124 10125 /** 10126 * Returns true if application is not found or there was an error. Otherwise it returns 10127 * the hidden state of the package for the given user. 10128 */ 10129 @Override 10130 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 10131 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10132 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 10133 false, "getApplicationHidden for user " + userId); 10134 PackageSetting pkgSetting; 10135 long callingId = Binder.clearCallingIdentity(); 10136 try { 10137 // writer 10138 synchronized (mPackages) { 10139 pkgSetting = mSettings.mPackages.get(packageName); 10140 if (pkgSetting == null) { 10141 return true; 10142 } 10143 return pkgSetting.getHidden(userId); 10144 } 10145 } finally { 10146 Binder.restoreCallingIdentity(callingId); 10147 } 10148 } 10149 10150 /** 10151 * @hide 10152 */ 10153 @Override 10154 public int installExistingPackageAsUser(String packageName, int userId) { 10155 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 10156 null); 10157 PackageSetting pkgSetting; 10158 final int uid = Binder.getCallingUid(); 10159 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 10160 + userId); 10161 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10162 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 10163 } 10164 10165 long callingId = Binder.clearCallingIdentity(); 10166 try { 10167 boolean installed = false; 10168 10169 // writer 10170 synchronized (mPackages) { 10171 pkgSetting = mSettings.mPackages.get(packageName); 10172 if (pkgSetting == null) { 10173 return PackageManager.INSTALL_FAILED_INVALID_URI; 10174 } 10175 if (!pkgSetting.getInstalled(userId)) { 10176 pkgSetting.setInstalled(true, userId); 10177 pkgSetting.setHidden(false, userId); 10178 mSettings.writePackageRestrictionsLPr(userId); 10179 if (pkgSetting.pkg != null) { 10180 prepareAppDataAfterInstall(pkgSetting.pkg); 10181 } 10182 installed = true; 10183 } 10184 } 10185 10186 if (installed) { 10187 sendPackageAddedForUser(packageName, pkgSetting, userId); 10188 } 10189 } finally { 10190 Binder.restoreCallingIdentity(callingId); 10191 } 10192 10193 return PackageManager.INSTALL_SUCCEEDED; 10194 } 10195 10196 boolean isUserRestricted(int userId, String restrictionKey) { 10197 Bundle restrictions = sUserManager.getUserRestrictions(userId); 10198 if (restrictions.getBoolean(restrictionKey, false)) { 10199 Log.w(TAG, "User is restricted: " + restrictionKey); 10200 return true; 10201 } 10202 return false; 10203 } 10204 10205 @Override 10206 public boolean setPackageSuspendedAsUser(String packageName, boolean suspended, int userId) { 10207 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10208 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true, 10209 "setPackageSuspended for user " + userId); 10210 10211 // TODO: investigate and add more restrictions for suspending crucial packages. 10212 if (isPackageDeviceAdmin(packageName, userId)) { 10213 Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName 10214 + "\": has active device admin"); 10215 return false; 10216 } 10217 10218 long callingId = Binder.clearCallingIdentity(); 10219 try { 10220 boolean changed = false; 10221 boolean success = false; 10222 int appId = -1; 10223 synchronized (mPackages) { 10224 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10225 if (pkgSetting != null) { 10226 if (pkgSetting.getSuspended(userId) != suspended) { 10227 pkgSetting.setSuspended(suspended, userId); 10228 mSettings.writePackageRestrictionsLPr(userId); 10229 appId = pkgSetting.appId; 10230 changed = true; 10231 } 10232 success = true; 10233 } 10234 } 10235 10236 if (changed) { 10237 sendPackagesSuspendedForUser(new String[]{packageName}, userId, suspended); 10238 if (suspended) { 10239 killApplication(packageName, UserHandle.getUid(userId, appId), 10240 "suspending package"); 10241 } 10242 } 10243 return success; 10244 } finally { 10245 Binder.restoreCallingIdentity(callingId); 10246 } 10247 } 10248 10249 @Override 10250 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 10251 mContext.enforceCallingOrSelfPermission( 10252 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10253 "Only package verification agents can verify applications"); 10254 10255 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10256 final PackageVerificationResponse response = new PackageVerificationResponse( 10257 verificationCode, Binder.getCallingUid()); 10258 msg.arg1 = id; 10259 msg.obj = response; 10260 mHandler.sendMessage(msg); 10261 } 10262 10263 @Override 10264 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 10265 long millisecondsToDelay) { 10266 mContext.enforceCallingOrSelfPermission( 10267 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10268 "Only package verification agents can extend verification timeouts"); 10269 10270 final PackageVerificationState state = mPendingVerification.get(id); 10271 final PackageVerificationResponse response = new PackageVerificationResponse( 10272 verificationCodeAtTimeout, Binder.getCallingUid()); 10273 10274 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 10275 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 10276 } 10277 if (millisecondsToDelay < 0) { 10278 millisecondsToDelay = 0; 10279 } 10280 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 10281 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 10282 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 10283 } 10284 10285 if ((state != null) && !state.timeoutExtended()) { 10286 state.extendTimeout(); 10287 10288 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10289 msg.arg1 = id; 10290 msg.obj = response; 10291 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 10292 } 10293 } 10294 10295 private void broadcastPackageVerified(int verificationId, Uri packageUri, 10296 int verificationCode, UserHandle user) { 10297 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 10298 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 10299 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10300 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10301 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 10302 10303 mContext.sendBroadcastAsUser(intent, user, 10304 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 10305 } 10306 10307 private ComponentName matchComponentForVerifier(String packageName, 10308 List<ResolveInfo> receivers) { 10309 ActivityInfo targetReceiver = null; 10310 10311 final int NR = receivers.size(); 10312 for (int i = 0; i < NR; i++) { 10313 final ResolveInfo info = receivers.get(i); 10314 if (info.activityInfo == null) { 10315 continue; 10316 } 10317 10318 if (packageName.equals(info.activityInfo.packageName)) { 10319 targetReceiver = info.activityInfo; 10320 break; 10321 } 10322 } 10323 10324 if (targetReceiver == null) { 10325 return null; 10326 } 10327 10328 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 10329 } 10330 10331 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 10332 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 10333 if (pkgInfo.verifiers.length == 0) { 10334 return null; 10335 } 10336 10337 final int N = pkgInfo.verifiers.length; 10338 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 10339 for (int i = 0; i < N; i++) { 10340 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 10341 10342 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 10343 receivers); 10344 if (comp == null) { 10345 continue; 10346 } 10347 10348 final int verifierUid = getUidForVerifier(verifierInfo); 10349 if (verifierUid == -1) { 10350 continue; 10351 } 10352 10353 if (DEBUG_VERIFY) { 10354 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 10355 + " with the correct signature"); 10356 } 10357 sufficientVerifiers.add(comp); 10358 verificationState.addSufficientVerifier(verifierUid); 10359 } 10360 10361 return sufficientVerifiers; 10362 } 10363 10364 private int getUidForVerifier(VerifierInfo verifierInfo) { 10365 synchronized (mPackages) { 10366 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 10367 if (pkg == null) { 10368 return -1; 10369 } else if (pkg.mSignatures.length != 1) { 10370 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10371 + " has more than one signature; ignoring"); 10372 return -1; 10373 } 10374 10375 /* 10376 * If the public key of the package's signature does not match 10377 * our expected public key, then this is a different package and 10378 * we should skip. 10379 */ 10380 10381 final byte[] expectedPublicKey; 10382 try { 10383 final Signature verifierSig = pkg.mSignatures[0]; 10384 final PublicKey publicKey = verifierSig.getPublicKey(); 10385 expectedPublicKey = publicKey.getEncoded(); 10386 } catch (CertificateException e) { 10387 return -1; 10388 } 10389 10390 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 10391 10392 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 10393 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10394 + " does not have the expected public key; ignoring"); 10395 return -1; 10396 } 10397 10398 return pkg.applicationInfo.uid; 10399 } 10400 } 10401 10402 @Override 10403 public void finishPackageInstall(int token) { 10404 enforceSystemOrRoot("Only the system is allowed to finish installs"); 10405 10406 if (DEBUG_INSTALL) { 10407 Slog.v(TAG, "BM finishing package install for " + token); 10408 } 10409 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10410 10411 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10412 mHandler.sendMessage(msg); 10413 } 10414 10415 /** 10416 * Get the verification agent timeout. 10417 * 10418 * @return verification timeout in milliseconds 10419 */ 10420 private long getVerificationTimeout() { 10421 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 10422 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 10423 DEFAULT_VERIFICATION_TIMEOUT); 10424 } 10425 10426 /** 10427 * Get the default verification agent response code. 10428 * 10429 * @return default verification response code 10430 */ 10431 private int getDefaultVerificationResponse() { 10432 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10433 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 10434 DEFAULT_VERIFICATION_RESPONSE); 10435 } 10436 10437 /** 10438 * Check whether or not package verification has been enabled. 10439 * 10440 * @return true if verification should be performed 10441 */ 10442 private boolean isVerificationEnabled(int userId, int installFlags) { 10443 if (!DEFAULT_VERIFY_ENABLE) { 10444 return false; 10445 } 10446 // Ephemeral apps don't get the full verification treatment 10447 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10448 if (DEBUG_EPHEMERAL) { 10449 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 10450 } 10451 return false; 10452 } 10453 10454 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 10455 10456 // Check if installing from ADB 10457 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 10458 // Do not run verification in a test harness environment 10459 if (ActivityManager.isRunningInTestHarness()) { 10460 return false; 10461 } 10462 if (ensureVerifyAppsEnabled) { 10463 return true; 10464 } 10465 // Check if the developer does not want package verification for ADB installs 10466 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10467 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 10468 return false; 10469 } 10470 } 10471 10472 if (ensureVerifyAppsEnabled) { 10473 return true; 10474 } 10475 10476 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10477 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 10478 } 10479 10480 @Override 10481 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 10482 throws RemoteException { 10483 mContext.enforceCallingOrSelfPermission( 10484 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 10485 "Only intentfilter verification agents can verify applications"); 10486 10487 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 10488 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 10489 Binder.getCallingUid(), verificationCode, failedDomains); 10490 msg.arg1 = id; 10491 msg.obj = response; 10492 mHandler.sendMessage(msg); 10493 } 10494 10495 @Override 10496 public int getIntentVerificationStatus(String packageName, int userId) { 10497 synchronized (mPackages) { 10498 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10499 } 10500 } 10501 10502 @Override 10503 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10504 mContext.enforceCallingOrSelfPermission( 10505 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10506 10507 boolean result = false; 10508 synchronized (mPackages) { 10509 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10510 } 10511 if (result) { 10512 scheduleWritePackageRestrictionsLocked(userId); 10513 } 10514 return result; 10515 } 10516 10517 @Override 10518 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10519 synchronized (mPackages) { 10520 return mSettings.getIntentFilterVerificationsLPr(packageName); 10521 } 10522 } 10523 10524 @Override 10525 public List<IntentFilter> getAllIntentFilters(String packageName) { 10526 if (TextUtils.isEmpty(packageName)) { 10527 return Collections.<IntentFilter>emptyList(); 10528 } 10529 synchronized (mPackages) { 10530 PackageParser.Package pkg = mPackages.get(packageName); 10531 if (pkg == null || pkg.activities == null) { 10532 return Collections.<IntentFilter>emptyList(); 10533 } 10534 final int count = pkg.activities.size(); 10535 ArrayList<IntentFilter> result = new ArrayList<>(); 10536 for (int n=0; n<count; n++) { 10537 PackageParser.Activity activity = pkg.activities.get(n); 10538 if (activity.intents != null && activity.intents.size() > 0) { 10539 result.addAll(activity.intents); 10540 } 10541 } 10542 return result; 10543 } 10544 } 10545 10546 @Override 10547 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10548 mContext.enforceCallingOrSelfPermission( 10549 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10550 10551 synchronized (mPackages) { 10552 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10553 if (packageName != null) { 10554 result |= updateIntentVerificationStatus(packageName, 10555 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10556 userId); 10557 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10558 packageName, userId); 10559 } 10560 return result; 10561 } 10562 } 10563 10564 @Override 10565 public String getDefaultBrowserPackageName(int userId) { 10566 synchronized (mPackages) { 10567 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10568 } 10569 } 10570 10571 /** 10572 * Get the "allow unknown sources" setting. 10573 * 10574 * @return the current "allow unknown sources" setting 10575 */ 10576 private int getUnknownSourcesSettings() { 10577 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10578 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10579 -1); 10580 } 10581 10582 @Override 10583 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10584 final int uid = Binder.getCallingUid(); 10585 // writer 10586 synchronized (mPackages) { 10587 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10588 if (targetPackageSetting == null) { 10589 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10590 } 10591 10592 PackageSetting installerPackageSetting; 10593 if (installerPackageName != null) { 10594 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10595 if (installerPackageSetting == null) { 10596 throw new IllegalArgumentException("Unknown installer package: " 10597 + installerPackageName); 10598 } 10599 } else { 10600 installerPackageSetting = null; 10601 } 10602 10603 Signature[] callerSignature; 10604 Object obj = mSettings.getUserIdLPr(uid); 10605 if (obj != null) { 10606 if (obj instanceof SharedUserSetting) { 10607 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10608 } else if (obj instanceof PackageSetting) { 10609 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10610 } else { 10611 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10612 } 10613 } else { 10614 throw new SecurityException("Unknown calling UID: " + uid); 10615 } 10616 10617 // Verify: can't set installerPackageName to a package that is 10618 // not signed with the same cert as the caller. 10619 if (installerPackageSetting != null) { 10620 if (compareSignatures(callerSignature, 10621 installerPackageSetting.signatures.mSignatures) 10622 != PackageManager.SIGNATURE_MATCH) { 10623 throw new SecurityException( 10624 "Caller does not have same cert as new installer package " 10625 + installerPackageName); 10626 } 10627 } 10628 10629 // Verify: if target already has an installer package, it must 10630 // be signed with the same cert as the caller. 10631 if (targetPackageSetting.installerPackageName != null) { 10632 PackageSetting setting = mSettings.mPackages.get( 10633 targetPackageSetting.installerPackageName); 10634 // If the currently set package isn't valid, then it's always 10635 // okay to change it. 10636 if (setting != null) { 10637 if (compareSignatures(callerSignature, 10638 setting.signatures.mSignatures) 10639 != PackageManager.SIGNATURE_MATCH) { 10640 throw new SecurityException( 10641 "Caller does not have same cert as old installer package " 10642 + targetPackageSetting.installerPackageName); 10643 } 10644 } 10645 } 10646 10647 // Okay! 10648 targetPackageSetting.installerPackageName = installerPackageName; 10649 scheduleWriteSettingsLocked(); 10650 } 10651 } 10652 10653 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10654 // Queue up an async operation since the package installation may take a little while. 10655 mHandler.post(new Runnable() { 10656 public void run() { 10657 mHandler.removeCallbacks(this); 10658 // Result object to be returned 10659 PackageInstalledInfo res = new PackageInstalledInfo(); 10660 res.returnCode = currentStatus; 10661 res.uid = -1; 10662 res.pkg = null; 10663 res.removedInfo = new PackageRemovedInfo(); 10664 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10665 args.doPreInstall(res.returnCode); 10666 synchronized (mInstallLock) { 10667 installPackageTracedLI(args, res); 10668 } 10669 args.doPostInstall(res.returnCode, res.uid); 10670 } 10671 10672 // A restore should be performed at this point if (a) the install 10673 // succeeded, (b) the operation is not an update, and (c) the new 10674 // package has not opted out of backup participation. 10675 final boolean update = res.removedInfo.removedPackage != null; 10676 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10677 boolean doRestore = !update 10678 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10679 10680 // Set up the post-install work request bookkeeping. This will be used 10681 // and cleaned up by the post-install event handling regardless of whether 10682 // there's a restore pass performed. Token values are >= 1. 10683 int token; 10684 if (mNextInstallToken < 0) mNextInstallToken = 1; 10685 token = mNextInstallToken++; 10686 10687 PostInstallData data = new PostInstallData(args, res); 10688 mRunningInstalls.put(token, data); 10689 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10690 10691 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10692 // Pass responsibility to the Backup Manager. It will perform a 10693 // restore if appropriate, then pass responsibility back to the 10694 // Package Manager to run the post-install observer callbacks 10695 // and broadcasts. 10696 IBackupManager bm = IBackupManager.Stub.asInterface( 10697 ServiceManager.getService(Context.BACKUP_SERVICE)); 10698 if (bm != null) { 10699 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10700 + " to BM for possible restore"); 10701 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10702 try { 10703 // TODO: http://b/22388012 10704 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 10705 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10706 } else { 10707 doRestore = false; 10708 } 10709 } catch (RemoteException e) { 10710 // can't happen; the backup manager is local 10711 } catch (Exception e) { 10712 Slog.e(TAG, "Exception trying to enqueue restore", e); 10713 doRestore = false; 10714 } 10715 } else { 10716 Slog.e(TAG, "Backup Manager not found!"); 10717 doRestore = false; 10718 } 10719 } 10720 10721 if (!doRestore) { 10722 // No restore possible, or the Backup Manager was mysteriously not 10723 // available -- just fire the post-install work request directly. 10724 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10725 10726 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 10727 10728 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10729 mHandler.sendMessage(msg); 10730 } 10731 } 10732 }); 10733 } 10734 10735 private abstract class HandlerParams { 10736 private static final int MAX_RETRIES = 4; 10737 10738 /** 10739 * Number of times startCopy() has been attempted and had a non-fatal 10740 * error. 10741 */ 10742 private int mRetries = 0; 10743 10744 /** User handle for the user requesting the information or installation. */ 10745 private final UserHandle mUser; 10746 String traceMethod; 10747 int traceCookie; 10748 10749 HandlerParams(UserHandle user) { 10750 mUser = user; 10751 } 10752 10753 UserHandle getUser() { 10754 return mUser; 10755 } 10756 10757 HandlerParams setTraceMethod(String traceMethod) { 10758 this.traceMethod = traceMethod; 10759 return this; 10760 } 10761 10762 HandlerParams setTraceCookie(int traceCookie) { 10763 this.traceCookie = traceCookie; 10764 return this; 10765 } 10766 10767 final boolean startCopy() { 10768 boolean res; 10769 try { 10770 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10771 10772 if (++mRetries > MAX_RETRIES) { 10773 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10774 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10775 handleServiceError(); 10776 return false; 10777 } else { 10778 handleStartCopy(); 10779 res = true; 10780 } 10781 } catch (RemoteException e) { 10782 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10783 mHandler.sendEmptyMessage(MCS_RECONNECT); 10784 res = false; 10785 } 10786 handleReturnCode(); 10787 return res; 10788 } 10789 10790 final void serviceError() { 10791 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10792 handleServiceError(); 10793 handleReturnCode(); 10794 } 10795 10796 abstract void handleStartCopy() throws RemoteException; 10797 abstract void handleServiceError(); 10798 abstract void handleReturnCode(); 10799 } 10800 10801 class MeasureParams extends HandlerParams { 10802 private final PackageStats mStats; 10803 private boolean mSuccess; 10804 10805 private final IPackageStatsObserver mObserver; 10806 10807 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10808 super(new UserHandle(stats.userHandle)); 10809 mObserver = observer; 10810 mStats = stats; 10811 } 10812 10813 @Override 10814 public String toString() { 10815 return "MeasureParams{" 10816 + Integer.toHexString(System.identityHashCode(this)) 10817 + " " + mStats.packageName + "}"; 10818 } 10819 10820 @Override 10821 void handleStartCopy() throws RemoteException { 10822 synchronized (mInstallLock) { 10823 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10824 } 10825 10826 if (mSuccess) { 10827 final boolean mounted; 10828 if (Environment.isExternalStorageEmulated()) { 10829 mounted = true; 10830 } else { 10831 final String status = Environment.getExternalStorageState(); 10832 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10833 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10834 } 10835 10836 if (mounted) { 10837 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10838 10839 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10840 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10841 10842 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10843 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10844 10845 // Always subtract cache size, since it's a subdirectory 10846 mStats.externalDataSize -= mStats.externalCacheSize; 10847 10848 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10849 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10850 10851 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10852 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10853 } 10854 } 10855 } 10856 10857 @Override 10858 void handleReturnCode() { 10859 if (mObserver != null) { 10860 try { 10861 mObserver.onGetStatsCompleted(mStats, mSuccess); 10862 } catch (RemoteException e) { 10863 Slog.i(TAG, "Observer no longer exists."); 10864 } 10865 } 10866 } 10867 10868 @Override 10869 void handleServiceError() { 10870 Slog.e(TAG, "Could not measure application " + mStats.packageName 10871 + " external storage"); 10872 } 10873 } 10874 10875 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10876 throws RemoteException { 10877 long result = 0; 10878 for (File path : paths) { 10879 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10880 } 10881 return result; 10882 } 10883 10884 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10885 for (File path : paths) { 10886 try { 10887 mcs.clearDirectory(path.getAbsolutePath()); 10888 } catch (RemoteException e) { 10889 } 10890 } 10891 } 10892 10893 static class OriginInfo { 10894 /** 10895 * Location where install is coming from, before it has been 10896 * copied/renamed into place. This could be a single monolithic APK 10897 * file, or a cluster directory. This location may be untrusted. 10898 */ 10899 final File file; 10900 final String cid; 10901 10902 /** 10903 * Flag indicating that {@link #file} or {@link #cid} has already been 10904 * staged, meaning downstream users don't need to defensively copy the 10905 * contents. 10906 */ 10907 final boolean staged; 10908 10909 /** 10910 * Flag indicating that {@link #file} or {@link #cid} is an already 10911 * installed app that is being moved. 10912 */ 10913 final boolean existing; 10914 10915 final String resolvedPath; 10916 final File resolvedFile; 10917 10918 static OriginInfo fromNothing() { 10919 return new OriginInfo(null, null, false, false); 10920 } 10921 10922 static OriginInfo fromUntrustedFile(File file) { 10923 return new OriginInfo(file, null, false, false); 10924 } 10925 10926 static OriginInfo fromExistingFile(File file) { 10927 return new OriginInfo(file, null, false, true); 10928 } 10929 10930 static OriginInfo fromStagedFile(File file) { 10931 return new OriginInfo(file, null, true, false); 10932 } 10933 10934 static OriginInfo fromStagedContainer(String cid) { 10935 return new OriginInfo(null, cid, true, false); 10936 } 10937 10938 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10939 this.file = file; 10940 this.cid = cid; 10941 this.staged = staged; 10942 this.existing = existing; 10943 10944 if (cid != null) { 10945 resolvedPath = PackageHelper.getSdDir(cid); 10946 resolvedFile = new File(resolvedPath); 10947 } else if (file != null) { 10948 resolvedPath = file.getAbsolutePath(); 10949 resolvedFile = file; 10950 } else { 10951 resolvedPath = null; 10952 resolvedFile = null; 10953 } 10954 } 10955 } 10956 10957 static class MoveInfo { 10958 final int moveId; 10959 final String fromUuid; 10960 final String toUuid; 10961 final String packageName; 10962 final String dataAppName; 10963 final int appId; 10964 final String seinfo; 10965 final int targetSdkVersion; 10966 10967 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10968 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 10969 this.moveId = moveId; 10970 this.fromUuid = fromUuid; 10971 this.toUuid = toUuid; 10972 this.packageName = packageName; 10973 this.dataAppName = dataAppName; 10974 this.appId = appId; 10975 this.seinfo = seinfo; 10976 this.targetSdkVersion = targetSdkVersion; 10977 } 10978 } 10979 10980 class InstallParams extends HandlerParams { 10981 final OriginInfo origin; 10982 final MoveInfo move; 10983 final IPackageInstallObserver2 observer; 10984 int installFlags; 10985 final String installerPackageName; 10986 final String volumeUuid; 10987 final VerificationParams verificationParams; 10988 private InstallArgs mArgs; 10989 private int mRet; 10990 final String packageAbiOverride; 10991 final String[] grantedRuntimePermissions; 10992 10993 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10994 int installFlags, String installerPackageName, String volumeUuid, 10995 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10996 String[] grantedPermissions) { 10997 super(user); 10998 this.origin = origin; 10999 this.move = move; 11000 this.observer = observer; 11001 this.installFlags = installFlags; 11002 this.installerPackageName = installerPackageName; 11003 this.volumeUuid = volumeUuid; 11004 this.verificationParams = verificationParams; 11005 this.packageAbiOverride = packageAbiOverride; 11006 this.grantedRuntimePermissions = grantedPermissions; 11007 } 11008 11009 @Override 11010 public String toString() { 11011 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 11012 + " file=" + origin.file + " cid=" + origin.cid + "}"; 11013 } 11014 11015 private int installLocationPolicy(PackageInfoLite pkgLite) { 11016 String packageName = pkgLite.packageName; 11017 int installLocation = pkgLite.installLocation; 11018 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11019 // reader 11020 synchronized (mPackages) { 11021 PackageParser.Package pkg = mPackages.get(packageName); 11022 if (pkg != null) { 11023 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11024 // Check for downgrading. 11025 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 11026 try { 11027 checkDowngrade(pkg, pkgLite); 11028 } catch (PackageManagerException e) { 11029 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 11030 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 11031 } 11032 } 11033 // Check for updated system application. 11034 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11035 if (onSd) { 11036 Slog.w(TAG, "Cannot install update to system app on sdcard"); 11037 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 11038 } 11039 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11040 } else { 11041 if (onSd) { 11042 // Install flag overrides everything. 11043 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11044 } 11045 // If current upgrade specifies particular preference 11046 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 11047 // Application explicitly specified internal. 11048 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11049 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 11050 // App explictly prefers external. Let policy decide 11051 } else { 11052 // Prefer previous location 11053 if (isExternal(pkg)) { 11054 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11055 } 11056 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11057 } 11058 } 11059 } else { 11060 // Invalid install. Return error code 11061 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 11062 } 11063 } 11064 } 11065 // All the special cases have been taken care of. 11066 // Return result based on recommended install location. 11067 if (onSd) { 11068 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11069 } 11070 return pkgLite.recommendedInstallLocation; 11071 } 11072 11073 /* 11074 * Invoke remote method to get package information and install 11075 * location values. Override install location based on default 11076 * policy if needed and then create install arguments based 11077 * on the install location. 11078 */ 11079 public void handleStartCopy() throws RemoteException { 11080 int ret = PackageManager.INSTALL_SUCCEEDED; 11081 11082 // If we're already staged, we've firmly committed to an install location 11083 if (origin.staged) { 11084 if (origin.file != null) { 11085 installFlags |= PackageManager.INSTALL_INTERNAL; 11086 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11087 } else if (origin.cid != null) { 11088 installFlags |= PackageManager.INSTALL_EXTERNAL; 11089 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11090 } else { 11091 throw new IllegalStateException("Invalid stage location"); 11092 } 11093 } 11094 11095 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11096 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 11097 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11098 PackageInfoLite pkgLite = null; 11099 11100 if (onInt && onSd) { 11101 // Check if both bits are set. 11102 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 11103 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11104 } else if (onSd && ephemeral) { 11105 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 11106 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11107 } else { 11108 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 11109 packageAbiOverride); 11110 11111 if (DEBUG_EPHEMERAL && ephemeral) { 11112 Slog.v(TAG, "pkgLite for install: " + pkgLite); 11113 } 11114 11115 /* 11116 * If we have too little free space, try to free cache 11117 * before giving up. 11118 */ 11119 if (!origin.staged && pkgLite.recommendedInstallLocation 11120 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11121 // TODO: focus freeing disk space on the target device 11122 final StorageManager storage = StorageManager.from(mContext); 11123 final long lowThreshold = storage.getStorageLowBytes( 11124 Environment.getDataDirectory()); 11125 11126 final long sizeBytes = mContainerService.calculateInstalledSize( 11127 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 11128 11129 try { 11130 mInstaller.freeCache(null, sizeBytes + lowThreshold); 11131 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 11132 installFlags, packageAbiOverride); 11133 } catch (InstallerException e) { 11134 Slog.w(TAG, "Failed to free cache", e); 11135 } 11136 11137 /* 11138 * The cache free must have deleted the file we 11139 * downloaded to install. 11140 * 11141 * TODO: fix the "freeCache" call to not delete 11142 * the file we care about. 11143 */ 11144 if (pkgLite.recommendedInstallLocation 11145 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11146 pkgLite.recommendedInstallLocation 11147 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 11148 } 11149 } 11150 } 11151 11152 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11153 int loc = pkgLite.recommendedInstallLocation; 11154 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 11155 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11156 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 11157 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 11158 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11159 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11160 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 11161 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 11162 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11163 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 11164 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 11165 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 11166 } else { 11167 // Override with defaults if needed. 11168 loc = installLocationPolicy(pkgLite); 11169 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 11170 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 11171 } else if (!onSd && !onInt) { 11172 // Override install location with flags 11173 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 11174 // Set the flag to install on external media. 11175 installFlags |= PackageManager.INSTALL_EXTERNAL; 11176 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11177 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 11178 if (DEBUG_EPHEMERAL) { 11179 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 11180 } 11181 installFlags |= PackageManager.INSTALL_EPHEMERAL; 11182 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 11183 |PackageManager.INSTALL_INTERNAL); 11184 } else { 11185 // Make sure the flag for installing on external 11186 // media is unset 11187 installFlags |= PackageManager.INSTALL_INTERNAL; 11188 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11189 } 11190 } 11191 } 11192 } 11193 11194 final InstallArgs args = createInstallArgs(this); 11195 mArgs = args; 11196 11197 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11198 // TODO: http://b/22976637 11199 // Apps installed for "all" users use the device owner to verify the app 11200 UserHandle verifierUser = getUser(); 11201 if (verifierUser == UserHandle.ALL) { 11202 verifierUser = UserHandle.SYSTEM; 11203 } 11204 11205 /* 11206 * Determine if we have any installed package verifiers. If we 11207 * do, then we'll defer to them to verify the packages. 11208 */ 11209 final int requiredUid = mRequiredVerifierPackage == null ? -1 11210 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 11211 verifierUser.getIdentifier()); 11212 if (!origin.existing && requiredUid != -1 11213 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 11214 final Intent verification = new Intent( 11215 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 11216 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 11217 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 11218 PACKAGE_MIME_TYPE); 11219 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11220 11221 // Query all live verifiers based on current user state 11222 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 11223 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 11224 11225 if (DEBUG_VERIFY) { 11226 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 11227 + verification.toString() + " with " + pkgLite.verifiers.length 11228 + " optional verifiers"); 11229 } 11230 11231 final int verificationId = mPendingVerificationToken++; 11232 11233 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11234 11235 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 11236 installerPackageName); 11237 11238 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 11239 installFlags); 11240 11241 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 11242 pkgLite.packageName); 11243 11244 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 11245 pkgLite.versionCode); 11246 11247 if (verificationParams != null) { 11248 if (verificationParams.getVerificationURI() != null) { 11249 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 11250 verificationParams.getVerificationURI()); 11251 } 11252 if (verificationParams.getOriginatingURI() != null) { 11253 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 11254 verificationParams.getOriginatingURI()); 11255 } 11256 if (verificationParams.getReferrer() != null) { 11257 verification.putExtra(Intent.EXTRA_REFERRER, 11258 verificationParams.getReferrer()); 11259 } 11260 if (verificationParams.getOriginatingUid() >= 0) { 11261 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 11262 verificationParams.getOriginatingUid()); 11263 } 11264 if (verificationParams.getInstallerUid() >= 0) { 11265 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 11266 verificationParams.getInstallerUid()); 11267 } 11268 } 11269 11270 final PackageVerificationState verificationState = new PackageVerificationState( 11271 requiredUid, args); 11272 11273 mPendingVerification.append(verificationId, verificationState); 11274 11275 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 11276 receivers, verificationState); 11277 11278 /* 11279 * If any sufficient verifiers were listed in the package 11280 * manifest, attempt to ask them. 11281 */ 11282 if (sufficientVerifiers != null) { 11283 final int N = sufficientVerifiers.size(); 11284 if (N == 0) { 11285 Slog.i(TAG, "Additional verifiers required, but none installed."); 11286 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 11287 } else { 11288 for (int i = 0; i < N; i++) { 11289 final ComponentName verifierComponent = sufficientVerifiers.get(i); 11290 11291 final Intent sufficientIntent = new Intent(verification); 11292 sufficientIntent.setComponent(verifierComponent); 11293 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 11294 } 11295 } 11296 } 11297 11298 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 11299 mRequiredVerifierPackage, receivers); 11300 if (ret == PackageManager.INSTALL_SUCCEEDED 11301 && mRequiredVerifierPackage != null) { 11302 Trace.asyncTraceBegin( 11303 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 11304 /* 11305 * Send the intent to the required verification agent, 11306 * but only start the verification timeout after the 11307 * target BroadcastReceivers have run. 11308 */ 11309 verification.setComponent(requiredVerifierComponent); 11310 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 11311 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11312 new BroadcastReceiver() { 11313 @Override 11314 public void onReceive(Context context, Intent intent) { 11315 final Message msg = mHandler 11316 .obtainMessage(CHECK_PENDING_VERIFICATION); 11317 msg.arg1 = verificationId; 11318 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 11319 } 11320 }, null, 0, null, null); 11321 11322 /* 11323 * We don't want the copy to proceed until verification 11324 * succeeds, so null out this field. 11325 */ 11326 mArgs = null; 11327 } 11328 } else { 11329 /* 11330 * No package verification is enabled, so immediately start 11331 * the remote call to initiate copy using temporary file. 11332 */ 11333 ret = args.copyApk(mContainerService, true); 11334 } 11335 } 11336 11337 mRet = ret; 11338 } 11339 11340 @Override 11341 void handleReturnCode() { 11342 // If mArgs is null, then MCS couldn't be reached. When it 11343 // reconnects, it will try again to install. At that point, this 11344 // will succeed. 11345 if (mArgs != null) { 11346 processPendingInstall(mArgs, mRet); 11347 } 11348 } 11349 11350 @Override 11351 void handleServiceError() { 11352 mArgs = createInstallArgs(this); 11353 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11354 } 11355 11356 public boolean isForwardLocked() { 11357 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11358 } 11359 } 11360 11361 /** 11362 * Used during creation of InstallArgs 11363 * 11364 * @param installFlags package installation flags 11365 * @return true if should be installed on external storage 11366 */ 11367 private static boolean installOnExternalAsec(int installFlags) { 11368 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 11369 return false; 11370 } 11371 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 11372 return true; 11373 } 11374 return false; 11375 } 11376 11377 /** 11378 * Used during creation of InstallArgs 11379 * 11380 * @param installFlags package installation flags 11381 * @return true if should be installed as forward locked 11382 */ 11383 private static boolean installForwardLocked(int installFlags) { 11384 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11385 } 11386 11387 private InstallArgs createInstallArgs(InstallParams params) { 11388 if (params.move != null) { 11389 return new MoveInstallArgs(params); 11390 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 11391 return new AsecInstallArgs(params); 11392 } else { 11393 return new FileInstallArgs(params); 11394 } 11395 } 11396 11397 /** 11398 * Create args that describe an existing installed package. Typically used 11399 * when cleaning up old installs, or used as a move source. 11400 */ 11401 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 11402 String resourcePath, String[] instructionSets) { 11403 final boolean isInAsec; 11404 if (installOnExternalAsec(installFlags)) { 11405 /* Apps on SD card are always in ASEC containers. */ 11406 isInAsec = true; 11407 } else if (installForwardLocked(installFlags) 11408 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 11409 /* 11410 * Forward-locked apps are only in ASEC containers if they're the 11411 * new style 11412 */ 11413 isInAsec = true; 11414 } else { 11415 isInAsec = false; 11416 } 11417 11418 if (isInAsec) { 11419 return new AsecInstallArgs(codePath, instructionSets, 11420 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 11421 } else { 11422 return new FileInstallArgs(codePath, resourcePath, instructionSets); 11423 } 11424 } 11425 11426 static abstract class InstallArgs { 11427 /** @see InstallParams#origin */ 11428 final OriginInfo origin; 11429 /** @see InstallParams#move */ 11430 final MoveInfo move; 11431 11432 final IPackageInstallObserver2 observer; 11433 // Always refers to PackageManager flags only 11434 final int installFlags; 11435 final String installerPackageName; 11436 final String volumeUuid; 11437 final UserHandle user; 11438 final String abiOverride; 11439 final String[] installGrantPermissions; 11440 /** If non-null, drop an async trace when the install completes */ 11441 final String traceMethod; 11442 final int traceCookie; 11443 11444 // The list of instruction sets supported by this app. This is currently 11445 // only used during the rmdex() phase to clean up resources. We can get rid of this 11446 // if we move dex files under the common app path. 11447 /* nullable */ String[] instructionSets; 11448 11449 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11450 int installFlags, String installerPackageName, String volumeUuid, 11451 UserHandle user, String[] instructionSets, 11452 String abiOverride, String[] installGrantPermissions, 11453 String traceMethod, int traceCookie) { 11454 this.origin = origin; 11455 this.move = move; 11456 this.installFlags = installFlags; 11457 this.observer = observer; 11458 this.installerPackageName = installerPackageName; 11459 this.volumeUuid = volumeUuid; 11460 this.user = user; 11461 this.instructionSets = instructionSets; 11462 this.abiOverride = abiOverride; 11463 this.installGrantPermissions = installGrantPermissions; 11464 this.traceMethod = traceMethod; 11465 this.traceCookie = traceCookie; 11466 } 11467 11468 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 11469 abstract int doPreInstall(int status); 11470 11471 /** 11472 * Rename package into final resting place. All paths on the given 11473 * scanned package should be updated to reflect the rename. 11474 */ 11475 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 11476 abstract int doPostInstall(int status, int uid); 11477 11478 /** @see PackageSettingBase#codePathString */ 11479 abstract String getCodePath(); 11480 /** @see PackageSettingBase#resourcePathString */ 11481 abstract String getResourcePath(); 11482 11483 // Need installer lock especially for dex file removal. 11484 abstract void cleanUpResourcesLI(); 11485 abstract boolean doPostDeleteLI(boolean delete); 11486 11487 /** 11488 * Called before the source arguments are copied. This is used mostly 11489 * for MoveParams when it needs to read the source file to put it in the 11490 * destination. 11491 */ 11492 int doPreCopy() { 11493 return PackageManager.INSTALL_SUCCEEDED; 11494 } 11495 11496 /** 11497 * Called after the source arguments are copied. This is used mostly for 11498 * MoveParams when it needs to read the source file to put it in the 11499 * destination. 11500 * 11501 * @return 11502 */ 11503 int doPostCopy(int uid) { 11504 return PackageManager.INSTALL_SUCCEEDED; 11505 } 11506 11507 protected boolean isFwdLocked() { 11508 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11509 } 11510 11511 protected boolean isExternalAsec() { 11512 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11513 } 11514 11515 protected boolean isEphemeral() { 11516 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11517 } 11518 11519 UserHandle getUser() { 11520 return user; 11521 } 11522 } 11523 11524 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 11525 if (!allCodePaths.isEmpty()) { 11526 if (instructionSets == null) { 11527 throw new IllegalStateException("instructionSet == null"); 11528 } 11529 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11530 for (String codePath : allCodePaths) { 11531 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11532 try { 11533 mInstaller.rmdex(codePath, dexCodeInstructionSet); 11534 } catch (InstallerException ignored) { 11535 } 11536 } 11537 } 11538 } 11539 } 11540 11541 /** 11542 * Logic to handle installation of non-ASEC applications, including copying 11543 * and renaming logic. 11544 */ 11545 class FileInstallArgs extends InstallArgs { 11546 private File codeFile; 11547 private File resourceFile; 11548 11549 // Example topology: 11550 // /data/app/com.example/base.apk 11551 // /data/app/com.example/split_foo.apk 11552 // /data/app/com.example/lib/arm/libfoo.so 11553 // /data/app/com.example/lib/arm64/libfoo.so 11554 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11555 11556 /** New install */ 11557 FileInstallArgs(InstallParams params) { 11558 super(params.origin, params.move, params.observer, params.installFlags, 11559 params.installerPackageName, params.volumeUuid, 11560 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11561 params.grantedRuntimePermissions, 11562 params.traceMethod, params.traceCookie); 11563 if (isFwdLocked()) { 11564 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11565 } 11566 } 11567 11568 /** Existing install */ 11569 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11570 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 11571 null, null, null, 0); 11572 this.codeFile = (codePath != null) ? new File(codePath) : null; 11573 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11574 } 11575 11576 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11577 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 11578 try { 11579 return doCopyApk(imcs, temp); 11580 } finally { 11581 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11582 } 11583 } 11584 11585 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11586 if (origin.staged) { 11587 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11588 codeFile = origin.file; 11589 resourceFile = origin.file; 11590 return PackageManager.INSTALL_SUCCEEDED; 11591 } 11592 11593 try { 11594 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11595 final File tempDir = 11596 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 11597 codeFile = tempDir; 11598 resourceFile = tempDir; 11599 } catch (IOException e) { 11600 Slog.w(TAG, "Failed to create copy file: " + e); 11601 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11602 } 11603 11604 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11605 @Override 11606 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11607 if (!FileUtils.isValidExtFilename(name)) { 11608 throw new IllegalArgumentException("Invalid filename: " + name); 11609 } 11610 try { 11611 final File file = new File(codeFile, name); 11612 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11613 O_RDWR | O_CREAT, 0644); 11614 Os.chmod(file.getAbsolutePath(), 0644); 11615 return new ParcelFileDescriptor(fd); 11616 } catch (ErrnoException e) { 11617 throw new RemoteException("Failed to open: " + e.getMessage()); 11618 } 11619 } 11620 }; 11621 11622 int ret = PackageManager.INSTALL_SUCCEEDED; 11623 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11624 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11625 Slog.e(TAG, "Failed to copy package"); 11626 return ret; 11627 } 11628 11629 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11630 NativeLibraryHelper.Handle handle = null; 11631 try { 11632 handle = NativeLibraryHelper.Handle.create(codeFile); 11633 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11634 abiOverride); 11635 } catch (IOException e) { 11636 Slog.e(TAG, "Copying native libraries failed", e); 11637 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11638 } finally { 11639 IoUtils.closeQuietly(handle); 11640 } 11641 11642 return ret; 11643 } 11644 11645 int doPreInstall(int status) { 11646 if (status != PackageManager.INSTALL_SUCCEEDED) { 11647 cleanUp(); 11648 } 11649 return status; 11650 } 11651 11652 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11653 if (status != PackageManager.INSTALL_SUCCEEDED) { 11654 cleanUp(); 11655 return false; 11656 } 11657 11658 final File targetDir = codeFile.getParentFile(); 11659 final File beforeCodeFile = codeFile; 11660 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11661 11662 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11663 try { 11664 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11665 } catch (ErrnoException e) { 11666 Slog.w(TAG, "Failed to rename", e); 11667 return false; 11668 } 11669 11670 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11671 Slog.w(TAG, "Failed to restorecon"); 11672 return false; 11673 } 11674 11675 // Reflect the rename internally 11676 codeFile = afterCodeFile; 11677 resourceFile = afterCodeFile; 11678 11679 // Reflect the rename in scanned details 11680 pkg.codePath = afterCodeFile.getAbsolutePath(); 11681 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11682 pkg.baseCodePath); 11683 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11684 pkg.splitCodePaths); 11685 11686 // Reflect the rename in app info 11687 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11688 pkg.applicationInfo.setCodePath(pkg.codePath); 11689 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11690 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11691 pkg.applicationInfo.setResourcePath(pkg.codePath); 11692 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11693 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11694 11695 return true; 11696 } 11697 11698 int doPostInstall(int status, int uid) { 11699 if (status != PackageManager.INSTALL_SUCCEEDED) { 11700 cleanUp(); 11701 } 11702 return status; 11703 } 11704 11705 @Override 11706 String getCodePath() { 11707 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11708 } 11709 11710 @Override 11711 String getResourcePath() { 11712 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11713 } 11714 11715 private boolean cleanUp() { 11716 if (codeFile == null || !codeFile.exists()) { 11717 return false; 11718 } 11719 11720 removeCodePathLI(codeFile); 11721 11722 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11723 resourceFile.delete(); 11724 } 11725 11726 return true; 11727 } 11728 11729 void cleanUpResourcesLI() { 11730 // Try enumerating all code paths before deleting 11731 List<String> allCodePaths = Collections.EMPTY_LIST; 11732 if (codeFile != null && codeFile.exists()) { 11733 try { 11734 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11735 allCodePaths = pkg.getAllCodePaths(); 11736 } catch (PackageParserException e) { 11737 // Ignored; we tried our best 11738 } 11739 } 11740 11741 cleanUp(); 11742 removeDexFiles(allCodePaths, instructionSets); 11743 } 11744 11745 boolean doPostDeleteLI(boolean delete) { 11746 // XXX err, shouldn't we respect the delete flag? 11747 cleanUpResourcesLI(); 11748 return true; 11749 } 11750 } 11751 11752 private boolean isAsecExternal(String cid) { 11753 final String asecPath = PackageHelper.getSdFilesystem(cid); 11754 return !asecPath.startsWith(mAsecInternalPath); 11755 } 11756 11757 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11758 PackageManagerException { 11759 if (copyRet < 0) { 11760 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11761 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11762 throw new PackageManagerException(copyRet, message); 11763 } 11764 } 11765 } 11766 11767 /** 11768 * Extract the MountService "container ID" from the full code path of an 11769 * .apk. 11770 */ 11771 static String cidFromCodePath(String fullCodePath) { 11772 int eidx = fullCodePath.lastIndexOf("/"); 11773 String subStr1 = fullCodePath.substring(0, eidx); 11774 int sidx = subStr1.lastIndexOf("/"); 11775 return subStr1.substring(sidx+1, eidx); 11776 } 11777 11778 /** 11779 * Logic to handle installation of ASEC applications, including copying and 11780 * renaming logic. 11781 */ 11782 class AsecInstallArgs extends InstallArgs { 11783 static final String RES_FILE_NAME = "pkg.apk"; 11784 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11785 11786 String cid; 11787 String packagePath; 11788 String resourcePath; 11789 11790 /** New install */ 11791 AsecInstallArgs(InstallParams params) { 11792 super(params.origin, params.move, params.observer, params.installFlags, 11793 params.installerPackageName, params.volumeUuid, 11794 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11795 params.grantedRuntimePermissions, 11796 params.traceMethod, params.traceCookie); 11797 } 11798 11799 /** Existing install */ 11800 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11801 boolean isExternal, boolean isForwardLocked) { 11802 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11803 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 11804 instructionSets, null, null, null, 0); 11805 // Hackily pretend we're still looking at a full code path 11806 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11807 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11808 } 11809 11810 // Extract cid from fullCodePath 11811 int eidx = fullCodePath.lastIndexOf("/"); 11812 String subStr1 = fullCodePath.substring(0, eidx); 11813 int sidx = subStr1.lastIndexOf("/"); 11814 cid = subStr1.substring(sidx+1, eidx); 11815 setMountPath(subStr1); 11816 } 11817 11818 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11819 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11820 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 11821 instructionSets, null, null, null, 0); 11822 this.cid = cid; 11823 setMountPath(PackageHelper.getSdDir(cid)); 11824 } 11825 11826 void createCopyFile() { 11827 cid = mInstallerService.allocateExternalStageCidLegacy(); 11828 } 11829 11830 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11831 if (origin.staged && origin.cid != null) { 11832 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11833 cid = origin.cid; 11834 setMountPath(PackageHelper.getSdDir(cid)); 11835 return PackageManager.INSTALL_SUCCEEDED; 11836 } 11837 11838 if (temp) { 11839 createCopyFile(); 11840 } else { 11841 /* 11842 * Pre-emptively destroy the container since it's destroyed if 11843 * copying fails due to it existing anyway. 11844 */ 11845 PackageHelper.destroySdDir(cid); 11846 } 11847 11848 final String newMountPath = imcs.copyPackageToContainer( 11849 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11850 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11851 11852 if (newMountPath != null) { 11853 setMountPath(newMountPath); 11854 return PackageManager.INSTALL_SUCCEEDED; 11855 } else { 11856 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11857 } 11858 } 11859 11860 @Override 11861 String getCodePath() { 11862 return packagePath; 11863 } 11864 11865 @Override 11866 String getResourcePath() { 11867 return resourcePath; 11868 } 11869 11870 int doPreInstall(int status) { 11871 if (status != PackageManager.INSTALL_SUCCEEDED) { 11872 // Destroy container 11873 PackageHelper.destroySdDir(cid); 11874 } else { 11875 boolean mounted = PackageHelper.isContainerMounted(cid); 11876 if (!mounted) { 11877 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11878 Process.SYSTEM_UID); 11879 if (newMountPath != null) { 11880 setMountPath(newMountPath); 11881 } else { 11882 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11883 } 11884 } 11885 } 11886 return status; 11887 } 11888 11889 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11890 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11891 String newMountPath = null; 11892 if (PackageHelper.isContainerMounted(cid)) { 11893 // Unmount the container 11894 if (!PackageHelper.unMountSdDir(cid)) { 11895 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11896 return false; 11897 } 11898 } 11899 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11900 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11901 " which might be stale. Will try to clean up."); 11902 // Clean up the stale container and proceed to recreate. 11903 if (!PackageHelper.destroySdDir(newCacheId)) { 11904 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11905 return false; 11906 } 11907 // Successfully cleaned up stale container. Try to rename again. 11908 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11909 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11910 + " inspite of cleaning it up."); 11911 return false; 11912 } 11913 } 11914 if (!PackageHelper.isContainerMounted(newCacheId)) { 11915 Slog.w(TAG, "Mounting container " + newCacheId); 11916 newMountPath = PackageHelper.mountSdDir(newCacheId, 11917 getEncryptKey(), Process.SYSTEM_UID); 11918 } else { 11919 newMountPath = PackageHelper.getSdDir(newCacheId); 11920 } 11921 if (newMountPath == null) { 11922 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11923 return false; 11924 } 11925 Log.i(TAG, "Succesfully renamed " + cid + 11926 " to " + newCacheId + 11927 " at new path: " + newMountPath); 11928 cid = newCacheId; 11929 11930 final File beforeCodeFile = new File(packagePath); 11931 setMountPath(newMountPath); 11932 final File afterCodeFile = new File(packagePath); 11933 11934 // Reflect the rename in scanned details 11935 pkg.codePath = afterCodeFile.getAbsolutePath(); 11936 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11937 pkg.baseCodePath); 11938 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11939 pkg.splitCodePaths); 11940 11941 // Reflect the rename in app info 11942 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11943 pkg.applicationInfo.setCodePath(pkg.codePath); 11944 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11945 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11946 pkg.applicationInfo.setResourcePath(pkg.codePath); 11947 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11948 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11949 11950 return true; 11951 } 11952 11953 private void setMountPath(String mountPath) { 11954 final File mountFile = new File(mountPath); 11955 11956 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11957 if (monolithicFile.exists()) { 11958 packagePath = monolithicFile.getAbsolutePath(); 11959 if (isFwdLocked()) { 11960 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11961 } else { 11962 resourcePath = packagePath; 11963 } 11964 } else { 11965 packagePath = mountFile.getAbsolutePath(); 11966 resourcePath = packagePath; 11967 } 11968 } 11969 11970 int doPostInstall(int status, int uid) { 11971 if (status != PackageManager.INSTALL_SUCCEEDED) { 11972 cleanUp(); 11973 } else { 11974 final int groupOwner; 11975 final String protectedFile; 11976 if (isFwdLocked()) { 11977 groupOwner = UserHandle.getSharedAppGid(uid); 11978 protectedFile = RES_FILE_NAME; 11979 } else { 11980 groupOwner = -1; 11981 protectedFile = null; 11982 } 11983 11984 if (uid < Process.FIRST_APPLICATION_UID 11985 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11986 Slog.e(TAG, "Failed to finalize " + cid); 11987 PackageHelper.destroySdDir(cid); 11988 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11989 } 11990 11991 boolean mounted = PackageHelper.isContainerMounted(cid); 11992 if (!mounted) { 11993 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11994 } 11995 } 11996 return status; 11997 } 11998 11999 private void cleanUp() { 12000 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 12001 12002 // Destroy secure container 12003 PackageHelper.destroySdDir(cid); 12004 } 12005 12006 private List<String> getAllCodePaths() { 12007 final File codeFile = new File(getCodePath()); 12008 if (codeFile != null && codeFile.exists()) { 12009 try { 12010 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12011 return pkg.getAllCodePaths(); 12012 } catch (PackageParserException e) { 12013 // Ignored; we tried our best 12014 } 12015 } 12016 return Collections.EMPTY_LIST; 12017 } 12018 12019 void cleanUpResourcesLI() { 12020 // Enumerate all code paths before deleting 12021 cleanUpResourcesLI(getAllCodePaths()); 12022 } 12023 12024 private void cleanUpResourcesLI(List<String> allCodePaths) { 12025 cleanUp(); 12026 removeDexFiles(allCodePaths, instructionSets); 12027 } 12028 12029 String getPackageName() { 12030 return getAsecPackageName(cid); 12031 } 12032 12033 boolean doPostDeleteLI(boolean delete) { 12034 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 12035 final List<String> allCodePaths = getAllCodePaths(); 12036 boolean mounted = PackageHelper.isContainerMounted(cid); 12037 if (mounted) { 12038 // Unmount first 12039 if (PackageHelper.unMountSdDir(cid)) { 12040 mounted = false; 12041 } 12042 } 12043 if (!mounted && delete) { 12044 cleanUpResourcesLI(allCodePaths); 12045 } 12046 return !mounted; 12047 } 12048 12049 @Override 12050 int doPreCopy() { 12051 if (isFwdLocked()) { 12052 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 12053 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 12054 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12055 } 12056 } 12057 12058 return PackageManager.INSTALL_SUCCEEDED; 12059 } 12060 12061 @Override 12062 int doPostCopy(int uid) { 12063 if (isFwdLocked()) { 12064 if (uid < Process.FIRST_APPLICATION_UID 12065 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 12066 RES_FILE_NAME)) { 12067 Slog.e(TAG, "Failed to finalize " + cid); 12068 PackageHelper.destroySdDir(cid); 12069 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12070 } 12071 } 12072 12073 return PackageManager.INSTALL_SUCCEEDED; 12074 } 12075 } 12076 12077 /** 12078 * Logic to handle movement of existing installed applications. 12079 */ 12080 class MoveInstallArgs extends InstallArgs { 12081 private File codeFile; 12082 private File resourceFile; 12083 12084 /** New install */ 12085 MoveInstallArgs(InstallParams params) { 12086 super(params.origin, params.move, params.observer, params.installFlags, 12087 params.installerPackageName, params.volumeUuid, 12088 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12089 params.grantedRuntimePermissions, 12090 params.traceMethod, params.traceCookie); 12091 } 12092 12093 int copyApk(IMediaContainerService imcs, boolean temp) { 12094 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 12095 + move.fromUuid + " to " + move.toUuid); 12096 synchronized (mInstaller) { 12097 try { 12098 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 12099 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 12100 } catch (InstallerException e) { 12101 Slog.w(TAG, "Failed to move app", e); 12102 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12103 } 12104 } 12105 12106 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 12107 resourceFile = codeFile; 12108 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 12109 12110 return PackageManager.INSTALL_SUCCEEDED; 12111 } 12112 12113 int doPreInstall(int status) { 12114 if (status != PackageManager.INSTALL_SUCCEEDED) { 12115 cleanUp(move.toUuid); 12116 } 12117 return status; 12118 } 12119 12120 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12121 if (status != PackageManager.INSTALL_SUCCEEDED) { 12122 cleanUp(move.toUuid); 12123 return false; 12124 } 12125 12126 // Reflect the move in app info 12127 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 12128 pkg.applicationInfo.setCodePath(pkg.codePath); 12129 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 12130 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 12131 pkg.applicationInfo.setResourcePath(pkg.codePath); 12132 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 12133 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 12134 12135 return true; 12136 } 12137 12138 int doPostInstall(int status, int uid) { 12139 if (status == PackageManager.INSTALL_SUCCEEDED) { 12140 cleanUp(move.fromUuid); 12141 } else { 12142 cleanUp(move.toUuid); 12143 } 12144 return status; 12145 } 12146 12147 @Override 12148 String getCodePath() { 12149 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12150 } 12151 12152 @Override 12153 String getResourcePath() { 12154 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12155 } 12156 12157 private boolean cleanUp(String volumeUuid) { 12158 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 12159 move.dataAppName); 12160 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 12161 synchronized (mInstallLock) { 12162 // Clean up both app data and code 12163 removeDataDirsLI(volumeUuid, move.packageName); 12164 removeCodePathLI(codeFile); 12165 } 12166 return true; 12167 } 12168 12169 void cleanUpResourcesLI() { 12170 throw new UnsupportedOperationException(); 12171 } 12172 12173 boolean doPostDeleteLI(boolean delete) { 12174 throw new UnsupportedOperationException(); 12175 } 12176 } 12177 12178 static String getAsecPackageName(String packageCid) { 12179 int idx = packageCid.lastIndexOf("-"); 12180 if (idx == -1) { 12181 return packageCid; 12182 } 12183 return packageCid.substring(0, idx); 12184 } 12185 12186 // Utility method used to create code paths based on package name and available index. 12187 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 12188 String idxStr = ""; 12189 int idx = 1; 12190 // Fall back to default value of idx=1 if prefix is not 12191 // part of oldCodePath 12192 if (oldCodePath != null) { 12193 String subStr = oldCodePath; 12194 // Drop the suffix right away 12195 if (suffix != null && subStr.endsWith(suffix)) { 12196 subStr = subStr.substring(0, subStr.length() - suffix.length()); 12197 } 12198 // If oldCodePath already contains prefix find out the 12199 // ending index to either increment or decrement. 12200 int sidx = subStr.lastIndexOf(prefix); 12201 if (sidx != -1) { 12202 subStr = subStr.substring(sidx + prefix.length()); 12203 if (subStr != null) { 12204 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 12205 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 12206 } 12207 try { 12208 idx = Integer.parseInt(subStr); 12209 if (idx <= 1) { 12210 idx++; 12211 } else { 12212 idx--; 12213 } 12214 } catch(NumberFormatException e) { 12215 } 12216 } 12217 } 12218 } 12219 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 12220 return prefix + idxStr; 12221 } 12222 12223 private File getNextCodePath(File targetDir, String packageName) { 12224 int suffix = 1; 12225 File result; 12226 do { 12227 result = new File(targetDir, packageName + "-" + suffix); 12228 suffix++; 12229 } while (result.exists()); 12230 return result; 12231 } 12232 12233 // Utility method that returns the relative package path with respect 12234 // to the installation directory. Like say for /data/data/com.test-1.apk 12235 // string com.test-1 is returned. 12236 static String deriveCodePathName(String codePath) { 12237 if (codePath == null) { 12238 return null; 12239 } 12240 final File codeFile = new File(codePath); 12241 final String name = codeFile.getName(); 12242 if (codeFile.isDirectory()) { 12243 return name; 12244 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 12245 final int lastDot = name.lastIndexOf('.'); 12246 return name.substring(0, lastDot); 12247 } else { 12248 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 12249 return null; 12250 } 12251 } 12252 12253 static class PackageInstalledInfo { 12254 String name; 12255 int uid; 12256 // The set of users that originally had this package installed. 12257 int[] origUsers; 12258 // The set of users that now have this package installed. 12259 int[] newUsers; 12260 PackageParser.Package pkg; 12261 int returnCode; 12262 String returnMsg; 12263 PackageRemovedInfo removedInfo; 12264 12265 public void setError(int code, String msg) { 12266 returnCode = code; 12267 returnMsg = msg; 12268 Slog.w(TAG, msg); 12269 } 12270 12271 public void setError(String msg, PackageParserException e) { 12272 returnCode = e.error; 12273 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12274 Slog.w(TAG, msg, e); 12275 } 12276 12277 public void setError(String msg, PackageManagerException e) { 12278 returnCode = e.error; 12279 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12280 Slog.w(TAG, msg, e); 12281 } 12282 12283 // In some error cases we want to convey more info back to the observer 12284 String origPackage; 12285 String origPermission; 12286 } 12287 12288 /* 12289 * Install a non-existing package. 12290 */ 12291 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12292 UserHandle user, String installerPackageName, String volumeUuid, 12293 PackageInstalledInfo res) { 12294 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 12295 12296 // Remember this for later, in case we need to rollback this install 12297 String pkgName = pkg.packageName; 12298 12299 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 12300 // TODO: b/23350563 12301 final boolean dataDirExists = Environment 12302 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists(); 12303 12304 synchronized(mPackages) { 12305 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 12306 // A package with the same name is already installed, though 12307 // it has been renamed to an older name. The package we 12308 // are trying to install should be installed as an update to 12309 // the existing one, but that has not been requested, so bail. 12310 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12311 + " without first uninstalling package running as " 12312 + mSettings.mRenamedPackages.get(pkgName)); 12313 return; 12314 } 12315 if (mPackages.containsKey(pkgName)) { 12316 // Don't allow installation over an existing package with the same name. 12317 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12318 + " without first uninstalling."); 12319 return; 12320 } 12321 } 12322 12323 try { 12324 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 12325 System.currentTimeMillis(), user); 12326 12327 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 12328 prepareAppDataAfterInstall(newPackage); 12329 12330 // delete the partially installed application. the data directory will have to be 12331 // restored if it was already existing 12332 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12333 // remove package from internal structures. Note that we want deletePackageX to 12334 // delete the package data and cache directories that it created in 12335 // scanPackageLocked, unless those directories existed before we even tried to 12336 // install. 12337 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 12338 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 12339 res.removedInfo, true); 12340 } 12341 12342 } catch (PackageManagerException e) { 12343 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12344 } 12345 12346 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12347 } 12348 12349 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 12350 // Can't rotate keys during boot or if sharedUser. 12351 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 12352 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 12353 return false; 12354 } 12355 // app is using upgradeKeySets; make sure all are valid 12356 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12357 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 12358 for (int i = 0; i < upgradeKeySets.length; i++) { 12359 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 12360 Slog.wtf(TAG, "Package " 12361 + (oldPs.name != null ? oldPs.name : "<null>") 12362 + " contains upgrade-key-set reference to unknown key-set: " 12363 + upgradeKeySets[i] 12364 + " reverting to signatures check."); 12365 return false; 12366 } 12367 } 12368 return true; 12369 } 12370 12371 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 12372 // Upgrade keysets are being used. Determine if new package has a superset of the 12373 // required keys. 12374 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 12375 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12376 for (int i = 0; i < upgradeKeySets.length; i++) { 12377 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 12378 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 12379 return true; 12380 } 12381 } 12382 return false; 12383 } 12384 12385 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12386 UserHandle user, String installerPackageName, String volumeUuid, 12387 PackageInstalledInfo res) { 12388 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 12389 12390 final PackageParser.Package oldPackage; 12391 final String pkgName = pkg.packageName; 12392 final int[] allUsers; 12393 final boolean[] perUserInstalled; 12394 12395 // First find the old package info and check signatures 12396 synchronized(mPackages) { 12397 oldPackage = mPackages.get(pkgName); 12398 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 12399 if (isEphemeral && !oldIsEphemeral) { 12400 // can't downgrade from full to ephemeral 12401 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 12402 res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 12403 return; 12404 } 12405 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 12406 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12407 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12408 if(!checkUpgradeKeySetLP(ps, pkg)) { 12409 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12410 "New package not signed by keys specified by upgrade-keysets: " 12411 + pkgName); 12412 return; 12413 } 12414 } else { 12415 // default to original signature matching 12416 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 12417 != PackageManager.SIGNATURE_MATCH) { 12418 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12419 "New package has a different signature: " + pkgName); 12420 return; 12421 } 12422 } 12423 12424 // In case of rollback, remember per-user/profile install state 12425 allUsers = sUserManager.getUserIds(); 12426 perUserInstalled = new boolean[allUsers.length]; 12427 for (int i = 0; i < allUsers.length; i++) { 12428 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12429 } 12430 } 12431 12432 boolean sysPkg = (isSystemApp(oldPackage)); 12433 if (sysPkg) { 12434 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12435 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12436 } else { 12437 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12438 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12439 } 12440 } 12441 12442 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 12443 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12444 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12445 String volumeUuid, PackageInstalledInfo res) { 12446 String pkgName = deletedPackage.packageName; 12447 boolean deletedPkg = true; 12448 boolean updatedSettings = false; 12449 12450 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 12451 + deletedPackage); 12452 long origUpdateTime; 12453 if (pkg.mExtras != null) { 12454 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 12455 } else { 12456 origUpdateTime = 0; 12457 } 12458 12459 // First delete the existing package while retaining the data directory 12460 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 12461 res.removedInfo, true)) { 12462 // If the existing package wasn't successfully deleted 12463 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 12464 deletedPkg = false; 12465 } else { 12466 // Successfully deleted the old package; proceed with replace. 12467 12468 // If deleted package lived in a container, give users a chance to 12469 // relinquish resources before killing. 12470 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 12471 if (DEBUG_INSTALL) { 12472 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 12473 } 12474 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 12475 final ArrayList<String> pkgList = new ArrayList<String>(1); 12476 pkgList.add(deletedPackage.applicationInfo.packageName); 12477 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 12478 } 12479 12480 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 12481 try { 12482 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 12483 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 12484 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12485 perUserInstalled, res, user); 12486 prepareAppDataAfterInstall(newPackage); 12487 updatedSettings = true; 12488 } catch (PackageManagerException e) { 12489 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12490 } 12491 } 12492 12493 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12494 // remove package from internal structures. Note that we want deletePackageX to 12495 // delete the package data and cache directories that it created in 12496 // scanPackageLocked, unless those directories existed before we even tried to 12497 // install. 12498 if(updatedSettings) { 12499 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 12500 deletePackageLI( 12501 pkgName, null, true, allUsers, perUserInstalled, 12502 PackageManager.DELETE_KEEP_DATA, 12503 res.removedInfo, true); 12504 } 12505 // Since we failed to install the new package we need to restore the old 12506 // package that we deleted. 12507 if (deletedPkg) { 12508 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 12509 File restoreFile = new File(deletedPackage.codePath); 12510 // Parse old package 12511 boolean oldExternal = isExternal(deletedPackage); 12512 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 12513 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 12514 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12515 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 12516 try { 12517 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 12518 null); 12519 } catch (PackageManagerException e) { 12520 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 12521 + e.getMessage()); 12522 return; 12523 } 12524 // Restore of old package succeeded. Update permissions. 12525 // writer 12526 synchronized (mPackages) { 12527 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 12528 UPDATE_PERMISSIONS_ALL); 12529 // can downgrade to reader 12530 mSettings.writeLPr(); 12531 } 12532 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 12533 } 12534 } 12535 } 12536 12537 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 12538 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12539 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12540 String volumeUuid, PackageInstalledInfo res) { 12541 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 12542 + ", old=" + deletedPackage); 12543 boolean disabledSystem = false; 12544 boolean updatedSettings = false; 12545 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 12546 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 12547 != 0) { 12548 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12549 } 12550 String packageName = deletedPackage.packageName; 12551 if (packageName == null) { 12552 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12553 "Attempt to delete null packageName."); 12554 return; 12555 } 12556 PackageParser.Package oldPkg; 12557 PackageSetting oldPkgSetting; 12558 // reader 12559 synchronized (mPackages) { 12560 oldPkg = mPackages.get(packageName); 12561 oldPkgSetting = mSettings.mPackages.get(packageName); 12562 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 12563 (oldPkgSetting == null)) { 12564 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12565 "Couldn't find package " + packageName + " information"); 12566 return; 12567 } 12568 } 12569 12570 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12571 12572 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12573 res.removedInfo.removedPackage = packageName; 12574 // Remove existing system package 12575 removePackageLI(oldPkgSetting, true); 12576 // writer 12577 synchronized (mPackages) { 12578 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12579 if (!disabledSystem && deletedPackage != null) { 12580 // We didn't need to disable the .apk as a current system package, 12581 // which means we are replacing another update that is already 12582 // installed. We need to make sure to delete the older one's .apk. 12583 res.removedInfo.args = createInstallArgsForExisting(0, 12584 deletedPackage.applicationInfo.getCodePath(), 12585 deletedPackage.applicationInfo.getResourcePath(), 12586 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12587 } else { 12588 res.removedInfo.args = null; 12589 } 12590 } 12591 12592 // Successfully disabled the old package. Now proceed with re-installation 12593 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12594 12595 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12596 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12597 12598 PackageParser.Package newPackage = null; 12599 try { 12600 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 12601 if (newPackage.mExtras != null) { 12602 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12603 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12604 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12605 12606 // is the update attempting to change shared user? that isn't going to work... 12607 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12608 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12609 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12610 + " to " + newPkgSetting.sharedUser); 12611 updatedSettings = true; 12612 } 12613 } 12614 12615 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12616 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12617 perUserInstalled, res, user); 12618 prepareAppDataAfterInstall(newPackage); 12619 updatedSettings = true; 12620 } 12621 12622 } catch (PackageManagerException e) { 12623 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12624 } 12625 12626 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12627 // Re installation failed. Restore old information 12628 // Remove new pkg information 12629 if (newPackage != null) { 12630 removeInstalledPackageLI(newPackage, true); 12631 } 12632 // Add back the old system package 12633 try { 12634 scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12635 } catch (PackageManagerException e) { 12636 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12637 } 12638 // Restore the old system information in Settings 12639 synchronized (mPackages) { 12640 if (disabledSystem) { 12641 mSettings.enableSystemPackageLPw(packageName); 12642 } 12643 if (updatedSettings) { 12644 mSettings.setInstallerPackageName(packageName, 12645 oldPkgSetting.installerPackageName); 12646 } 12647 mSettings.writeLPr(); 12648 } 12649 } 12650 } 12651 12652 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 12653 // Collect all used permissions in the UID 12654 ArraySet<String> usedPermissions = new ArraySet<>(); 12655 final int packageCount = su.packages.size(); 12656 for (int i = 0; i < packageCount; i++) { 12657 PackageSetting ps = su.packages.valueAt(i); 12658 if (ps.pkg == null) { 12659 continue; 12660 } 12661 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 12662 for (int j = 0; j < requestedPermCount; j++) { 12663 String permission = ps.pkg.requestedPermissions.get(j); 12664 BasePermission bp = mSettings.mPermissions.get(permission); 12665 if (bp != null) { 12666 usedPermissions.add(permission); 12667 } 12668 } 12669 } 12670 12671 PermissionsState permissionsState = su.getPermissionsState(); 12672 // Prune install permissions 12673 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 12674 final int installPermCount = installPermStates.size(); 12675 for (int i = installPermCount - 1; i >= 0; i--) { 12676 PermissionState permissionState = installPermStates.get(i); 12677 if (!usedPermissions.contains(permissionState.getName())) { 12678 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12679 if (bp != null) { 12680 permissionsState.revokeInstallPermission(bp); 12681 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 12682 PackageManager.MASK_PERMISSION_FLAGS, 0); 12683 } 12684 } 12685 } 12686 12687 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 12688 12689 // Prune runtime permissions 12690 for (int userId : allUserIds) { 12691 List<PermissionState> runtimePermStates = permissionsState 12692 .getRuntimePermissionStates(userId); 12693 final int runtimePermCount = runtimePermStates.size(); 12694 for (int i = runtimePermCount - 1; i >= 0; i--) { 12695 PermissionState permissionState = runtimePermStates.get(i); 12696 if (!usedPermissions.contains(permissionState.getName())) { 12697 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12698 if (bp != null) { 12699 permissionsState.revokeRuntimePermission(bp, userId); 12700 permissionsState.updatePermissionFlags(bp, userId, 12701 PackageManager.MASK_PERMISSION_FLAGS, 0); 12702 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 12703 runtimePermissionChangedUserIds, userId); 12704 } 12705 } 12706 } 12707 } 12708 12709 return runtimePermissionChangedUserIds; 12710 } 12711 12712 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12713 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12714 UserHandle user) { 12715 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 12716 12717 String pkgName = newPackage.packageName; 12718 synchronized (mPackages) { 12719 //write settings. the installStatus will be incomplete at this stage. 12720 //note that the new package setting would have already been 12721 //added to mPackages. It hasn't been persisted yet. 12722 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12723 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12724 mSettings.writeLPr(); 12725 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12726 } 12727 12728 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12729 synchronized (mPackages) { 12730 updatePermissionsLPw(newPackage.packageName, newPackage, 12731 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12732 ? UPDATE_PERMISSIONS_ALL : 0)); 12733 // For system-bundled packages, we assume that installing an upgraded version 12734 // of the package implies that the user actually wants to run that new code, 12735 // so we enable the package. 12736 PackageSetting ps = mSettings.mPackages.get(pkgName); 12737 if (ps != null) { 12738 if (isSystemApp(newPackage)) { 12739 // NB: implicit assumption that system package upgrades apply to all users 12740 if (DEBUG_INSTALL) { 12741 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12742 } 12743 if (res.origUsers != null) { 12744 for (int userHandle : res.origUsers) { 12745 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12746 userHandle, installerPackageName); 12747 } 12748 } 12749 // Also convey the prior install/uninstall state 12750 if (allUsers != null && perUserInstalled != null) { 12751 for (int i = 0; i < allUsers.length; i++) { 12752 if (DEBUG_INSTALL) { 12753 Slog.d(TAG, " user " + allUsers[i] 12754 + " => " + perUserInstalled[i]); 12755 } 12756 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12757 } 12758 // these install state changes will be persisted in the 12759 // upcoming call to mSettings.writeLPr(). 12760 } 12761 } 12762 // It's implied that when a user requests installation, they want the app to be 12763 // installed and enabled. 12764 int userId = user.getIdentifier(); 12765 if (userId != UserHandle.USER_ALL) { 12766 ps.setInstalled(true, userId); 12767 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12768 } 12769 } 12770 res.name = pkgName; 12771 res.uid = newPackage.applicationInfo.uid; 12772 res.pkg = newPackage; 12773 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12774 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12775 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12776 //to update install status 12777 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12778 mSettings.writeLPr(); 12779 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12780 } 12781 12782 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12783 } 12784 12785 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 12786 try { 12787 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 12788 installPackageLI(args, res); 12789 } finally { 12790 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12791 } 12792 } 12793 12794 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12795 final int installFlags = args.installFlags; 12796 final String installerPackageName = args.installerPackageName; 12797 final String volumeUuid = args.volumeUuid; 12798 final File tmpPackageFile = new File(args.getCodePath()); 12799 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12800 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12801 || (args.volumeUuid != null)); 12802 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 12803 boolean replace = false; 12804 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12805 if (args.move != null) { 12806 // moving a complete application; perfom an initial scan on the new install location 12807 scanFlags |= SCAN_INITIAL; 12808 } 12809 // Result object to be returned 12810 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12811 12812 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12813 12814 // Sanity check 12815 if (ephemeral && (forwardLocked || onExternal)) { 12816 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 12817 + " external=" + onExternal); 12818 res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 12819 return; 12820 } 12821 12822 // Retrieve PackageSettings and parse package 12823 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12824 | PackageParser.PARSE_ENFORCE_CODE 12825 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12826 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 12827 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 12828 PackageParser pp = new PackageParser(); 12829 pp.setSeparateProcesses(mSeparateProcesses); 12830 pp.setDisplayMetrics(mMetrics); 12831 12832 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 12833 final PackageParser.Package pkg; 12834 try { 12835 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12836 } catch (PackageParserException e) { 12837 res.setError("Failed parse during installPackageLI", e); 12838 return; 12839 } finally { 12840 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12841 } 12842 12843 // Mark that we have an install time CPU ABI override. 12844 pkg.cpuAbiOverride = args.abiOverride; 12845 12846 String pkgName = res.name = pkg.packageName; 12847 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12848 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12849 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12850 return; 12851 } 12852 } 12853 12854 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 12855 try { 12856 pp.collectCertificates(pkg, parseFlags); 12857 } catch (PackageParserException e) { 12858 res.setError("Failed collect during installPackageLI", e); 12859 return; 12860 } finally { 12861 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12862 } 12863 12864 // Get rid of all references to package scan path via parser. 12865 pp = null; 12866 String oldCodePath = null; 12867 boolean systemApp = false; 12868 synchronized (mPackages) { 12869 // Check if installing already existing package 12870 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12871 String oldName = mSettings.mRenamedPackages.get(pkgName); 12872 if (pkg.mOriginalPackages != null 12873 && pkg.mOriginalPackages.contains(oldName) 12874 && mPackages.containsKey(oldName)) { 12875 // This package is derived from an original package, 12876 // and this device has been updating from that original 12877 // name. We must continue using the original name, so 12878 // rename the new package here. 12879 pkg.setPackageName(oldName); 12880 pkgName = pkg.packageName; 12881 replace = true; 12882 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12883 + oldName + " pkgName=" + pkgName); 12884 } else if (mPackages.containsKey(pkgName)) { 12885 // This package, under its official name, already exists 12886 // on the device; we should replace it. 12887 replace = true; 12888 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12889 } 12890 12891 // Prevent apps opting out from runtime permissions 12892 if (replace) { 12893 PackageParser.Package oldPackage = mPackages.get(pkgName); 12894 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12895 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12896 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12897 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12898 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12899 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12900 + " doesn't support runtime permissions but the old" 12901 + " target SDK " + oldTargetSdk + " does."); 12902 return; 12903 } 12904 } 12905 } 12906 12907 PackageSetting ps = mSettings.mPackages.get(pkgName); 12908 if (ps != null) { 12909 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12910 12911 // Quick sanity check that we're signed correctly if updating; 12912 // we'll check this again later when scanning, but we want to 12913 // bail early here before tripping over redefined permissions. 12914 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12915 if (!checkUpgradeKeySetLP(ps, pkg)) { 12916 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12917 + pkg.packageName + " upgrade keys do not match the " 12918 + "previously installed version"); 12919 return; 12920 } 12921 } else { 12922 try { 12923 verifySignaturesLP(ps, pkg); 12924 } catch (PackageManagerException e) { 12925 res.setError(e.error, e.getMessage()); 12926 return; 12927 } 12928 } 12929 12930 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12931 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12932 systemApp = (ps.pkg.applicationInfo.flags & 12933 ApplicationInfo.FLAG_SYSTEM) != 0; 12934 } 12935 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12936 } 12937 12938 // Check whether the newly-scanned package wants to define an already-defined perm 12939 int N = pkg.permissions.size(); 12940 for (int i = N-1; i >= 0; i--) { 12941 PackageParser.Permission perm = pkg.permissions.get(i); 12942 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12943 if (bp != null) { 12944 // If the defining package is signed with our cert, it's okay. This 12945 // also includes the "updating the same package" case, of course. 12946 // "updating same package" could also involve key-rotation. 12947 final boolean sigsOk; 12948 if (bp.sourcePackage.equals(pkg.packageName) 12949 && (bp.packageSetting instanceof PackageSetting) 12950 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12951 scanFlags))) { 12952 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12953 } else { 12954 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12955 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12956 } 12957 if (!sigsOk) { 12958 // If the owning package is the system itself, we log but allow 12959 // install to proceed; we fail the install on all other permission 12960 // redefinitions. 12961 if (!bp.sourcePackage.equals("android")) { 12962 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12963 + pkg.packageName + " attempting to redeclare permission " 12964 + perm.info.name + " already owned by " + bp.sourcePackage); 12965 res.origPermission = perm.info.name; 12966 res.origPackage = bp.sourcePackage; 12967 return; 12968 } else { 12969 Slog.w(TAG, "Package " + pkg.packageName 12970 + " attempting to redeclare system permission " 12971 + perm.info.name + "; ignoring new declaration"); 12972 pkg.permissions.remove(i); 12973 } 12974 } 12975 } 12976 } 12977 12978 } 12979 12980 if (systemApp) { 12981 if (onExternal) { 12982 // Abort update; system app can't be replaced with app on sdcard 12983 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12984 "Cannot install updates to system apps on sdcard"); 12985 return; 12986 } else if (ephemeral) { 12987 // Abort update; system app can't be replaced with an ephemeral app 12988 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 12989 "Cannot update a system app with an ephemeral app"); 12990 return; 12991 } 12992 } 12993 12994 if (args.move != null) { 12995 // We did an in-place move, so dex is ready to roll 12996 scanFlags |= SCAN_NO_DEX; 12997 scanFlags |= SCAN_MOVE; 12998 12999 synchronized (mPackages) { 13000 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13001 if (ps == null) { 13002 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 13003 "Missing settings for moved package " + pkgName); 13004 } 13005 13006 // We moved the entire application as-is, so bring over the 13007 // previously derived ABI information. 13008 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 13009 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 13010 } 13011 13012 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 13013 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 13014 scanFlags |= SCAN_NO_DEX; 13015 13016 try { 13017 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 13018 true /* extract libs */); 13019 } catch (PackageManagerException pme) { 13020 Slog.e(TAG, "Error deriving application ABI", pme); 13021 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 13022 return; 13023 } 13024 13025 // Extract package to save the VM unzipping the APK in memory during 13026 // launch. Only do this if profile-guided compilation is enabled because 13027 // otherwise BackgroundDexOptService will not dexopt the package later. 13028 if (mUseJitProfiles) { 13029 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 13030 // Do not run PackageDexOptimizer through the local performDexOpt 13031 // method because `pkg` is not in `mPackages` yet. 13032 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 13033 false /* inclDependencies */, false /* useProfiles */, 13034 true /* extractOnly */); 13035 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13036 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 13037 String msg = "Extracking package failed for " + pkgName; 13038 res.setError(INSTALL_FAILED_DEXOPT, msg); 13039 return; 13040 } 13041 } 13042 } 13043 13044 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 13045 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 13046 return; 13047 } 13048 13049 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 13050 13051 if (replace) { 13052 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 13053 installerPackageName, volumeUuid, res); 13054 } else { 13055 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 13056 args.user, installerPackageName, volumeUuid, res); 13057 } 13058 synchronized (mPackages) { 13059 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13060 if (ps != null) { 13061 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13062 } 13063 } 13064 } 13065 13066 private void startIntentFilterVerifications(int userId, boolean replacing, 13067 PackageParser.Package pkg) { 13068 if (mIntentFilterVerifierComponent == null) { 13069 Slog.w(TAG, "No IntentFilter verification will not be done as " 13070 + "there is no IntentFilterVerifier available!"); 13071 return; 13072 } 13073 13074 final int verifierUid = getPackageUid( 13075 mIntentFilterVerifierComponent.getPackageName(), 13076 MATCH_DEBUG_TRIAGED_MISSING, 13077 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 13078 13079 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 13080 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 13081 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 13082 mHandler.sendMessage(msg); 13083 } 13084 13085 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 13086 PackageParser.Package pkg) { 13087 int size = pkg.activities.size(); 13088 if (size == 0) { 13089 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13090 "No activity, so no need to verify any IntentFilter!"); 13091 return; 13092 } 13093 13094 final boolean hasDomainURLs = hasDomainURLs(pkg); 13095 if (!hasDomainURLs) { 13096 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13097 "No domain URLs, so no need to verify any IntentFilter!"); 13098 return; 13099 } 13100 13101 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 13102 + " if any IntentFilter from the " + size 13103 + " Activities needs verification ..."); 13104 13105 int count = 0; 13106 final String packageName = pkg.packageName; 13107 13108 synchronized (mPackages) { 13109 // If this is a new install and we see that we've already run verification for this 13110 // package, we have nothing to do: it means the state was restored from backup. 13111 if (!replacing) { 13112 IntentFilterVerificationInfo ivi = 13113 mSettings.getIntentFilterVerificationLPr(packageName); 13114 if (ivi != null) { 13115 if (DEBUG_DOMAIN_VERIFICATION) { 13116 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 13117 + ivi.getStatusString()); 13118 } 13119 return; 13120 } 13121 } 13122 13123 // If any filters need to be verified, then all need to be. 13124 boolean needToVerify = false; 13125 for (PackageParser.Activity a : pkg.activities) { 13126 for (ActivityIntentInfo filter : a.intents) { 13127 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 13128 if (DEBUG_DOMAIN_VERIFICATION) { 13129 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 13130 } 13131 needToVerify = true; 13132 break; 13133 } 13134 } 13135 } 13136 13137 if (needToVerify) { 13138 final int verificationId = mIntentFilterVerificationToken++; 13139 for (PackageParser.Activity a : pkg.activities) { 13140 for (ActivityIntentInfo filter : a.intents) { 13141 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 13142 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13143 "Verification needed for IntentFilter:" + filter.toString()); 13144 mIntentFilterVerifier.addOneIntentFilterVerification( 13145 verifierUid, userId, verificationId, filter, packageName); 13146 count++; 13147 } 13148 } 13149 } 13150 } 13151 } 13152 13153 if (count > 0) { 13154 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 13155 + " IntentFilter verification" + (count > 1 ? "s" : "") 13156 + " for userId:" + userId); 13157 mIntentFilterVerifier.startVerifications(userId); 13158 } else { 13159 if (DEBUG_DOMAIN_VERIFICATION) { 13160 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 13161 } 13162 } 13163 } 13164 13165 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 13166 final ComponentName cn = filter.activity.getComponentName(); 13167 final String packageName = cn.getPackageName(); 13168 13169 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 13170 packageName); 13171 if (ivi == null) { 13172 return true; 13173 } 13174 int status = ivi.getStatus(); 13175 switch (status) { 13176 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 13177 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 13178 return true; 13179 13180 default: 13181 // Nothing to do 13182 return false; 13183 } 13184 } 13185 13186 private static boolean isMultiArch(ApplicationInfo info) { 13187 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 13188 } 13189 13190 private static boolean isExternal(PackageParser.Package pkg) { 13191 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13192 } 13193 13194 private static boolean isExternal(PackageSetting ps) { 13195 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13196 } 13197 13198 private static boolean isEphemeral(PackageParser.Package pkg) { 13199 return pkg.applicationInfo.isEphemeralApp(); 13200 } 13201 13202 private static boolean isEphemeral(PackageSetting ps) { 13203 return ps.pkg != null && isEphemeral(ps.pkg); 13204 } 13205 13206 private static boolean isSystemApp(PackageParser.Package pkg) { 13207 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 13208 } 13209 13210 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 13211 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 13212 } 13213 13214 private static boolean hasDomainURLs(PackageParser.Package pkg) { 13215 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 13216 } 13217 13218 private static boolean isSystemApp(PackageSetting ps) { 13219 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 13220 } 13221 13222 private static boolean isUpdatedSystemApp(PackageSetting ps) { 13223 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 13224 } 13225 13226 private int packageFlagsToInstallFlags(PackageSetting ps) { 13227 int installFlags = 0; 13228 if (isEphemeral(ps)) { 13229 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13230 } 13231 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 13232 // This existing package was an external ASEC install when we have 13233 // the external flag without a UUID 13234 installFlags |= PackageManager.INSTALL_EXTERNAL; 13235 } 13236 if (ps.isForwardLocked()) { 13237 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13238 } 13239 return installFlags; 13240 } 13241 13242 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 13243 if (isExternal(pkg)) { 13244 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13245 return StorageManager.UUID_PRIMARY_PHYSICAL; 13246 } else { 13247 return pkg.volumeUuid; 13248 } 13249 } else { 13250 return StorageManager.UUID_PRIVATE_INTERNAL; 13251 } 13252 } 13253 13254 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 13255 if (isExternal(pkg)) { 13256 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13257 return mSettings.getExternalVersion(); 13258 } else { 13259 return mSettings.findOrCreateVersion(pkg.volumeUuid); 13260 } 13261 } else { 13262 return mSettings.getInternalVersion(); 13263 } 13264 } 13265 13266 private void deleteTempPackageFiles() { 13267 final FilenameFilter filter = new FilenameFilter() { 13268 public boolean accept(File dir, String name) { 13269 return name.startsWith("vmdl") && name.endsWith(".tmp"); 13270 } 13271 }; 13272 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 13273 file.delete(); 13274 } 13275 } 13276 13277 @Override 13278 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 13279 int flags) { 13280 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 13281 flags); 13282 } 13283 13284 @Override 13285 public void deletePackage(final String packageName, 13286 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 13287 mContext.enforceCallingOrSelfPermission( 13288 android.Manifest.permission.DELETE_PACKAGES, null); 13289 Preconditions.checkNotNull(packageName); 13290 Preconditions.checkNotNull(observer); 13291 final int uid = Binder.getCallingUid(); 13292 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 13293 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 13294 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 13295 mContext.enforceCallingOrSelfPermission( 13296 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 13297 "deletePackage for user " + userId); 13298 } 13299 13300 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 13301 try { 13302 observer.onPackageDeleted(packageName, 13303 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 13304 } catch (RemoteException re) { 13305 } 13306 return; 13307 } 13308 13309 for (int currentUserId : users) { 13310 if (getBlockUninstallForUser(packageName, currentUserId)) { 13311 try { 13312 observer.onPackageDeleted(packageName, 13313 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 13314 } catch (RemoteException re) { 13315 } 13316 return; 13317 } 13318 } 13319 13320 if (DEBUG_REMOVE) { 13321 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 13322 } 13323 // Queue up an async operation since the package deletion may take a little while. 13324 mHandler.post(new Runnable() { 13325 public void run() { 13326 mHandler.removeCallbacks(this); 13327 final int returnCode = deletePackageX(packageName, userId, flags); 13328 try { 13329 observer.onPackageDeleted(packageName, returnCode, null); 13330 } catch (RemoteException e) { 13331 Log.i(TAG, "Observer no longer exists."); 13332 } //end catch 13333 } //end run 13334 }); 13335 } 13336 13337 private boolean isPackageDeviceAdmin(String packageName, int userId) { 13338 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13339 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13340 try { 13341 if (dpm != null) { 13342 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 13343 /* callingUserOnly =*/ false); 13344 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 13345 : deviceOwnerComponentName.getPackageName(); 13346 // Does the package contains the device owner? 13347 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 13348 // this check is probably not needed, since DO should be registered as a device 13349 // admin on some user too. (Original bug for this: b/17657954) 13350 if (packageName.equals(deviceOwnerPackageName)) { 13351 return true; 13352 } 13353 // Does it contain a device admin for any user? 13354 int[] users; 13355 if (userId == UserHandle.USER_ALL) { 13356 users = sUserManager.getUserIds(); 13357 } else { 13358 users = new int[]{userId}; 13359 } 13360 for (int i = 0; i < users.length; ++i) { 13361 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 13362 return true; 13363 } 13364 } 13365 } 13366 } catch (RemoteException e) { 13367 } 13368 return false; 13369 } 13370 13371 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 13372 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 13373 } 13374 13375 /** 13376 * This method is an internal method that could be get invoked either 13377 * to delete an installed package or to clean up a failed installation. 13378 * After deleting an installed package, a broadcast is sent to notify any 13379 * listeners that the package has been installed. For cleaning up a failed 13380 * installation, the broadcast is not necessary since the package's 13381 * installation wouldn't have sent the initial broadcast either 13382 * The key steps in deleting a package are 13383 * deleting the package information in internal structures like mPackages, 13384 * deleting the packages base directories through installd 13385 * updating mSettings to reflect current status 13386 * persisting settings for later use 13387 * sending a broadcast if necessary 13388 */ 13389 private int deletePackageX(String packageName, int userId, int flags) { 13390 final PackageRemovedInfo info = new PackageRemovedInfo(); 13391 final boolean res; 13392 13393 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 13394 ? UserHandle.ALL : new UserHandle(userId); 13395 13396 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 13397 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 13398 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 13399 } 13400 13401 boolean removedForAllUsers = false; 13402 boolean systemUpdate = false; 13403 13404 PackageParser.Package uninstalledPkg; 13405 13406 // for the uninstall-updates case and restricted profiles, remember the per- 13407 // userhandle installed state 13408 int[] allUsers; 13409 boolean[] perUserInstalled; 13410 synchronized (mPackages) { 13411 uninstalledPkg = mPackages.get(packageName); 13412 PackageSetting ps = mSettings.mPackages.get(packageName); 13413 allUsers = sUserManager.getUserIds(); 13414 perUserInstalled = new boolean[allUsers.length]; 13415 for (int i = 0; i < allUsers.length; i++) { 13416 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 13417 } 13418 } 13419 13420 synchronized (mInstallLock) { 13421 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 13422 res = deletePackageLI(packageName, removeForUser, 13423 true, allUsers, perUserInstalled, 13424 flags | REMOVE_CHATTY, info, true); 13425 systemUpdate = info.isRemovedPackageSystemUpdate; 13426 synchronized (mPackages) { 13427 if (res) { 13428 if (!systemUpdate && mPackages.get(packageName) == null) { 13429 removedForAllUsers = true; 13430 } 13431 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg); 13432 } 13433 } 13434 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 13435 + " removedForAllUsers=" + removedForAllUsers); 13436 } 13437 13438 if (res) { 13439 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 13440 13441 // If the removed package was a system update, the old system package 13442 // was re-enabled; we need to broadcast this information 13443 if (systemUpdate) { 13444 Bundle extras = new Bundle(1); 13445 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 13446 ? info.removedAppId : info.uid); 13447 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13448 13449 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 13450 extras, 0, null, null, null); 13451 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 13452 extras, 0, null, null, null); 13453 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 13454 null, 0, packageName, null, null); 13455 } 13456 } 13457 // Force a gc here. 13458 Runtime.getRuntime().gc(); 13459 // Delete the resources here after sending the broadcast to let 13460 // other processes clean up before deleting resources. 13461 if (info.args != null) { 13462 synchronized (mInstallLock) { 13463 info.args.doPostDeleteLI(true); 13464 } 13465 } 13466 13467 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 13468 } 13469 13470 class PackageRemovedInfo { 13471 String removedPackage; 13472 int uid = -1; 13473 int removedAppId = -1; 13474 int[] removedUsers = null; 13475 boolean isRemovedPackageSystemUpdate = false; 13476 // Clean up resources deleted packages. 13477 InstallArgs args = null; 13478 13479 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 13480 Bundle extras = new Bundle(1); 13481 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 13482 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 13483 if (replacing) { 13484 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13485 } 13486 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 13487 if (removedPackage != null) { 13488 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 13489 extras, 0, null, null, removedUsers); 13490 if (fullRemove && !replacing) { 13491 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 13492 extras, 0, null, null, removedUsers); 13493 } 13494 } 13495 if (removedAppId >= 0) { 13496 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 13497 removedUsers); 13498 } 13499 } 13500 } 13501 13502 /* 13503 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 13504 * flag is not set, the data directory is removed as well. 13505 * make sure this flag is set for partially installed apps. If not its meaningless to 13506 * delete a partially installed application. 13507 */ 13508 private void removePackageDataLI(PackageSetting ps, 13509 int[] allUserHandles, boolean[] perUserInstalled, 13510 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 13511 String packageName = ps.name; 13512 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 13513 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 13514 // Retrieve object to delete permissions for shared user later on 13515 final PackageSetting deletedPs; 13516 // reader 13517 synchronized (mPackages) { 13518 deletedPs = mSettings.mPackages.get(packageName); 13519 if (outInfo != null) { 13520 outInfo.removedPackage = packageName; 13521 outInfo.removedUsers = deletedPs != null 13522 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 13523 : null; 13524 } 13525 } 13526 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13527 removeDataDirsLI(ps.volumeUuid, packageName); 13528 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 13529 } 13530 // writer 13531 synchronized (mPackages) { 13532 if (deletedPs != null) { 13533 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13534 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 13535 clearDefaultBrowserIfNeeded(packageName); 13536 if (outInfo != null) { 13537 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 13538 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 13539 } 13540 updatePermissionsLPw(deletedPs.name, null, 0); 13541 if (deletedPs.sharedUser != null) { 13542 // Remove permissions associated with package. Since runtime 13543 // permissions are per user we have to kill the removed package 13544 // or packages running under the shared user of the removed 13545 // package if revoking the permissions requested only by the removed 13546 // package is successful and this causes a change in gids. 13547 for (int userId : UserManagerService.getInstance().getUserIds()) { 13548 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 13549 userId); 13550 if (userIdToKill == UserHandle.USER_ALL 13551 || userIdToKill >= UserHandle.USER_SYSTEM) { 13552 // If gids changed for this user, kill all affected packages. 13553 mHandler.post(new Runnable() { 13554 @Override 13555 public void run() { 13556 // This has to happen with no lock held. 13557 killApplication(deletedPs.name, deletedPs.appId, 13558 KILL_APP_REASON_GIDS_CHANGED); 13559 } 13560 }); 13561 break; 13562 } 13563 } 13564 } 13565 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 13566 } 13567 // make sure to preserve per-user disabled state if this removal was just 13568 // a downgrade of a system app to the factory package 13569 if (allUserHandles != null && perUserInstalled != null) { 13570 if (DEBUG_REMOVE) { 13571 Slog.d(TAG, "Propagating install state across downgrade"); 13572 } 13573 for (int i = 0; i < allUserHandles.length; i++) { 13574 if (DEBUG_REMOVE) { 13575 Slog.d(TAG, " user " + allUserHandles[i] 13576 + " => " + perUserInstalled[i]); 13577 } 13578 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13579 } 13580 } 13581 } 13582 // can downgrade to reader 13583 if (writeSettings) { 13584 // Save settings now 13585 mSettings.writeLPr(); 13586 } 13587 } 13588 if (outInfo != null) { 13589 // A user ID was deleted here. Go through all users and remove it 13590 // from KeyStore. 13591 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 13592 } 13593 } 13594 13595 static boolean locationIsPrivileged(File path) { 13596 try { 13597 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 13598 .getCanonicalPath(); 13599 return path.getCanonicalPath().startsWith(privilegedAppDir); 13600 } catch (IOException e) { 13601 Slog.e(TAG, "Unable to access code path " + path); 13602 } 13603 return false; 13604 } 13605 13606 /* 13607 * Tries to delete system package. 13608 */ 13609 private boolean deleteSystemPackageLI(PackageSetting newPs, 13610 int[] allUserHandles, boolean[] perUserInstalled, 13611 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 13612 final boolean applyUserRestrictions 13613 = (allUserHandles != null) && (perUserInstalled != null); 13614 PackageSetting disabledPs = null; 13615 // Confirm if the system package has been updated 13616 // An updated system app can be deleted. This will also have to restore 13617 // the system pkg from system partition 13618 // reader 13619 synchronized (mPackages) { 13620 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13621 } 13622 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13623 + " disabledPs=" + disabledPs); 13624 if (disabledPs == null) { 13625 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13626 return false; 13627 } else if (DEBUG_REMOVE) { 13628 Slog.d(TAG, "Deleting system pkg from data partition"); 13629 } 13630 if (DEBUG_REMOVE) { 13631 if (applyUserRestrictions) { 13632 Slog.d(TAG, "Remembering install states:"); 13633 for (int i = 0; i < allUserHandles.length; i++) { 13634 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13635 } 13636 } 13637 } 13638 // Delete the updated package 13639 outInfo.isRemovedPackageSystemUpdate = true; 13640 if (disabledPs.versionCode < newPs.versionCode) { 13641 // Delete data for downgrades 13642 flags &= ~PackageManager.DELETE_KEEP_DATA; 13643 } else { 13644 // Preserve data by setting flag 13645 flags |= PackageManager.DELETE_KEEP_DATA; 13646 } 13647 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13648 allUserHandles, perUserInstalled, outInfo, writeSettings); 13649 if (!ret) { 13650 return false; 13651 } 13652 // writer 13653 synchronized (mPackages) { 13654 // Reinstate the old system package 13655 mSettings.enableSystemPackageLPw(newPs.name); 13656 // Remove any native libraries from the upgraded package. 13657 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13658 } 13659 // Install the system package 13660 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13661 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13662 if (locationIsPrivileged(disabledPs.codePath)) { 13663 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13664 } 13665 13666 final PackageParser.Package newPkg; 13667 try { 13668 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 13669 } catch (PackageManagerException e) { 13670 Slog.w(TAG, "Failed to restore system package " + newPs.name + ": " + e.getMessage()); 13671 return false; 13672 } 13673 13674 prepareAppDataAfterInstall(newPkg); 13675 13676 // writer 13677 synchronized (mPackages) { 13678 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13679 13680 // Propagate the permissions state as we do not want to drop on the floor 13681 // runtime permissions. The update permissions method below will take 13682 // care of removing obsolete permissions and grant install permissions. 13683 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13684 updatePermissionsLPw(newPkg.packageName, newPkg, 13685 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13686 13687 if (applyUserRestrictions) { 13688 if (DEBUG_REMOVE) { 13689 Slog.d(TAG, "Propagating install state across reinstall"); 13690 } 13691 for (int i = 0; i < allUserHandles.length; i++) { 13692 if (DEBUG_REMOVE) { 13693 Slog.d(TAG, " user " + allUserHandles[i] 13694 + " => " + perUserInstalled[i]); 13695 } 13696 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13697 13698 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13699 } 13700 // Regardless of writeSettings we need to ensure that this restriction 13701 // state propagation is persisted 13702 mSettings.writeAllUsersPackageRestrictionsLPr(); 13703 } 13704 // can downgrade to reader here 13705 if (writeSettings) { 13706 mSettings.writeLPr(); 13707 } 13708 } 13709 return true; 13710 } 13711 13712 private boolean deleteInstalledPackageLI(PackageSetting ps, 13713 boolean deleteCodeAndResources, int flags, 13714 int[] allUserHandles, boolean[] perUserInstalled, 13715 PackageRemovedInfo outInfo, boolean writeSettings) { 13716 if (outInfo != null) { 13717 outInfo.uid = ps.appId; 13718 } 13719 13720 // Delete package data from internal structures and also remove data if flag is set 13721 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13722 13723 // Delete application code and resources 13724 if (deleteCodeAndResources && (outInfo != null)) { 13725 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13726 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13727 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13728 } 13729 return true; 13730 } 13731 13732 @Override 13733 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13734 int userId) { 13735 mContext.enforceCallingOrSelfPermission( 13736 android.Manifest.permission.DELETE_PACKAGES, null); 13737 synchronized (mPackages) { 13738 PackageSetting ps = mSettings.mPackages.get(packageName); 13739 if (ps == null) { 13740 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13741 return false; 13742 } 13743 if (!ps.getInstalled(userId)) { 13744 // Can't block uninstall for an app that is not installed or enabled. 13745 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13746 return false; 13747 } 13748 ps.setBlockUninstall(blockUninstall, userId); 13749 mSettings.writePackageRestrictionsLPr(userId); 13750 } 13751 return true; 13752 } 13753 13754 @Override 13755 public boolean getBlockUninstallForUser(String packageName, int userId) { 13756 synchronized (mPackages) { 13757 PackageSetting ps = mSettings.mPackages.get(packageName); 13758 if (ps == null) { 13759 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13760 return false; 13761 } 13762 return ps.getBlockUninstall(userId); 13763 } 13764 } 13765 13766 @Override 13767 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 13768 int callingUid = Binder.getCallingUid(); 13769 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 13770 throw new SecurityException( 13771 "setRequiredForSystemUser can only be run by the system or root"); 13772 } 13773 synchronized (mPackages) { 13774 PackageSetting ps = mSettings.mPackages.get(packageName); 13775 if (ps == null) { 13776 Log.w(TAG, "Package doesn't exist: " + packageName); 13777 return false; 13778 } 13779 if (systemUserApp) { 13780 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 13781 } else { 13782 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 13783 } 13784 mSettings.writeLPr(); 13785 } 13786 return true; 13787 } 13788 13789 /* 13790 * This method handles package deletion in general 13791 */ 13792 private boolean deletePackageLI(String packageName, UserHandle user, 13793 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13794 int flags, PackageRemovedInfo outInfo, 13795 boolean writeSettings) { 13796 if (packageName == null) { 13797 Slog.w(TAG, "Attempt to delete null packageName."); 13798 return false; 13799 } 13800 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13801 PackageSetting ps; 13802 boolean dataOnly = false; 13803 int removeUser = -1; 13804 int appId = -1; 13805 synchronized (mPackages) { 13806 ps = mSettings.mPackages.get(packageName); 13807 if (ps == null) { 13808 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13809 return false; 13810 } 13811 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13812 && user.getIdentifier() != UserHandle.USER_ALL) { 13813 // The caller is asking that the package only be deleted for a single 13814 // user. To do this, we just mark its uninstalled state and delete 13815 // its data. If this is a system app, we only allow this to happen if 13816 // they have set the special DELETE_SYSTEM_APP which requests different 13817 // semantics than normal for uninstalling system apps. 13818 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13819 final int userId = user.getIdentifier(); 13820 ps.setUserState(userId, 13821 COMPONENT_ENABLED_STATE_DEFAULT, 13822 false, //installed 13823 true, //stopped 13824 true, //notLaunched 13825 false, //hidden 13826 false, //suspended 13827 null, null, null, 13828 false, // blockUninstall 13829 ps.readUserState(userId).domainVerificationStatus, 0); 13830 if (!isSystemApp(ps)) { 13831 // Do not uninstall the APK if an app should be cached 13832 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 13833 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 13834 // Other user still have this package installed, so all 13835 // we need to do is clear this user's data and save that 13836 // it is uninstalled. 13837 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13838 removeUser = user.getIdentifier(); 13839 appId = ps.appId; 13840 scheduleWritePackageRestrictionsLocked(removeUser); 13841 } else { 13842 // We need to set it back to 'installed' so the uninstall 13843 // broadcasts will be sent correctly. 13844 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13845 ps.setInstalled(true, user.getIdentifier()); 13846 } 13847 } else { 13848 // This is a system app, so we assume that the 13849 // other users still have this package installed, so all 13850 // we need to do is clear this user's data and save that 13851 // it is uninstalled. 13852 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13853 removeUser = user.getIdentifier(); 13854 appId = ps.appId; 13855 scheduleWritePackageRestrictionsLocked(removeUser); 13856 } 13857 } 13858 } 13859 13860 if (removeUser >= 0) { 13861 // From above, we determined that we are deleting this only 13862 // for a single user. Continue the work here. 13863 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13864 if (outInfo != null) { 13865 outInfo.removedPackage = packageName; 13866 outInfo.removedAppId = appId; 13867 outInfo.removedUsers = new int[] {removeUser}; 13868 } 13869 // TODO: triage flags as part of 26466827 13870 final int installerFlags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 13871 try { 13872 mInstaller.destroyAppData(ps.volumeUuid, packageName, removeUser, installerFlags); 13873 } catch (InstallerException e) { 13874 Slog.w(TAG, "Failed to delete app data", e); 13875 } 13876 removeKeystoreDataIfNeeded(removeUser, appId); 13877 schedulePackageCleaning(packageName, removeUser, false); 13878 synchronized (mPackages) { 13879 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13880 scheduleWritePackageRestrictionsLocked(removeUser); 13881 } 13882 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13883 } 13884 return true; 13885 } 13886 13887 if (dataOnly) { 13888 // Delete application data first 13889 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13890 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13891 return true; 13892 } 13893 13894 boolean ret = false; 13895 if (isSystemApp(ps)) { 13896 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 13897 // When an updated system application is deleted we delete the existing resources as well and 13898 // fall back to existing code in system partition 13899 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13900 flags, outInfo, writeSettings); 13901 } else { 13902 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 13903 // Kill application pre-emptively especially for apps on sd. 13904 killApplication(packageName, ps.appId, "uninstall pkg"); 13905 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13906 allUserHandles, perUserInstalled, 13907 outInfo, writeSettings); 13908 } 13909 13910 return ret; 13911 } 13912 13913 private final static class ClearStorageConnection implements ServiceConnection { 13914 IMediaContainerService mContainerService; 13915 13916 @Override 13917 public void onServiceConnected(ComponentName name, IBinder service) { 13918 synchronized (this) { 13919 mContainerService = IMediaContainerService.Stub.asInterface(service); 13920 notifyAll(); 13921 } 13922 } 13923 13924 @Override 13925 public void onServiceDisconnected(ComponentName name) { 13926 } 13927 } 13928 13929 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13930 final boolean mounted; 13931 if (Environment.isExternalStorageEmulated()) { 13932 mounted = true; 13933 } else { 13934 final String status = Environment.getExternalStorageState(); 13935 13936 mounted = status.equals(Environment.MEDIA_MOUNTED) 13937 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13938 } 13939 13940 if (!mounted) { 13941 return; 13942 } 13943 13944 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13945 int[] users; 13946 if (userId == UserHandle.USER_ALL) { 13947 users = sUserManager.getUserIds(); 13948 } else { 13949 users = new int[] { userId }; 13950 } 13951 final ClearStorageConnection conn = new ClearStorageConnection(); 13952 if (mContext.bindServiceAsUser( 13953 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 13954 try { 13955 for (int curUser : users) { 13956 long timeout = SystemClock.uptimeMillis() + 5000; 13957 synchronized (conn) { 13958 long now = SystemClock.uptimeMillis(); 13959 while (conn.mContainerService == null && now < timeout) { 13960 try { 13961 conn.wait(timeout - now); 13962 } catch (InterruptedException e) { 13963 } 13964 } 13965 } 13966 if (conn.mContainerService == null) { 13967 return; 13968 } 13969 13970 final UserEnvironment userEnv = new UserEnvironment(curUser); 13971 clearDirectory(conn.mContainerService, 13972 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13973 if (allData) { 13974 clearDirectory(conn.mContainerService, 13975 userEnv.buildExternalStorageAppDataDirs(packageName)); 13976 clearDirectory(conn.mContainerService, 13977 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13978 } 13979 } 13980 } finally { 13981 mContext.unbindService(conn); 13982 } 13983 } 13984 } 13985 13986 @Override 13987 public void clearApplicationUserData(final String packageName, 13988 final IPackageDataObserver observer, final int userId) { 13989 mContext.enforceCallingOrSelfPermission( 13990 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13991 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13992 // Queue up an async operation since the package deletion may take a little while. 13993 mHandler.post(new Runnable() { 13994 public void run() { 13995 mHandler.removeCallbacks(this); 13996 final boolean succeeded; 13997 synchronized (mInstallLock) { 13998 succeeded = clearApplicationUserDataLI(packageName, userId); 13999 } 14000 clearExternalStorageDataSync(packageName, userId, true); 14001 if (succeeded) { 14002 // invoke DeviceStorageMonitor's update method to clear any notifications 14003 DeviceStorageMonitorInternal 14004 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 14005 if (dsm != null) { 14006 dsm.checkMemory(); 14007 } 14008 } 14009 if(observer != null) { 14010 try { 14011 observer.onRemoveCompleted(packageName, succeeded); 14012 } catch (RemoteException e) { 14013 Log.i(TAG, "Observer no longer exists."); 14014 } 14015 } //end if observer 14016 } //end run 14017 }); 14018 } 14019 14020 private boolean clearApplicationUserDataLI(String packageName, int userId) { 14021 if (packageName == null) { 14022 Slog.w(TAG, "Attempt to delete null packageName."); 14023 return false; 14024 } 14025 14026 // Try finding details about the requested package 14027 PackageParser.Package pkg; 14028 synchronized (mPackages) { 14029 pkg = mPackages.get(packageName); 14030 if (pkg == null) { 14031 final PackageSetting ps = mSettings.mPackages.get(packageName); 14032 if (ps != null) { 14033 pkg = ps.pkg; 14034 } 14035 } 14036 14037 if (pkg == null) { 14038 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 14039 return false; 14040 } 14041 14042 PackageSetting ps = (PackageSetting) pkg.mExtras; 14043 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 14044 } 14045 14046 // Always delete data directories for package, even if we found no other 14047 // record of app. This helps users recover from UID mismatches without 14048 // resorting to a full data wipe. 14049 // TODO: triage flags as part of 26466827 14050 final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 14051 try { 14052 mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags); 14053 } catch (InstallerException e) { 14054 Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e); 14055 return false; 14056 } 14057 14058 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 14059 removeKeystoreDataIfNeeded(userId, appId); 14060 14061 // Create a native library symlink only if we have native libraries 14062 // and if the native libraries are 32 bit libraries. We do not provide 14063 // this symlink for 64 bit libraries. 14064 if (pkg.applicationInfo.primaryCpuAbi != null && 14065 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 14066 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 14067 try { 14068 mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 14069 nativeLibPath, userId); 14070 } catch (InstallerException e) { 14071 Slog.w(TAG, "Failed linking native library dir", e); 14072 return false; 14073 } 14074 } 14075 14076 return true; 14077 } 14078 14079 /** 14080 * Reverts user permission state changes (permissions and flags) in 14081 * all packages for a given user. 14082 * 14083 * @param userId The device user for which to do a reset. 14084 */ 14085 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 14086 final int packageCount = mPackages.size(); 14087 for (int i = 0; i < packageCount; i++) { 14088 PackageParser.Package pkg = mPackages.valueAt(i); 14089 PackageSetting ps = (PackageSetting) pkg.mExtras; 14090 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 14091 } 14092 } 14093 14094 /** 14095 * Reverts user permission state changes (permissions and flags). 14096 * 14097 * @param ps The package for which to reset. 14098 * @param userId The device user for which to do a reset. 14099 */ 14100 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 14101 final PackageSetting ps, final int userId) { 14102 if (ps.pkg == null) { 14103 return; 14104 } 14105 14106 // These are flags that can change base on user actions. 14107 final int userSettableMask = FLAG_PERMISSION_USER_SET 14108 | FLAG_PERMISSION_USER_FIXED 14109 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 14110 | FLAG_PERMISSION_REVIEW_REQUIRED; 14111 14112 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 14113 | FLAG_PERMISSION_POLICY_FIXED; 14114 14115 boolean writeInstallPermissions = false; 14116 boolean writeRuntimePermissions = false; 14117 14118 final int permissionCount = ps.pkg.requestedPermissions.size(); 14119 for (int i = 0; i < permissionCount; i++) { 14120 String permission = ps.pkg.requestedPermissions.get(i); 14121 14122 BasePermission bp = mSettings.mPermissions.get(permission); 14123 if (bp == null) { 14124 continue; 14125 } 14126 14127 // If shared user we just reset the state to which only this app contributed. 14128 if (ps.sharedUser != null) { 14129 boolean used = false; 14130 final int packageCount = ps.sharedUser.packages.size(); 14131 for (int j = 0; j < packageCount; j++) { 14132 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 14133 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 14134 && pkg.pkg.requestedPermissions.contains(permission)) { 14135 used = true; 14136 break; 14137 } 14138 } 14139 if (used) { 14140 continue; 14141 } 14142 } 14143 14144 PermissionsState permissionsState = ps.getPermissionsState(); 14145 14146 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 14147 14148 // Always clear the user settable flags. 14149 final boolean hasInstallState = permissionsState.getInstallPermissionState( 14150 bp.name) != null; 14151 // If permission review is enabled and this is a legacy app, mark the 14152 // permission as requiring a review as this is the initial state. 14153 int flags = 0; 14154 if (Build.PERMISSIONS_REVIEW_REQUIRED 14155 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 14156 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 14157 } 14158 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 14159 if (hasInstallState) { 14160 writeInstallPermissions = true; 14161 } else { 14162 writeRuntimePermissions = true; 14163 } 14164 } 14165 14166 // Below is only runtime permission handling. 14167 if (!bp.isRuntime()) { 14168 continue; 14169 } 14170 14171 // Never clobber system or policy. 14172 if ((oldFlags & policyOrSystemFlags) != 0) { 14173 continue; 14174 } 14175 14176 // If this permission was granted by default, make sure it is. 14177 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 14178 if (permissionsState.grantRuntimePermission(bp, userId) 14179 != PERMISSION_OPERATION_FAILURE) { 14180 writeRuntimePermissions = true; 14181 } 14182 // If permission review is enabled the permissions for a legacy apps 14183 // are represented as constantly granted runtime ones, so don't revoke. 14184 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 14185 // Otherwise, reset the permission. 14186 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 14187 switch (revokeResult) { 14188 case PERMISSION_OPERATION_SUCCESS: { 14189 writeRuntimePermissions = true; 14190 } break; 14191 14192 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 14193 writeRuntimePermissions = true; 14194 final int appId = ps.appId; 14195 mHandler.post(new Runnable() { 14196 @Override 14197 public void run() { 14198 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 14199 } 14200 }); 14201 } break; 14202 } 14203 } 14204 } 14205 14206 // Synchronously write as we are taking permissions away. 14207 if (writeRuntimePermissions) { 14208 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 14209 } 14210 14211 // Synchronously write as we are taking permissions away. 14212 if (writeInstallPermissions) { 14213 mSettings.writeLPr(); 14214 } 14215 } 14216 14217 /** 14218 * Remove entries from the keystore daemon. Will only remove it if the 14219 * {@code appId} is valid. 14220 */ 14221 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 14222 if (appId < 0) { 14223 return; 14224 } 14225 14226 final KeyStore keyStore = KeyStore.getInstance(); 14227 if (keyStore != null) { 14228 if (userId == UserHandle.USER_ALL) { 14229 for (final int individual : sUserManager.getUserIds()) { 14230 keyStore.clearUid(UserHandle.getUid(individual, appId)); 14231 } 14232 } else { 14233 keyStore.clearUid(UserHandle.getUid(userId, appId)); 14234 } 14235 } else { 14236 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 14237 } 14238 } 14239 14240 @Override 14241 public void deleteApplicationCacheFiles(final String packageName, 14242 final IPackageDataObserver observer) { 14243 mContext.enforceCallingOrSelfPermission( 14244 android.Manifest.permission.DELETE_CACHE_FILES, null); 14245 // Queue up an async operation since the package deletion may take a little while. 14246 final int userId = UserHandle.getCallingUserId(); 14247 mHandler.post(new Runnable() { 14248 public void run() { 14249 mHandler.removeCallbacks(this); 14250 final boolean succeded; 14251 synchronized (mInstallLock) { 14252 succeded = deleteApplicationCacheFilesLI(packageName, userId); 14253 } 14254 clearExternalStorageDataSync(packageName, userId, false); 14255 if (observer != null) { 14256 try { 14257 observer.onRemoveCompleted(packageName, succeded); 14258 } catch (RemoteException e) { 14259 Log.i(TAG, "Observer no longer exists."); 14260 } 14261 } //end if observer 14262 } //end run 14263 }); 14264 } 14265 14266 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 14267 if (packageName == null) { 14268 Slog.w(TAG, "Attempt to delete null packageName."); 14269 return false; 14270 } 14271 PackageParser.Package p; 14272 synchronized (mPackages) { 14273 p = mPackages.get(packageName); 14274 } 14275 if (p == null) { 14276 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14277 return false; 14278 } 14279 final ApplicationInfo applicationInfo = p.applicationInfo; 14280 if (applicationInfo == null) { 14281 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14282 return false; 14283 } 14284 // TODO: triage flags as part of 26466827 14285 final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 14286 try { 14287 mInstaller.clearAppData(p.volumeUuid, packageName, userId, 14288 flags | Installer.FLAG_CLEAR_CACHE_ONLY); 14289 } catch (InstallerException e) { 14290 Slog.w(TAG, "Couldn't remove cache files for package " 14291 + packageName + " u" + userId, e); 14292 return false; 14293 } 14294 return true; 14295 } 14296 14297 @Override 14298 public void getPackageSizeInfo(final String packageName, int userHandle, 14299 final IPackageStatsObserver observer) { 14300 mContext.enforceCallingOrSelfPermission( 14301 android.Manifest.permission.GET_PACKAGE_SIZE, null); 14302 if (packageName == null) { 14303 throw new IllegalArgumentException("Attempt to get size of null packageName"); 14304 } 14305 14306 PackageStats stats = new PackageStats(packageName, userHandle); 14307 14308 /* 14309 * Queue up an async operation since the package measurement may take a 14310 * little while. 14311 */ 14312 Message msg = mHandler.obtainMessage(INIT_COPY); 14313 msg.obj = new MeasureParams(stats, observer); 14314 mHandler.sendMessage(msg); 14315 } 14316 14317 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 14318 PackageStats pStats) { 14319 if (packageName == null) { 14320 Slog.w(TAG, "Attempt to get size of null packageName."); 14321 return false; 14322 } 14323 PackageParser.Package p; 14324 boolean dataOnly = false; 14325 String libDirRoot = null; 14326 String asecPath = null; 14327 PackageSetting ps = null; 14328 synchronized (mPackages) { 14329 p = mPackages.get(packageName); 14330 ps = mSettings.mPackages.get(packageName); 14331 if(p == null) { 14332 dataOnly = true; 14333 if((ps == null) || (ps.pkg == null)) { 14334 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14335 return false; 14336 } 14337 p = ps.pkg; 14338 } 14339 if (ps != null) { 14340 libDirRoot = ps.legacyNativeLibraryPathString; 14341 } 14342 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 14343 final long token = Binder.clearCallingIdentity(); 14344 try { 14345 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 14346 if (secureContainerId != null) { 14347 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 14348 } 14349 } finally { 14350 Binder.restoreCallingIdentity(token); 14351 } 14352 } 14353 } 14354 String publicSrcDir = null; 14355 if(!dataOnly) { 14356 final ApplicationInfo applicationInfo = p.applicationInfo; 14357 if (applicationInfo == null) { 14358 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14359 return false; 14360 } 14361 if (p.isForwardLocked()) { 14362 publicSrcDir = applicationInfo.getBaseResourcePath(); 14363 } 14364 } 14365 // TODO: extend to measure size of split APKs 14366 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 14367 // not just the first level. 14368 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 14369 // just the primary. 14370 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 14371 14372 String apkPath; 14373 File packageDir = new File(p.codePath); 14374 14375 if (packageDir.isDirectory() && p.canHaveOatDir()) { 14376 apkPath = packageDir.getAbsolutePath(); 14377 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 14378 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 14379 libDirRoot = null; 14380 } 14381 } else { 14382 apkPath = p.baseCodePath; 14383 } 14384 14385 // TODO: triage flags as part of 26466827 14386 final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 14387 try { 14388 mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath, 14389 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 14390 } catch (InstallerException e) { 14391 return false; 14392 } 14393 14394 // Fix-up for forward-locked applications in ASEC containers. 14395 if (!isExternal(p)) { 14396 pStats.codeSize += pStats.externalCodeSize; 14397 pStats.externalCodeSize = 0L; 14398 } 14399 14400 return true; 14401 } 14402 14403 14404 @Override 14405 public void addPackageToPreferred(String packageName) { 14406 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 14407 } 14408 14409 @Override 14410 public void removePackageFromPreferred(String packageName) { 14411 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 14412 } 14413 14414 @Override 14415 public List<PackageInfo> getPreferredPackages(int flags) { 14416 return new ArrayList<PackageInfo>(); 14417 } 14418 14419 private int getUidTargetSdkVersionLockedLPr(int uid) { 14420 Object obj = mSettings.getUserIdLPr(uid); 14421 if (obj instanceof SharedUserSetting) { 14422 final SharedUserSetting sus = (SharedUserSetting) obj; 14423 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 14424 final Iterator<PackageSetting> it = sus.packages.iterator(); 14425 while (it.hasNext()) { 14426 final PackageSetting ps = it.next(); 14427 if (ps.pkg != null) { 14428 int v = ps.pkg.applicationInfo.targetSdkVersion; 14429 if (v < vers) vers = v; 14430 } 14431 } 14432 return vers; 14433 } else if (obj instanceof PackageSetting) { 14434 final PackageSetting ps = (PackageSetting) obj; 14435 if (ps.pkg != null) { 14436 return ps.pkg.applicationInfo.targetSdkVersion; 14437 } 14438 } 14439 return Build.VERSION_CODES.CUR_DEVELOPMENT; 14440 } 14441 14442 @Override 14443 public void addPreferredActivity(IntentFilter filter, int match, 14444 ComponentName[] set, ComponentName activity, int userId) { 14445 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14446 "Adding preferred"); 14447 } 14448 14449 private void addPreferredActivityInternal(IntentFilter filter, int match, 14450 ComponentName[] set, ComponentName activity, boolean always, int userId, 14451 String opname) { 14452 // writer 14453 int callingUid = Binder.getCallingUid(); 14454 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 14455 if (filter.countActions() == 0) { 14456 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14457 return; 14458 } 14459 synchronized (mPackages) { 14460 if (mContext.checkCallingOrSelfPermission( 14461 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14462 != PackageManager.PERMISSION_GRANTED) { 14463 if (getUidTargetSdkVersionLockedLPr(callingUid) 14464 < Build.VERSION_CODES.FROYO) { 14465 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 14466 + callingUid); 14467 return; 14468 } 14469 mContext.enforceCallingOrSelfPermission( 14470 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14471 } 14472 14473 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 14474 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 14475 + userId + ":"); 14476 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14477 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 14478 scheduleWritePackageRestrictionsLocked(userId); 14479 } 14480 } 14481 14482 @Override 14483 public void replacePreferredActivity(IntentFilter filter, int match, 14484 ComponentName[] set, ComponentName activity, int userId) { 14485 if (filter.countActions() != 1) { 14486 throw new IllegalArgumentException( 14487 "replacePreferredActivity expects filter to have only 1 action."); 14488 } 14489 if (filter.countDataAuthorities() != 0 14490 || filter.countDataPaths() != 0 14491 || filter.countDataSchemes() > 1 14492 || filter.countDataTypes() != 0) { 14493 throw new IllegalArgumentException( 14494 "replacePreferredActivity expects filter to have no data authorities, " + 14495 "paths, or types; and at most one scheme."); 14496 } 14497 14498 final int callingUid = Binder.getCallingUid(); 14499 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 14500 synchronized (mPackages) { 14501 if (mContext.checkCallingOrSelfPermission( 14502 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14503 != PackageManager.PERMISSION_GRANTED) { 14504 if (getUidTargetSdkVersionLockedLPr(callingUid) 14505 < Build.VERSION_CODES.FROYO) { 14506 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 14507 + Binder.getCallingUid()); 14508 return; 14509 } 14510 mContext.enforceCallingOrSelfPermission( 14511 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14512 } 14513 14514 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14515 if (pir != null) { 14516 // Get all of the existing entries that exactly match this filter. 14517 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 14518 if (existing != null && existing.size() == 1) { 14519 PreferredActivity cur = existing.get(0); 14520 if (DEBUG_PREFERRED) { 14521 Slog.i(TAG, "Checking replace of preferred:"); 14522 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14523 if (!cur.mPref.mAlways) { 14524 Slog.i(TAG, " -- CUR; not mAlways!"); 14525 } else { 14526 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 14527 Slog.i(TAG, " -- CUR: mSet=" 14528 + Arrays.toString(cur.mPref.mSetComponents)); 14529 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 14530 Slog.i(TAG, " -- NEW: mMatch=" 14531 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 14532 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 14533 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 14534 } 14535 } 14536 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 14537 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 14538 && cur.mPref.sameSet(set)) { 14539 // Setting the preferred activity to what it happens to be already 14540 if (DEBUG_PREFERRED) { 14541 Slog.i(TAG, "Replacing with same preferred activity " 14542 + cur.mPref.mShortComponent + " for user " 14543 + userId + ":"); 14544 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14545 } 14546 return; 14547 } 14548 } 14549 14550 if (existing != null) { 14551 if (DEBUG_PREFERRED) { 14552 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 14553 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14554 } 14555 for (int i = 0; i < existing.size(); i++) { 14556 PreferredActivity pa = existing.get(i); 14557 if (DEBUG_PREFERRED) { 14558 Slog.i(TAG, "Removing existing preferred activity " 14559 + pa.mPref.mComponent + ":"); 14560 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 14561 } 14562 pir.removeFilter(pa); 14563 } 14564 } 14565 } 14566 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14567 "Replacing preferred"); 14568 } 14569 } 14570 14571 @Override 14572 public void clearPackagePreferredActivities(String packageName) { 14573 final int uid = Binder.getCallingUid(); 14574 // writer 14575 synchronized (mPackages) { 14576 PackageParser.Package pkg = mPackages.get(packageName); 14577 if (pkg == null || pkg.applicationInfo.uid != uid) { 14578 if (mContext.checkCallingOrSelfPermission( 14579 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14580 != PackageManager.PERMISSION_GRANTED) { 14581 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 14582 < Build.VERSION_CODES.FROYO) { 14583 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 14584 + Binder.getCallingUid()); 14585 return; 14586 } 14587 mContext.enforceCallingOrSelfPermission( 14588 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14589 } 14590 } 14591 14592 int user = UserHandle.getCallingUserId(); 14593 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 14594 scheduleWritePackageRestrictionsLocked(user); 14595 } 14596 } 14597 } 14598 14599 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14600 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 14601 ArrayList<PreferredActivity> removed = null; 14602 boolean changed = false; 14603 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14604 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 14605 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14606 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 14607 continue; 14608 } 14609 Iterator<PreferredActivity> it = pir.filterIterator(); 14610 while (it.hasNext()) { 14611 PreferredActivity pa = it.next(); 14612 // Mark entry for removal only if it matches the package name 14613 // and the entry is of type "always". 14614 if (packageName == null || 14615 (pa.mPref.mComponent.getPackageName().equals(packageName) 14616 && pa.mPref.mAlways)) { 14617 if (removed == null) { 14618 removed = new ArrayList<PreferredActivity>(); 14619 } 14620 removed.add(pa); 14621 } 14622 } 14623 if (removed != null) { 14624 for (int j=0; j<removed.size(); j++) { 14625 PreferredActivity pa = removed.get(j); 14626 pir.removeFilter(pa); 14627 } 14628 changed = true; 14629 } 14630 } 14631 return changed; 14632 } 14633 14634 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14635 private void clearIntentFilterVerificationsLPw(int userId) { 14636 final int packageCount = mPackages.size(); 14637 for (int i = 0; i < packageCount; i++) { 14638 PackageParser.Package pkg = mPackages.valueAt(i); 14639 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 14640 } 14641 } 14642 14643 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14644 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 14645 if (userId == UserHandle.USER_ALL) { 14646 if (mSettings.removeIntentFilterVerificationLPw(packageName, 14647 sUserManager.getUserIds())) { 14648 for (int oneUserId : sUserManager.getUserIds()) { 14649 scheduleWritePackageRestrictionsLocked(oneUserId); 14650 } 14651 } 14652 } else { 14653 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 14654 scheduleWritePackageRestrictionsLocked(userId); 14655 } 14656 } 14657 } 14658 14659 void clearDefaultBrowserIfNeeded(String packageName) { 14660 for (int oneUserId : sUserManager.getUserIds()) { 14661 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 14662 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 14663 if (packageName.equals(defaultBrowserPackageName)) { 14664 setDefaultBrowserPackageName(null, oneUserId); 14665 } 14666 } 14667 } 14668 14669 @Override 14670 public void resetApplicationPreferences(int userId) { 14671 mContext.enforceCallingOrSelfPermission( 14672 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14673 // writer 14674 synchronized (mPackages) { 14675 final long identity = Binder.clearCallingIdentity(); 14676 try { 14677 clearPackagePreferredActivitiesLPw(null, userId); 14678 mSettings.applyDefaultPreferredAppsLPw(this, userId); 14679 // TODO: We have to reset the default SMS and Phone. This requires 14680 // significant refactoring to keep all default apps in the package 14681 // manager (cleaner but more work) or have the services provide 14682 // callbacks to the package manager to request a default app reset. 14683 applyFactoryDefaultBrowserLPw(userId); 14684 clearIntentFilterVerificationsLPw(userId); 14685 primeDomainVerificationsLPw(userId); 14686 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 14687 scheduleWritePackageRestrictionsLocked(userId); 14688 } finally { 14689 Binder.restoreCallingIdentity(identity); 14690 } 14691 } 14692 } 14693 14694 @Override 14695 public int getPreferredActivities(List<IntentFilter> outFilters, 14696 List<ComponentName> outActivities, String packageName) { 14697 14698 int num = 0; 14699 final int userId = UserHandle.getCallingUserId(); 14700 // reader 14701 synchronized (mPackages) { 14702 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14703 if (pir != null) { 14704 final Iterator<PreferredActivity> it = pir.filterIterator(); 14705 while (it.hasNext()) { 14706 final PreferredActivity pa = it.next(); 14707 if (packageName == null 14708 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14709 && pa.mPref.mAlways)) { 14710 if (outFilters != null) { 14711 outFilters.add(new IntentFilter(pa)); 14712 } 14713 if (outActivities != null) { 14714 outActivities.add(pa.mPref.mComponent); 14715 } 14716 } 14717 } 14718 } 14719 } 14720 14721 return num; 14722 } 14723 14724 @Override 14725 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14726 int userId) { 14727 int callingUid = Binder.getCallingUid(); 14728 if (callingUid != Process.SYSTEM_UID) { 14729 throw new SecurityException( 14730 "addPersistentPreferredActivity can only be run by the system"); 14731 } 14732 if (filter.countActions() == 0) { 14733 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14734 return; 14735 } 14736 synchronized (mPackages) { 14737 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14738 ":"); 14739 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14740 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14741 new PersistentPreferredActivity(filter, activity)); 14742 scheduleWritePackageRestrictionsLocked(userId); 14743 } 14744 } 14745 14746 @Override 14747 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14748 int callingUid = Binder.getCallingUid(); 14749 if (callingUid != Process.SYSTEM_UID) { 14750 throw new SecurityException( 14751 "clearPackagePersistentPreferredActivities can only be run by the system"); 14752 } 14753 ArrayList<PersistentPreferredActivity> removed = null; 14754 boolean changed = false; 14755 synchronized (mPackages) { 14756 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14757 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14758 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14759 .valueAt(i); 14760 if (userId != thisUserId) { 14761 continue; 14762 } 14763 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14764 while (it.hasNext()) { 14765 PersistentPreferredActivity ppa = it.next(); 14766 // Mark entry for removal only if it matches the package name. 14767 if (ppa.mComponent.getPackageName().equals(packageName)) { 14768 if (removed == null) { 14769 removed = new ArrayList<PersistentPreferredActivity>(); 14770 } 14771 removed.add(ppa); 14772 } 14773 } 14774 if (removed != null) { 14775 for (int j=0; j<removed.size(); j++) { 14776 PersistentPreferredActivity ppa = removed.get(j); 14777 ppir.removeFilter(ppa); 14778 } 14779 changed = true; 14780 } 14781 } 14782 14783 if (changed) { 14784 scheduleWritePackageRestrictionsLocked(userId); 14785 } 14786 } 14787 } 14788 14789 /** 14790 * Common machinery for picking apart a restored XML blob and passing 14791 * it to a caller-supplied functor to be applied to the running system. 14792 */ 14793 private void restoreFromXml(XmlPullParser parser, int userId, 14794 String expectedStartTag, BlobXmlRestorer functor) 14795 throws IOException, XmlPullParserException { 14796 int type; 14797 while ((type = parser.next()) != XmlPullParser.START_TAG 14798 && type != XmlPullParser.END_DOCUMENT) { 14799 } 14800 if (type != XmlPullParser.START_TAG) { 14801 // oops didn't find a start tag?! 14802 if (DEBUG_BACKUP) { 14803 Slog.e(TAG, "Didn't find start tag during restore"); 14804 } 14805 return; 14806 } 14807Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 14808 // this is supposed to be TAG_PREFERRED_BACKUP 14809 if (!expectedStartTag.equals(parser.getName())) { 14810 if (DEBUG_BACKUP) { 14811 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14812 } 14813 return; 14814 } 14815 14816 // skip interfering stuff, then we're aligned with the backing implementation 14817 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14818Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 14819 functor.apply(parser, userId); 14820 } 14821 14822 private interface BlobXmlRestorer { 14823 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14824 } 14825 14826 /** 14827 * Non-Binder method, support for the backup/restore mechanism: write the 14828 * full set of preferred activities in its canonical XML format. Returns the 14829 * XML output as a byte array, or null if there is none. 14830 */ 14831 @Override 14832 public byte[] getPreferredActivityBackup(int userId) { 14833 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14834 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14835 } 14836 14837 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14838 try { 14839 final XmlSerializer serializer = new FastXmlSerializer(); 14840 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14841 serializer.startDocument(null, true); 14842 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14843 14844 synchronized (mPackages) { 14845 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14846 } 14847 14848 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14849 serializer.endDocument(); 14850 serializer.flush(); 14851 } catch (Exception e) { 14852 if (DEBUG_BACKUP) { 14853 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14854 } 14855 return null; 14856 } 14857 14858 return dataStream.toByteArray(); 14859 } 14860 14861 @Override 14862 public void restorePreferredActivities(byte[] backup, int userId) { 14863 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14864 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14865 } 14866 14867 try { 14868 final XmlPullParser parser = Xml.newPullParser(); 14869 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14870 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14871 new BlobXmlRestorer() { 14872 @Override 14873 public void apply(XmlPullParser parser, int userId) 14874 throws XmlPullParserException, IOException { 14875 synchronized (mPackages) { 14876 mSettings.readPreferredActivitiesLPw(parser, userId); 14877 } 14878 } 14879 } ); 14880 } catch (Exception e) { 14881 if (DEBUG_BACKUP) { 14882 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14883 } 14884 } 14885 } 14886 14887 /** 14888 * Non-Binder method, support for the backup/restore mechanism: write the 14889 * default browser (etc) settings in its canonical XML format. Returns the default 14890 * browser XML representation as a byte array, or null if there is none. 14891 */ 14892 @Override 14893 public byte[] getDefaultAppsBackup(int userId) { 14894 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14895 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14896 } 14897 14898 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14899 try { 14900 final XmlSerializer serializer = new FastXmlSerializer(); 14901 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14902 serializer.startDocument(null, true); 14903 serializer.startTag(null, TAG_DEFAULT_APPS); 14904 14905 synchronized (mPackages) { 14906 mSettings.writeDefaultAppsLPr(serializer, userId); 14907 } 14908 14909 serializer.endTag(null, TAG_DEFAULT_APPS); 14910 serializer.endDocument(); 14911 serializer.flush(); 14912 } catch (Exception e) { 14913 if (DEBUG_BACKUP) { 14914 Slog.e(TAG, "Unable to write default apps for backup", e); 14915 } 14916 return null; 14917 } 14918 14919 return dataStream.toByteArray(); 14920 } 14921 14922 @Override 14923 public void restoreDefaultApps(byte[] backup, int userId) { 14924 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14925 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14926 } 14927 14928 try { 14929 final XmlPullParser parser = Xml.newPullParser(); 14930 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14931 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14932 new BlobXmlRestorer() { 14933 @Override 14934 public void apply(XmlPullParser parser, int userId) 14935 throws XmlPullParserException, IOException { 14936 synchronized (mPackages) { 14937 mSettings.readDefaultAppsLPw(parser, userId); 14938 } 14939 } 14940 } ); 14941 } catch (Exception e) { 14942 if (DEBUG_BACKUP) { 14943 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14944 } 14945 } 14946 } 14947 14948 @Override 14949 public byte[] getIntentFilterVerificationBackup(int userId) { 14950 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14951 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14952 } 14953 14954 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14955 try { 14956 final XmlSerializer serializer = new FastXmlSerializer(); 14957 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14958 serializer.startDocument(null, true); 14959 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14960 14961 synchronized (mPackages) { 14962 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14963 } 14964 14965 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14966 serializer.endDocument(); 14967 serializer.flush(); 14968 } catch (Exception e) { 14969 if (DEBUG_BACKUP) { 14970 Slog.e(TAG, "Unable to write default apps for backup", e); 14971 } 14972 return null; 14973 } 14974 14975 return dataStream.toByteArray(); 14976 } 14977 14978 @Override 14979 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14980 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14981 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14982 } 14983 14984 try { 14985 final XmlPullParser parser = Xml.newPullParser(); 14986 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14987 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14988 new BlobXmlRestorer() { 14989 @Override 14990 public void apply(XmlPullParser parser, int userId) 14991 throws XmlPullParserException, IOException { 14992 synchronized (mPackages) { 14993 mSettings.readAllDomainVerificationsLPr(parser, userId); 14994 mSettings.writeLPr(); 14995 } 14996 } 14997 } ); 14998 } catch (Exception e) { 14999 if (DEBUG_BACKUP) { 15000 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 15001 } 15002 } 15003 } 15004 15005 @Override 15006 public byte[] getPermissionGrantBackup(int userId) { 15007 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15008 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 15009 } 15010 15011 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 15012 try { 15013 final XmlSerializer serializer = new FastXmlSerializer(); 15014 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 15015 serializer.startDocument(null, true); 15016 serializer.startTag(null, TAG_PERMISSION_BACKUP); 15017 15018 synchronized (mPackages) { 15019 serializeRuntimePermissionGrantsLPr(serializer, userId); 15020 } 15021 15022 serializer.endTag(null, TAG_PERMISSION_BACKUP); 15023 serializer.endDocument(); 15024 serializer.flush(); 15025 } catch (Exception e) { 15026 if (DEBUG_BACKUP) { 15027 Slog.e(TAG, "Unable to write default apps for backup", e); 15028 } 15029 return null; 15030 } 15031 15032 return dataStream.toByteArray(); 15033 } 15034 15035 @Override 15036 public void restorePermissionGrants(byte[] backup, int userId) { 15037 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15038 throw new SecurityException("Only the system may call restorePermissionGrants()"); 15039 } 15040 15041 try { 15042 final XmlPullParser parser = Xml.newPullParser(); 15043 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 15044 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 15045 new BlobXmlRestorer() { 15046 @Override 15047 public void apply(XmlPullParser parser, int userId) 15048 throws XmlPullParserException, IOException { 15049 synchronized (mPackages) { 15050 processRestoredPermissionGrantsLPr(parser, userId); 15051 } 15052 } 15053 } ); 15054 } catch (Exception e) { 15055 if (DEBUG_BACKUP) { 15056 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 15057 } 15058 } 15059 } 15060 15061 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 15062 throws IOException { 15063 serializer.startTag(null, TAG_ALL_GRANTS); 15064 15065 final int N = mSettings.mPackages.size(); 15066 for (int i = 0; i < N; i++) { 15067 final PackageSetting ps = mSettings.mPackages.valueAt(i); 15068 boolean pkgGrantsKnown = false; 15069 15070 PermissionsState packagePerms = ps.getPermissionsState(); 15071 15072 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 15073 final int grantFlags = state.getFlags(); 15074 // only look at grants that are not system/policy fixed 15075 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 15076 final boolean isGranted = state.isGranted(); 15077 // And only back up the user-twiddled state bits 15078 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 15079 final String packageName = mSettings.mPackages.keyAt(i); 15080 if (!pkgGrantsKnown) { 15081 serializer.startTag(null, TAG_GRANT); 15082 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 15083 pkgGrantsKnown = true; 15084 } 15085 15086 final boolean userSet = 15087 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 15088 final boolean userFixed = 15089 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 15090 final boolean revoke = 15091 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 15092 15093 serializer.startTag(null, TAG_PERMISSION); 15094 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 15095 if (isGranted) { 15096 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 15097 } 15098 if (userSet) { 15099 serializer.attribute(null, ATTR_USER_SET, "true"); 15100 } 15101 if (userFixed) { 15102 serializer.attribute(null, ATTR_USER_FIXED, "true"); 15103 } 15104 if (revoke) { 15105 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 15106 } 15107 serializer.endTag(null, TAG_PERMISSION); 15108 } 15109 } 15110 } 15111 15112 if (pkgGrantsKnown) { 15113 serializer.endTag(null, TAG_GRANT); 15114 } 15115 } 15116 15117 serializer.endTag(null, TAG_ALL_GRANTS); 15118 } 15119 15120 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 15121 throws XmlPullParserException, IOException { 15122 String pkgName = null; 15123 int outerDepth = parser.getDepth(); 15124 int type; 15125 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 15126 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 15127 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 15128 continue; 15129 } 15130 15131 final String tagName = parser.getName(); 15132 if (tagName.equals(TAG_GRANT)) { 15133 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 15134 if (DEBUG_BACKUP) { 15135 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 15136 } 15137 } else if (tagName.equals(TAG_PERMISSION)) { 15138 15139 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 15140 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 15141 15142 int newFlagSet = 0; 15143 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 15144 newFlagSet |= FLAG_PERMISSION_USER_SET; 15145 } 15146 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 15147 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 15148 } 15149 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 15150 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 15151 } 15152 if (DEBUG_BACKUP) { 15153 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 15154 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 15155 } 15156 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15157 if (ps != null) { 15158 // Already installed so we apply the grant immediately 15159 if (DEBUG_BACKUP) { 15160 Slog.v(TAG, " + already installed; applying"); 15161 } 15162 PermissionsState perms = ps.getPermissionsState(); 15163 BasePermission bp = mSettings.mPermissions.get(permName); 15164 if (bp != null) { 15165 if (isGranted) { 15166 perms.grantRuntimePermission(bp, userId); 15167 } 15168 if (newFlagSet != 0) { 15169 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 15170 } 15171 } 15172 } else { 15173 // Need to wait for post-restore install to apply the grant 15174 if (DEBUG_BACKUP) { 15175 Slog.v(TAG, " - not yet installed; saving for later"); 15176 } 15177 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 15178 isGranted, newFlagSet, userId); 15179 } 15180 } else { 15181 PackageManagerService.reportSettingsProblem(Log.WARN, 15182 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 15183 XmlUtils.skipCurrentTag(parser); 15184 } 15185 } 15186 15187 scheduleWriteSettingsLocked(); 15188 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15189 } 15190 15191 @Override 15192 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 15193 int sourceUserId, int targetUserId, int flags) { 15194 mContext.enforceCallingOrSelfPermission( 15195 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 15196 int callingUid = Binder.getCallingUid(); 15197 enforceOwnerRights(ownerPackage, callingUid); 15198 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 15199 if (intentFilter.countActions() == 0) { 15200 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 15201 return; 15202 } 15203 synchronized (mPackages) { 15204 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 15205 ownerPackage, targetUserId, flags); 15206 CrossProfileIntentResolver resolver = 15207 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 15208 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 15209 // We have all those whose filter is equal. Now checking if the rest is equal as well. 15210 if (existing != null) { 15211 int size = existing.size(); 15212 for (int i = 0; i < size; i++) { 15213 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 15214 return; 15215 } 15216 } 15217 } 15218 resolver.addFilter(newFilter); 15219 scheduleWritePackageRestrictionsLocked(sourceUserId); 15220 } 15221 } 15222 15223 @Override 15224 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 15225 mContext.enforceCallingOrSelfPermission( 15226 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 15227 int callingUid = Binder.getCallingUid(); 15228 enforceOwnerRights(ownerPackage, callingUid); 15229 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 15230 synchronized (mPackages) { 15231 CrossProfileIntentResolver resolver = 15232 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 15233 ArraySet<CrossProfileIntentFilter> set = 15234 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 15235 for (CrossProfileIntentFilter filter : set) { 15236 if (filter.getOwnerPackage().equals(ownerPackage)) { 15237 resolver.removeFilter(filter); 15238 } 15239 } 15240 scheduleWritePackageRestrictionsLocked(sourceUserId); 15241 } 15242 } 15243 15244 // Enforcing that callingUid is owning pkg on userId 15245 private void enforceOwnerRights(String pkg, int callingUid) { 15246 // The system owns everything. 15247 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 15248 return; 15249 } 15250 int callingUserId = UserHandle.getUserId(callingUid); 15251 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 15252 if (pi == null) { 15253 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 15254 + callingUserId); 15255 } 15256 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 15257 throw new SecurityException("Calling uid " + callingUid 15258 + " does not own package " + pkg); 15259 } 15260 } 15261 15262 @Override 15263 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 15264 Intent intent = new Intent(Intent.ACTION_MAIN); 15265 intent.addCategory(Intent.CATEGORY_HOME); 15266 15267 final int callingUserId = UserHandle.getCallingUserId(); 15268 List<ResolveInfo> list = queryIntentActivities(intent, null, 15269 PackageManager.GET_META_DATA, callingUserId); 15270 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 15271 true, false, false, callingUserId); 15272 15273 allHomeCandidates.clear(); 15274 if (list != null) { 15275 for (ResolveInfo ri : list) { 15276 allHomeCandidates.add(ri); 15277 } 15278 } 15279 return (preferred == null || preferred.activityInfo == null) 15280 ? null 15281 : new ComponentName(preferred.activityInfo.packageName, 15282 preferred.activityInfo.name); 15283 } 15284 15285 @Override 15286 public void setApplicationEnabledSetting(String appPackageName, 15287 int newState, int flags, int userId, String callingPackage) { 15288 if (!sUserManager.exists(userId)) return; 15289 if (callingPackage == null) { 15290 callingPackage = Integer.toString(Binder.getCallingUid()); 15291 } 15292 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 15293 } 15294 15295 @Override 15296 public void setComponentEnabledSetting(ComponentName componentName, 15297 int newState, int flags, int userId) { 15298 if (!sUserManager.exists(userId)) return; 15299 setEnabledSetting(componentName.getPackageName(), 15300 componentName.getClassName(), newState, flags, userId, null); 15301 } 15302 15303 private void setEnabledSetting(final String packageName, String className, int newState, 15304 final int flags, int userId, String callingPackage) { 15305 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 15306 || newState == COMPONENT_ENABLED_STATE_ENABLED 15307 || newState == COMPONENT_ENABLED_STATE_DISABLED 15308 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 15309 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 15310 throw new IllegalArgumentException("Invalid new component state: " 15311 + newState); 15312 } 15313 PackageSetting pkgSetting; 15314 final int uid = Binder.getCallingUid(); 15315 final int permission = mContext.checkCallingOrSelfPermission( 15316 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 15317 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 15318 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 15319 boolean sendNow = false; 15320 boolean isApp = (className == null); 15321 String componentName = isApp ? packageName : className; 15322 int packageUid = -1; 15323 ArrayList<String> components; 15324 15325 // writer 15326 synchronized (mPackages) { 15327 pkgSetting = mSettings.mPackages.get(packageName); 15328 if (pkgSetting == null) { 15329 if (className == null) { 15330 throw new IllegalArgumentException("Unknown package: " + packageName); 15331 } 15332 throw new IllegalArgumentException( 15333 "Unknown component: " + packageName + "/" + className); 15334 } 15335 // Allow root and verify that userId is not being specified by a different user 15336 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 15337 throw new SecurityException( 15338 "Permission Denial: attempt to change component state from pid=" 15339 + Binder.getCallingPid() 15340 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 15341 } 15342 if (className == null) { 15343 // We're dealing with an application/package level state change 15344 if (pkgSetting.getEnabled(userId) == newState) { 15345 // Nothing to do 15346 return; 15347 } 15348 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 15349 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 15350 // Don't care about who enables an app. 15351 callingPackage = null; 15352 } 15353 pkgSetting.setEnabled(newState, userId, callingPackage); 15354 // pkgSetting.pkg.mSetEnabled = newState; 15355 } else { 15356 // We're dealing with a component level state change 15357 // First, verify that this is a valid class name. 15358 PackageParser.Package pkg = pkgSetting.pkg; 15359 if (pkg == null || !pkg.hasComponentClassName(className)) { 15360 if (pkg != null && 15361 pkg.applicationInfo.targetSdkVersion >= 15362 Build.VERSION_CODES.JELLY_BEAN) { 15363 throw new IllegalArgumentException("Component class " + className 15364 + " does not exist in " + packageName); 15365 } else { 15366 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 15367 + className + " does not exist in " + packageName); 15368 } 15369 } 15370 switch (newState) { 15371 case COMPONENT_ENABLED_STATE_ENABLED: 15372 if (!pkgSetting.enableComponentLPw(className, userId)) { 15373 return; 15374 } 15375 break; 15376 case COMPONENT_ENABLED_STATE_DISABLED: 15377 if (!pkgSetting.disableComponentLPw(className, userId)) { 15378 return; 15379 } 15380 break; 15381 case COMPONENT_ENABLED_STATE_DEFAULT: 15382 if (!pkgSetting.restoreComponentLPw(className, userId)) { 15383 return; 15384 } 15385 break; 15386 default: 15387 Slog.e(TAG, "Invalid new component state: " + newState); 15388 return; 15389 } 15390 } 15391 scheduleWritePackageRestrictionsLocked(userId); 15392 components = mPendingBroadcasts.get(userId, packageName); 15393 final boolean newPackage = components == null; 15394 if (newPackage) { 15395 components = new ArrayList<String>(); 15396 } 15397 if (!components.contains(componentName)) { 15398 components.add(componentName); 15399 } 15400 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 15401 sendNow = true; 15402 // Purge entry from pending broadcast list if another one exists already 15403 // since we are sending one right away. 15404 mPendingBroadcasts.remove(userId, packageName); 15405 } else { 15406 if (newPackage) { 15407 mPendingBroadcasts.put(userId, packageName, components); 15408 } 15409 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 15410 // Schedule a message 15411 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 15412 } 15413 } 15414 } 15415 15416 long callingId = Binder.clearCallingIdentity(); 15417 try { 15418 if (sendNow) { 15419 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 15420 sendPackageChangedBroadcast(packageName, 15421 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 15422 } 15423 } finally { 15424 Binder.restoreCallingIdentity(callingId); 15425 } 15426 } 15427 15428 private void sendPackageChangedBroadcast(String packageName, 15429 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 15430 if (DEBUG_INSTALL) 15431 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 15432 + componentNames); 15433 Bundle extras = new Bundle(4); 15434 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 15435 String nameList[] = new String[componentNames.size()]; 15436 componentNames.toArray(nameList); 15437 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 15438 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 15439 extras.putInt(Intent.EXTRA_UID, packageUid); 15440 // If this is not reporting a change of the overall package, then only send it 15441 // to registered receivers. We don't want to launch a swath of apps for every 15442 // little component state change. 15443 final int flags = !componentNames.contains(packageName) 15444 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 15445 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 15446 new int[] {UserHandle.getUserId(packageUid)}); 15447 } 15448 15449 @Override 15450 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 15451 if (!sUserManager.exists(userId)) return; 15452 final int uid = Binder.getCallingUid(); 15453 final int permission = mContext.checkCallingOrSelfPermission( 15454 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 15455 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 15456 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 15457 // writer 15458 synchronized (mPackages) { 15459 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 15460 allowedByPermission, uid, userId)) { 15461 scheduleWritePackageRestrictionsLocked(userId); 15462 } 15463 } 15464 } 15465 15466 @Override 15467 public String getInstallerPackageName(String packageName) { 15468 // reader 15469 synchronized (mPackages) { 15470 return mSettings.getInstallerPackageNameLPr(packageName); 15471 } 15472 } 15473 15474 @Override 15475 public int getApplicationEnabledSetting(String packageName, int userId) { 15476 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 15477 int uid = Binder.getCallingUid(); 15478 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 15479 // reader 15480 synchronized (mPackages) { 15481 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 15482 } 15483 } 15484 15485 @Override 15486 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 15487 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 15488 int uid = Binder.getCallingUid(); 15489 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 15490 // reader 15491 synchronized (mPackages) { 15492 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 15493 } 15494 } 15495 15496 @Override 15497 public void enterSafeMode() { 15498 enforceSystemOrRoot("Only the system can request entering safe mode"); 15499 15500 if (!mSystemReady) { 15501 mSafeMode = true; 15502 } 15503 } 15504 15505 @Override 15506 public void systemReady() { 15507 mSystemReady = true; 15508 15509 // Read the compatibilty setting when the system is ready. 15510 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 15511 mContext.getContentResolver(), 15512 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 15513 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 15514 if (DEBUG_SETTINGS) { 15515 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 15516 } 15517 15518 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 15519 15520 synchronized (mPackages) { 15521 // Verify that all of the preferred activity components actually 15522 // exist. It is possible for applications to be updated and at 15523 // that point remove a previously declared activity component that 15524 // had been set as a preferred activity. We try to clean this up 15525 // the next time we encounter that preferred activity, but it is 15526 // possible for the user flow to never be able to return to that 15527 // situation so here we do a sanity check to make sure we haven't 15528 // left any junk around. 15529 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 15530 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15531 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15532 removed.clear(); 15533 for (PreferredActivity pa : pir.filterSet()) { 15534 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 15535 removed.add(pa); 15536 } 15537 } 15538 if (removed.size() > 0) { 15539 for (int r=0; r<removed.size(); r++) { 15540 PreferredActivity pa = removed.get(r); 15541 Slog.w(TAG, "Removing dangling preferred activity: " 15542 + pa.mPref.mComponent); 15543 pir.removeFilter(pa); 15544 } 15545 mSettings.writePackageRestrictionsLPr( 15546 mSettings.mPreferredActivities.keyAt(i)); 15547 } 15548 } 15549 15550 for (int userId : UserManagerService.getInstance().getUserIds()) { 15551 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 15552 grantPermissionsUserIds = ArrayUtils.appendInt( 15553 grantPermissionsUserIds, userId); 15554 } 15555 } 15556 } 15557 sUserManager.systemReady(); 15558 15559 // If we upgraded grant all default permissions before kicking off. 15560 for (int userId : grantPermissionsUserIds) { 15561 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 15562 } 15563 15564 // Kick off any messages waiting for system ready 15565 if (mPostSystemReadyMessages != null) { 15566 for (Message msg : mPostSystemReadyMessages) { 15567 msg.sendToTarget(); 15568 } 15569 mPostSystemReadyMessages = null; 15570 } 15571 15572 // Watch for external volumes that come and go over time 15573 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15574 storage.registerListener(mStorageListener); 15575 15576 mInstallerService.systemReady(); 15577 mPackageDexOptimizer.systemReady(); 15578 15579 MountServiceInternal mountServiceInternal = LocalServices.getService( 15580 MountServiceInternal.class); 15581 mountServiceInternal.addExternalStoragePolicy( 15582 new MountServiceInternal.ExternalStorageMountPolicy() { 15583 @Override 15584 public int getMountMode(int uid, String packageName) { 15585 if (Process.isIsolated(uid)) { 15586 return Zygote.MOUNT_EXTERNAL_NONE; 15587 } 15588 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 15589 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15590 } 15591 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15592 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15593 } 15594 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15595 return Zygote.MOUNT_EXTERNAL_READ; 15596 } 15597 return Zygote.MOUNT_EXTERNAL_WRITE; 15598 } 15599 15600 @Override 15601 public boolean hasExternalStorage(int uid, String packageName) { 15602 return true; 15603 } 15604 }); 15605 } 15606 15607 @Override 15608 public boolean isSafeMode() { 15609 return mSafeMode; 15610 } 15611 15612 @Override 15613 public boolean hasSystemUidErrors() { 15614 return mHasSystemUidErrors; 15615 } 15616 15617 static String arrayToString(int[] array) { 15618 StringBuffer buf = new StringBuffer(128); 15619 buf.append('['); 15620 if (array != null) { 15621 for (int i=0; i<array.length; i++) { 15622 if (i > 0) buf.append(", "); 15623 buf.append(array[i]); 15624 } 15625 } 15626 buf.append(']'); 15627 return buf.toString(); 15628 } 15629 15630 static class DumpState { 15631 public static final int DUMP_LIBS = 1 << 0; 15632 public static final int DUMP_FEATURES = 1 << 1; 15633 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 15634 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 15635 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 15636 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 15637 public static final int DUMP_PERMISSIONS = 1 << 6; 15638 public static final int DUMP_PACKAGES = 1 << 7; 15639 public static final int DUMP_SHARED_USERS = 1 << 8; 15640 public static final int DUMP_MESSAGES = 1 << 9; 15641 public static final int DUMP_PROVIDERS = 1 << 10; 15642 public static final int DUMP_VERIFIERS = 1 << 11; 15643 public static final int DUMP_PREFERRED = 1 << 12; 15644 public static final int DUMP_PREFERRED_XML = 1 << 13; 15645 public static final int DUMP_KEYSETS = 1 << 14; 15646 public static final int DUMP_VERSION = 1 << 15; 15647 public static final int DUMP_INSTALLS = 1 << 16; 15648 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 15649 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 15650 15651 public static final int OPTION_SHOW_FILTERS = 1 << 0; 15652 15653 private int mTypes; 15654 15655 private int mOptions; 15656 15657 private boolean mTitlePrinted; 15658 15659 private SharedUserSetting mSharedUser; 15660 15661 public boolean isDumping(int type) { 15662 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 15663 return true; 15664 } 15665 15666 return (mTypes & type) != 0; 15667 } 15668 15669 public void setDump(int type) { 15670 mTypes |= type; 15671 } 15672 15673 public boolean isOptionEnabled(int option) { 15674 return (mOptions & option) != 0; 15675 } 15676 15677 public void setOptionEnabled(int option) { 15678 mOptions |= option; 15679 } 15680 15681 public boolean onTitlePrinted() { 15682 final boolean printed = mTitlePrinted; 15683 mTitlePrinted = true; 15684 return printed; 15685 } 15686 15687 public boolean getTitlePrinted() { 15688 return mTitlePrinted; 15689 } 15690 15691 public void setTitlePrinted(boolean enabled) { 15692 mTitlePrinted = enabled; 15693 } 15694 15695 public SharedUserSetting getSharedUser() { 15696 return mSharedUser; 15697 } 15698 15699 public void setSharedUser(SharedUserSetting user) { 15700 mSharedUser = user; 15701 } 15702 } 15703 15704 @Override 15705 public void onShellCommand(FileDescriptor in, FileDescriptor out, 15706 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 15707 (new PackageManagerShellCommand(this)).exec( 15708 this, in, out, err, args, resultReceiver); 15709 } 15710 15711 @Override 15712 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 15713 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 15714 != PackageManager.PERMISSION_GRANTED) { 15715 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 15716 + Binder.getCallingPid() 15717 + ", uid=" + Binder.getCallingUid() 15718 + " without permission " 15719 + android.Manifest.permission.DUMP); 15720 return; 15721 } 15722 15723 DumpState dumpState = new DumpState(); 15724 boolean fullPreferred = false; 15725 boolean checkin = false; 15726 15727 String packageName = null; 15728 ArraySet<String> permissionNames = null; 15729 15730 int opti = 0; 15731 while (opti < args.length) { 15732 String opt = args[opti]; 15733 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 15734 break; 15735 } 15736 opti++; 15737 15738 if ("-a".equals(opt)) { 15739 // Right now we only know how to print all. 15740 } else if ("-h".equals(opt)) { 15741 pw.println("Package manager dump options:"); 15742 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 15743 pw.println(" --checkin: dump for a checkin"); 15744 pw.println(" -f: print details of intent filters"); 15745 pw.println(" -h: print this help"); 15746 pw.println(" cmd may be one of:"); 15747 pw.println(" l[ibraries]: list known shared libraries"); 15748 pw.println(" f[eatures]: list device features"); 15749 pw.println(" k[eysets]: print known keysets"); 15750 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 15751 pw.println(" perm[issions]: dump permissions"); 15752 pw.println(" permission [name ...]: dump declaration and use of given permission"); 15753 pw.println(" pref[erred]: print preferred package settings"); 15754 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 15755 pw.println(" prov[iders]: dump content providers"); 15756 pw.println(" p[ackages]: dump installed packages"); 15757 pw.println(" s[hared-users]: dump shared user IDs"); 15758 pw.println(" m[essages]: print collected runtime messages"); 15759 pw.println(" v[erifiers]: print package verifier info"); 15760 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 15761 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 15762 pw.println(" version: print database version info"); 15763 pw.println(" write: write current settings now"); 15764 pw.println(" installs: details about install sessions"); 15765 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 15766 pw.println(" <package.name>: info about given package"); 15767 return; 15768 } else if ("--checkin".equals(opt)) { 15769 checkin = true; 15770 } else if ("-f".equals(opt)) { 15771 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15772 } else { 15773 pw.println("Unknown argument: " + opt + "; use -h for help"); 15774 } 15775 } 15776 15777 // Is the caller requesting to dump a particular piece of data? 15778 if (opti < args.length) { 15779 String cmd = args[opti]; 15780 opti++; 15781 // Is this a package name? 15782 if ("android".equals(cmd) || cmd.contains(".")) { 15783 packageName = cmd; 15784 // When dumping a single package, we always dump all of its 15785 // filter information since the amount of data will be reasonable. 15786 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15787 } else if ("check-permission".equals(cmd)) { 15788 if (opti >= args.length) { 15789 pw.println("Error: check-permission missing permission argument"); 15790 return; 15791 } 15792 String perm = args[opti]; 15793 opti++; 15794 if (opti >= args.length) { 15795 pw.println("Error: check-permission missing package argument"); 15796 return; 15797 } 15798 String pkg = args[opti]; 15799 opti++; 15800 int user = UserHandle.getUserId(Binder.getCallingUid()); 15801 if (opti < args.length) { 15802 try { 15803 user = Integer.parseInt(args[opti]); 15804 } catch (NumberFormatException e) { 15805 pw.println("Error: check-permission user argument is not a number: " 15806 + args[opti]); 15807 return; 15808 } 15809 } 15810 pw.println(checkPermission(perm, pkg, user)); 15811 return; 15812 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 15813 dumpState.setDump(DumpState.DUMP_LIBS); 15814 } else if ("f".equals(cmd) || "features".equals(cmd)) { 15815 dumpState.setDump(DumpState.DUMP_FEATURES); 15816 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 15817 if (opti >= args.length) { 15818 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 15819 | DumpState.DUMP_SERVICE_RESOLVERS 15820 | DumpState.DUMP_RECEIVER_RESOLVERS 15821 | DumpState.DUMP_CONTENT_RESOLVERS); 15822 } else { 15823 while (opti < args.length) { 15824 String name = args[opti]; 15825 if ("a".equals(name) || "activity".equals(name)) { 15826 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 15827 } else if ("s".equals(name) || "service".equals(name)) { 15828 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 15829 } else if ("r".equals(name) || "receiver".equals(name)) { 15830 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 15831 } else if ("c".equals(name) || "content".equals(name)) { 15832 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 15833 } else { 15834 pw.println("Error: unknown resolver table type: " + name); 15835 return; 15836 } 15837 opti++; 15838 } 15839 } 15840 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 15841 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 15842 } else if ("permission".equals(cmd)) { 15843 if (opti >= args.length) { 15844 pw.println("Error: permission requires permission name"); 15845 return; 15846 } 15847 permissionNames = new ArraySet<>(); 15848 while (opti < args.length) { 15849 permissionNames.add(args[opti]); 15850 opti++; 15851 } 15852 dumpState.setDump(DumpState.DUMP_PERMISSIONS 15853 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 15854 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 15855 dumpState.setDump(DumpState.DUMP_PREFERRED); 15856 } else if ("preferred-xml".equals(cmd)) { 15857 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 15858 if (opti < args.length && "--full".equals(args[opti])) { 15859 fullPreferred = true; 15860 opti++; 15861 } 15862 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 15863 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 15864 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 15865 dumpState.setDump(DumpState.DUMP_PACKAGES); 15866 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 15867 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 15868 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 15869 dumpState.setDump(DumpState.DUMP_PROVIDERS); 15870 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 15871 dumpState.setDump(DumpState.DUMP_MESSAGES); 15872 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 15873 dumpState.setDump(DumpState.DUMP_VERIFIERS); 15874 } else if ("i".equals(cmd) || "ifv".equals(cmd) 15875 || "intent-filter-verifiers".equals(cmd)) { 15876 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 15877 } else if ("version".equals(cmd)) { 15878 dumpState.setDump(DumpState.DUMP_VERSION); 15879 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 15880 dumpState.setDump(DumpState.DUMP_KEYSETS); 15881 } else if ("installs".equals(cmd)) { 15882 dumpState.setDump(DumpState.DUMP_INSTALLS); 15883 } else if ("write".equals(cmd)) { 15884 synchronized (mPackages) { 15885 mSettings.writeLPr(); 15886 pw.println("Settings written."); 15887 return; 15888 } 15889 } 15890 } 15891 15892 if (checkin) { 15893 pw.println("vers,1"); 15894 } 15895 15896 // reader 15897 synchronized (mPackages) { 15898 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 15899 if (!checkin) { 15900 if (dumpState.onTitlePrinted()) 15901 pw.println(); 15902 pw.println("Database versions:"); 15903 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 15904 } 15905 } 15906 15907 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 15908 if (!checkin) { 15909 if (dumpState.onTitlePrinted()) 15910 pw.println(); 15911 pw.println("Verifiers:"); 15912 pw.print(" Required: "); 15913 pw.print(mRequiredVerifierPackage); 15914 pw.print(" (uid="); 15915 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 15916 UserHandle.USER_SYSTEM)); 15917 pw.println(")"); 15918 } else if (mRequiredVerifierPackage != null) { 15919 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 15920 pw.print(","); 15921 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 15922 UserHandle.USER_SYSTEM)); 15923 } 15924 } 15925 15926 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 15927 packageName == null) { 15928 if (mIntentFilterVerifierComponent != null) { 15929 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 15930 if (!checkin) { 15931 if (dumpState.onTitlePrinted()) 15932 pw.println(); 15933 pw.println("Intent Filter Verifier:"); 15934 pw.print(" Using: "); 15935 pw.print(verifierPackageName); 15936 pw.print(" (uid="); 15937 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 15938 UserHandle.USER_SYSTEM)); 15939 pw.println(")"); 15940 } else if (verifierPackageName != null) { 15941 pw.print("ifv,"); pw.print(verifierPackageName); 15942 pw.print(","); 15943 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 15944 UserHandle.USER_SYSTEM)); 15945 } 15946 } else { 15947 pw.println(); 15948 pw.println("No Intent Filter Verifier available!"); 15949 } 15950 } 15951 15952 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 15953 boolean printedHeader = false; 15954 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 15955 while (it.hasNext()) { 15956 String name = it.next(); 15957 SharedLibraryEntry ent = mSharedLibraries.get(name); 15958 if (!checkin) { 15959 if (!printedHeader) { 15960 if (dumpState.onTitlePrinted()) 15961 pw.println(); 15962 pw.println("Libraries:"); 15963 printedHeader = true; 15964 } 15965 pw.print(" "); 15966 } else { 15967 pw.print("lib,"); 15968 } 15969 pw.print(name); 15970 if (!checkin) { 15971 pw.print(" -> "); 15972 } 15973 if (ent.path != null) { 15974 if (!checkin) { 15975 pw.print("(jar) "); 15976 pw.print(ent.path); 15977 } else { 15978 pw.print(",jar,"); 15979 pw.print(ent.path); 15980 } 15981 } else { 15982 if (!checkin) { 15983 pw.print("(apk) "); 15984 pw.print(ent.apk); 15985 } else { 15986 pw.print(",apk,"); 15987 pw.print(ent.apk); 15988 } 15989 } 15990 pw.println(); 15991 } 15992 } 15993 15994 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 15995 if (dumpState.onTitlePrinted()) 15996 pw.println(); 15997 if (!checkin) { 15998 pw.println("Features:"); 15999 } 16000 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 16001 while (it.hasNext()) { 16002 String name = it.next(); 16003 if (!checkin) { 16004 pw.print(" "); 16005 } else { 16006 pw.print("feat,"); 16007 } 16008 pw.println(name); 16009 } 16010 } 16011 16012 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 16013 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 16014 : "Activity Resolver Table:", " ", packageName, 16015 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16016 dumpState.setTitlePrinted(true); 16017 } 16018 } 16019 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 16020 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 16021 : "Receiver Resolver Table:", " ", packageName, 16022 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16023 dumpState.setTitlePrinted(true); 16024 } 16025 } 16026 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 16027 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 16028 : "Service Resolver Table:", " ", packageName, 16029 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16030 dumpState.setTitlePrinted(true); 16031 } 16032 } 16033 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 16034 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 16035 : "Provider Resolver Table:", " ", packageName, 16036 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16037 dumpState.setTitlePrinted(true); 16038 } 16039 } 16040 16041 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 16042 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16043 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16044 int user = mSettings.mPreferredActivities.keyAt(i); 16045 if (pir.dump(pw, 16046 dumpState.getTitlePrinted() 16047 ? "\nPreferred Activities User " + user + ":" 16048 : "Preferred Activities User " + user + ":", " ", 16049 packageName, true, false)) { 16050 dumpState.setTitlePrinted(true); 16051 } 16052 } 16053 } 16054 16055 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 16056 pw.flush(); 16057 FileOutputStream fout = new FileOutputStream(fd); 16058 BufferedOutputStream str = new BufferedOutputStream(fout); 16059 XmlSerializer serializer = new FastXmlSerializer(); 16060 try { 16061 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 16062 serializer.startDocument(null, true); 16063 serializer.setFeature( 16064 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 16065 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 16066 serializer.endDocument(); 16067 serializer.flush(); 16068 } catch (IllegalArgumentException e) { 16069 pw.println("Failed writing: " + e); 16070 } catch (IllegalStateException e) { 16071 pw.println("Failed writing: " + e); 16072 } catch (IOException e) { 16073 pw.println("Failed writing: " + e); 16074 } 16075 } 16076 16077 if (!checkin 16078 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 16079 && packageName == null) { 16080 pw.println(); 16081 int count = mSettings.mPackages.size(); 16082 if (count == 0) { 16083 pw.println("No applications!"); 16084 pw.println(); 16085 } else { 16086 final String prefix = " "; 16087 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 16088 if (allPackageSettings.size() == 0) { 16089 pw.println("No domain preferred apps!"); 16090 pw.println(); 16091 } else { 16092 pw.println("App verification status:"); 16093 pw.println(); 16094 count = 0; 16095 for (PackageSetting ps : allPackageSettings) { 16096 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 16097 if (ivi == null || ivi.getPackageName() == null) continue; 16098 pw.println(prefix + "Package: " + ivi.getPackageName()); 16099 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 16100 pw.println(prefix + "Status: " + ivi.getStatusString()); 16101 pw.println(); 16102 count++; 16103 } 16104 if (count == 0) { 16105 pw.println(prefix + "No app verification established."); 16106 pw.println(); 16107 } 16108 for (int userId : sUserManager.getUserIds()) { 16109 pw.println("App linkages for user " + userId + ":"); 16110 pw.println(); 16111 count = 0; 16112 for (PackageSetting ps : allPackageSettings) { 16113 final long status = ps.getDomainVerificationStatusForUser(userId); 16114 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 16115 continue; 16116 } 16117 pw.println(prefix + "Package: " + ps.name); 16118 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 16119 String statusStr = IntentFilterVerificationInfo. 16120 getStatusStringFromValue(status); 16121 pw.println(prefix + "Status: " + statusStr); 16122 pw.println(); 16123 count++; 16124 } 16125 if (count == 0) { 16126 pw.println(prefix + "No configured app linkages."); 16127 pw.println(); 16128 } 16129 } 16130 } 16131 } 16132 } 16133 16134 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 16135 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 16136 if (packageName == null && permissionNames == null) { 16137 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 16138 if (iperm == 0) { 16139 if (dumpState.onTitlePrinted()) 16140 pw.println(); 16141 pw.println("AppOp Permissions:"); 16142 } 16143 pw.print(" AppOp Permission "); 16144 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 16145 pw.println(":"); 16146 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 16147 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 16148 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 16149 } 16150 } 16151 } 16152 } 16153 16154 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 16155 boolean printedSomething = false; 16156 for (PackageParser.Provider p : mProviders.mProviders.values()) { 16157 if (packageName != null && !packageName.equals(p.info.packageName)) { 16158 continue; 16159 } 16160 if (!printedSomething) { 16161 if (dumpState.onTitlePrinted()) 16162 pw.println(); 16163 pw.println("Registered ContentProviders:"); 16164 printedSomething = true; 16165 } 16166 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 16167 pw.print(" "); pw.println(p.toString()); 16168 } 16169 printedSomething = false; 16170 for (Map.Entry<String, PackageParser.Provider> entry : 16171 mProvidersByAuthority.entrySet()) { 16172 PackageParser.Provider p = entry.getValue(); 16173 if (packageName != null && !packageName.equals(p.info.packageName)) { 16174 continue; 16175 } 16176 if (!printedSomething) { 16177 if (dumpState.onTitlePrinted()) 16178 pw.println(); 16179 pw.println("ContentProvider Authorities:"); 16180 printedSomething = true; 16181 } 16182 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 16183 pw.print(" "); pw.println(p.toString()); 16184 if (p.info != null && p.info.applicationInfo != null) { 16185 final String appInfo = p.info.applicationInfo.toString(); 16186 pw.print(" applicationInfo="); pw.println(appInfo); 16187 } 16188 } 16189 } 16190 16191 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 16192 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 16193 } 16194 16195 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 16196 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 16197 } 16198 16199 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 16200 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 16201 } 16202 16203 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 16204 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 16205 } 16206 16207 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 16208 // XXX should handle packageName != null by dumping only install data that 16209 // the given package is involved with. 16210 if (dumpState.onTitlePrinted()) pw.println(); 16211 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 16212 } 16213 16214 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 16215 if (dumpState.onTitlePrinted()) pw.println(); 16216 mSettings.dumpReadMessagesLPr(pw, dumpState); 16217 16218 pw.println(); 16219 pw.println("Package warning messages:"); 16220 BufferedReader in = null; 16221 String line = null; 16222 try { 16223 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 16224 while ((line = in.readLine()) != null) { 16225 if (line.contains("ignored: updated version")) continue; 16226 pw.println(line); 16227 } 16228 } catch (IOException ignored) { 16229 } finally { 16230 IoUtils.closeQuietly(in); 16231 } 16232 } 16233 16234 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 16235 BufferedReader in = null; 16236 String line = null; 16237 try { 16238 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 16239 while ((line = in.readLine()) != null) { 16240 if (line.contains("ignored: updated version")) continue; 16241 pw.print("msg,"); 16242 pw.println(line); 16243 } 16244 } catch (IOException ignored) { 16245 } finally { 16246 IoUtils.closeQuietly(in); 16247 } 16248 } 16249 } 16250 } 16251 16252 private String dumpDomainString(String packageName) { 16253 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 16254 List<IntentFilter> filters = getAllIntentFilters(packageName); 16255 16256 ArraySet<String> result = new ArraySet<>(); 16257 if (iviList.size() > 0) { 16258 for (IntentFilterVerificationInfo ivi : iviList) { 16259 for (String host : ivi.getDomains()) { 16260 result.add(host); 16261 } 16262 } 16263 } 16264 if (filters != null && filters.size() > 0) { 16265 for (IntentFilter filter : filters) { 16266 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 16267 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 16268 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 16269 result.addAll(filter.getHostsList()); 16270 } 16271 } 16272 } 16273 16274 StringBuilder sb = new StringBuilder(result.size() * 16); 16275 for (String domain : result) { 16276 if (sb.length() > 0) sb.append(" "); 16277 sb.append(domain); 16278 } 16279 return sb.toString(); 16280 } 16281 16282 // ------- apps on sdcard specific code ------- 16283 static final boolean DEBUG_SD_INSTALL = false; 16284 16285 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 16286 16287 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 16288 16289 private boolean mMediaMounted = false; 16290 16291 static String getEncryptKey() { 16292 try { 16293 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 16294 SD_ENCRYPTION_KEYSTORE_NAME); 16295 if (sdEncKey == null) { 16296 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 16297 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 16298 if (sdEncKey == null) { 16299 Slog.e(TAG, "Failed to create encryption keys"); 16300 return null; 16301 } 16302 } 16303 return sdEncKey; 16304 } catch (NoSuchAlgorithmException nsae) { 16305 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 16306 return null; 16307 } catch (IOException ioe) { 16308 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 16309 return null; 16310 } 16311 } 16312 16313 /* 16314 * Update media status on PackageManager. 16315 */ 16316 @Override 16317 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 16318 int callingUid = Binder.getCallingUid(); 16319 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 16320 throw new SecurityException("Media status can only be updated by the system"); 16321 } 16322 // reader; this apparently protects mMediaMounted, but should probably 16323 // be a different lock in that case. 16324 synchronized (mPackages) { 16325 Log.i(TAG, "Updating external media status from " 16326 + (mMediaMounted ? "mounted" : "unmounted") + " to " 16327 + (mediaStatus ? "mounted" : "unmounted")); 16328 if (DEBUG_SD_INSTALL) 16329 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 16330 + ", mMediaMounted=" + mMediaMounted); 16331 if (mediaStatus == mMediaMounted) { 16332 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 16333 : 0, -1); 16334 mHandler.sendMessage(msg); 16335 return; 16336 } 16337 mMediaMounted = mediaStatus; 16338 } 16339 // Queue up an async operation since the package installation may take a 16340 // little while. 16341 mHandler.post(new Runnable() { 16342 public void run() { 16343 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 16344 } 16345 }); 16346 } 16347 16348 /** 16349 * Called by MountService when the initial ASECs to scan are available. 16350 * Should block until all the ASEC containers are finished being scanned. 16351 */ 16352 public void scanAvailableAsecs() { 16353 updateExternalMediaStatusInner(true, false, false); 16354 } 16355 16356 /* 16357 * Collect information of applications on external media, map them against 16358 * existing containers and update information based on current mount status. 16359 * Please note that we always have to report status if reportStatus has been 16360 * set to true especially when unloading packages. 16361 */ 16362 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 16363 boolean externalStorage) { 16364 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 16365 int[] uidArr = EmptyArray.INT; 16366 16367 final String[] list = PackageHelper.getSecureContainerList(); 16368 if (ArrayUtils.isEmpty(list)) { 16369 Log.i(TAG, "No secure containers found"); 16370 } else { 16371 // Process list of secure containers and categorize them 16372 // as active or stale based on their package internal state. 16373 16374 // reader 16375 synchronized (mPackages) { 16376 for (String cid : list) { 16377 // Leave stages untouched for now; installer service owns them 16378 if (PackageInstallerService.isStageName(cid)) continue; 16379 16380 if (DEBUG_SD_INSTALL) 16381 Log.i(TAG, "Processing container " + cid); 16382 String pkgName = getAsecPackageName(cid); 16383 if (pkgName == null) { 16384 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 16385 continue; 16386 } 16387 if (DEBUG_SD_INSTALL) 16388 Log.i(TAG, "Looking for pkg : " + pkgName); 16389 16390 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16391 if (ps == null) { 16392 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 16393 continue; 16394 } 16395 16396 /* 16397 * Skip packages that are not external if we're unmounting 16398 * external storage. 16399 */ 16400 if (externalStorage && !isMounted && !isExternal(ps)) { 16401 continue; 16402 } 16403 16404 final AsecInstallArgs args = new AsecInstallArgs(cid, 16405 getAppDexInstructionSets(ps), ps.isForwardLocked()); 16406 // The package status is changed only if the code path 16407 // matches between settings and the container id. 16408 if (ps.codePathString != null 16409 && ps.codePathString.startsWith(args.getCodePath())) { 16410 if (DEBUG_SD_INSTALL) { 16411 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 16412 + " at code path: " + ps.codePathString); 16413 } 16414 16415 // We do have a valid package installed on sdcard 16416 processCids.put(args, ps.codePathString); 16417 final int uid = ps.appId; 16418 if (uid != -1) { 16419 uidArr = ArrayUtils.appendInt(uidArr, uid); 16420 } 16421 } else { 16422 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 16423 + ps.codePathString); 16424 } 16425 } 16426 } 16427 16428 Arrays.sort(uidArr); 16429 } 16430 16431 // Process packages with valid entries. 16432 if (isMounted) { 16433 if (DEBUG_SD_INSTALL) 16434 Log.i(TAG, "Loading packages"); 16435 loadMediaPackages(processCids, uidArr, externalStorage); 16436 startCleaningPackages(); 16437 mInstallerService.onSecureContainersAvailable(); 16438 } else { 16439 if (DEBUG_SD_INSTALL) 16440 Log.i(TAG, "Unloading packages"); 16441 unloadMediaPackages(processCids, uidArr, reportStatus); 16442 } 16443 } 16444 16445 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16446 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 16447 final int size = infos.size(); 16448 final String[] packageNames = new String[size]; 16449 final int[] packageUids = new int[size]; 16450 for (int i = 0; i < size; i++) { 16451 final ApplicationInfo info = infos.get(i); 16452 packageNames[i] = info.packageName; 16453 packageUids[i] = info.uid; 16454 } 16455 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 16456 finishedReceiver); 16457 } 16458 16459 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16460 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 16461 sendResourcesChangedBroadcast(mediaStatus, replacing, 16462 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 16463 } 16464 16465 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16466 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 16467 int size = pkgList.length; 16468 if (size > 0) { 16469 // Send broadcasts here 16470 Bundle extras = new Bundle(); 16471 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 16472 if (uidArr != null) { 16473 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 16474 } 16475 if (replacing) { 16476 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 16477 } 16478 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 16479 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 16480 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 16481 } 16482 } 16483 16484 /* 16485 * Look at potentially valid container ids from processCids If package 16486 * information doesn't match the one on record or package scanning fails, 16487 * the cid is added to list of removeCids. We currently don't delete stale 16488 * containers. 16489 */ 16490 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 16491 boolean externalStorage) { 16492 ArrayList<String> pkgList = new ArrayList<String>(); 16493 Set<AsecInstallArgs> keys = processCids.keySet(); 16494 16495 for (AsecInstallArgs args : keys) { 16496 String codePath = processCids.get(args); 16497 if (DEBUG_SD_INSTALL) 16498 Log.i(TAG, "Loading container : " + args.cid); 16499 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 16500 try { 16501 // Make sure there are no container errors first. 16502 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 16503 Slog.e(TAG, "Failed to mount cid : " + args.cid 16504 + " when installing from sdcard"); 16505 continue; 16506 } 16507 // Check code path here. 16508 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 16509 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 16510 + " does not match one in settings " + codePath); 16511 continue; 16512 } 16513 // Parse package 16514 int parseFlags = mDefParseFlags; 16515 if (args.isExternalAsec()) { 16516 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 16517 } 16518 if (args.isFwdLocked()) { 16519 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 16520 } 16521 16522 synchronized (mInstallLock) { 16523 PackageParser.Package pkg = null; 16524 try { 16525 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 16526 } catch (PackageManagerException e) { 16527 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 16528 } 16529 // Scan the package 16530 if (pkg != null) { 16531 /* 16532 * TODO why is the lock being held? doPostInstall is 16533 * called in other places without the lock. This needs 16534 * to be straightened out. 16535 */ 16536 // writer 16537 synchronized (mPackages) { 16538 retCode = PackageManager.INSTALL_SUCCEEDED; 16539 pkgList.add(pkg.packageName); 16540 // Post process args 16541 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 16542 pkg.applicationInfo.uid); 16543 } 16544 } else { 16545 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 16546 } 16547 } 16548 16549 } finally { 16550 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 16551 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 16552 } 16553 } 16554 } 16555 // writer 16556 synchronized (mPackages) { 16557 // If the platform SDK has changed since the last time we booted, 16558 // we need to re-grant app permission to catch any new ones that 16559 // appear. This is really a hack, and means that apps can in some 16560 // cases get permissions that the user didn't initially explicitly 16561 // allow... it would be nice to have some better way to handle 16562 // this situation. 16563 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 16564 : mSettings.getInternalVersion(); 16565 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 16566 : StorageManager.UUID_PRIVATE_INTERNAL; 16567 16568 int updateFlags = UPDATE_PERMISSIONS_ALL; 16569 if (ver.sdkVersion != mSdkVersion) { 16570 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16571 + mSdkVersion + "; regranting permissions for external"); 16572 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16573 } 16574 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 16575 16576 // Yay, everything is now upgraded 16577 ver.forceCurrent(); 16578 16579 // can downgrade to reader 16580 // Persist settings 16581 mSettings.writeLPr(); 16582 } 16583 // Send a broadcast to let everyone know we are done processing 16584 if (pkgList.size() > 0) { 16585 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 16586 } 16587 } 16588 16589 /* 16590 * Utility method to unload a list of specified containers 16591 */ 16592 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 16593 // Just unmount all valid containers. 16594 for (AsecInstallArgs arg : cidArgs) { 16595 synchronized (mInstallLock) { 16596 arg.doPostDeleteLI(false); 16597 } 16598 } 16599 } 16600 16601 /* 16602 * Unload packages mounted on external media. This involves deleting package 16603 * data from internal structures, sending broadcasts about diabled packages, 16604 * gc'ing to free up references, unmounting all secure containers 16605 * corresponding to packages on external media, and posting a 16606 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 16607 * that we always have to post this message if status has been requested no 16608 * matter what. 16609 */ 16610 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 16611 final boolean reportStatus) { 16612 if (DEBUG_SD_INSTALL) 16613 Log.i(TAG, "unloading media packages"); 16614 ArrayList<String> pkgList = new ArrayList<String>(); 16615 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 16616 final Set<AsecInstallArgs> keys = processCids.keySet(); 16617 for (AsecInstallArgs args : keys) { 16618 String pkgName = args.getPackageName(); 16619 if (DEBUG_SD_INSTALL) 16620 Log.i(TAG, "Trying to unload pkg : " + pkgName); 16621 // Delete package internally 16622 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16623 synchronized (mInstallLock) { 16624 boolean res = deletePackageLI(pkgName, null, false, null, null, 16625 PackageManager.DELETE_KEEP_DATA, outInfo, false); 16626 if (res) { 16627 pkgList.add(pkgName); 16628 } else { 16629 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 16630 failedList.add(args); 16631 } 16632 } 16633 } 16634 16635 // reader 16636 synchronized (mPackages) { 16637 // We didn't update the settings after removing each package; 16638 // write them now for all packages. 16639 mSettings.writeLPr(); 16640 } 16641 16642 // We have to absolutely send UPDATED_MEDIA_STATUS only 16643 // after confirming that all the receivers processed the ordered 16644 // broadcast when packages get disabled, force a gc to clean things up. 16645 // and unload all the containers. 16646 if (pkgList.size() > 0) { 16647 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 16648 new IIntentReceiver.Stub() { 16649 public void performReceive(Intent intent, int resultCode, String data, 16650 Bundle extras, boolean ordered, boolean sticky, 16651 int sendingUser) throws RemoteException { 16652 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 16653 reportStatus ? 1 : 0, 1, keys); 16654 mHandler.sendMessage(msg); 16655 } 16656 }); 16657 } else { 16658 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 16659 keys); 16660 mHandler.sendMessage(msg); 16661 } 16662 } 16663 16664 private void loadPrivatePackages(final VolumeInfo vol) { 16665 mHandler.post(new Runnable() { 16666 @Override 16667 public void run() { 16668 loadPrivatePackagesInner(vol); 16669 } 16670 }); 16671 } 16672 16673 private void loadPrivatePackagesInner(VolumeInfo vol) { 16674 final String volumeUuid = vol.fsUuid; 16675 if (TextUtils.isEmpty(volumeUuid)) { 16676 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 16677 return; 16678 } 16679 16680 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 16681 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 16682 16683 final VersionInfo ver; 16684 final List<PackageSetting> packages; 16685 synchronized (mPackages) { 16686 ver = mSettings.findOrCreateVersion(volumeUuid); 16687 packages = mSettings.getVolumePackagesLPr(volumeUuid); 16688 } 16689 16690 // TODO: introduce a new concept similar to "frozen" to prevent these 16691 // apps from being launched until after data has been fully reconciled 16692 for (PackageSetting ps : packages) { 16693 synchronized (mInstallLock) { 16694 final PackageParser.Package pkg; 16695 try { 16696 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 16697 loaded.add(pkg.applicationInfo); 16698 16699 } catch (PackageManagerException e) { 16700 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 16701 } 16702 16703 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 16704 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 16705 } 16706 } 16707 } 16708 16709 // Reconcile app data for all started/unlocked users 16710 final UserManager um = mContext.getSystemService(UserManager.class); 16711 for (UserInfo user : um.getUsers()) { 16712 if (um.isUserUnlocked(user.id)) { 16713 reconcileAppsData(volumeUuid, user.id, 16714 Installer.FLAG_DE_STORAGE | Installer.FLAG_CE_STORAGE); 16715 } else if (um.isUserRunning(user.id)) { 16716 reconcileAppsData(volumeUuid, user.id, Installer.FLAG_DE_STORAGE); 16717 } else { 16718 continue; 16719 } 16720 } 16721 16722 synchronized (mPackages) { 16723 int updateFlags = UPDATE_PERMISSIONS_ALL; 16724 if (ver.sdkVersion != mSdkVersion) { 16725 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16726 + mSdkVersion + "; regranting permissions for " + volumeUuid); 16727 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16728 } 16729 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 16730 16731 // Yay, everything is now upgraded 16732 ver.forceCurrent(); 16733 16734 mSettings.writeLPr(); 16735 } 16736 16737 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 16738 sendResourcesChangedBroadcast(true, false, loaded, null); 16739 } 16740 16741 private void unloadPrivatePackages(final VolumeInfo vol) { 16742 mHandler.post(new Runnable() { 16743 @Override 16744 public void run() { 16745 unloadPrivatePackagesInner(vol); 16746 } 16747 }); 16748 } 16749 16750 private void unloadPrivatePackagesInner(VolumeInfo vol) { 16751 final String volumeUuid = vol.fsUuid; 16752 if (TextUtils.isEmpty(volumeUuid)) { 16753 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 16754 return; 16755 } 16756 16757 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 16758 synchronized (mInstallLock) { 16759 synchronized (mPackages) { 16760 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 16761 for (PackageSetting ps : packages) { 16762 if (ps.pkg == null) continue; 16763 16764 final ApplicationInfo info = ps.pkg.applicationInfo; 16765 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16766 if (deletePackageLI(ps.name, null, false, null, null, 16767 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 16768 unloaded.add(info); 16769 } else { 16770 Slog.w(TAG, "Failed to unload " + ps.codePath); 16771 } 16772 } 16773 16774 mSettings.writeLPr(); 16775 } 16776 } 16777 16778 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 16779 sendResourcesChangedBroadcast(false, false, unloaded, null); 16780 } 16781 16782 /** 16783 * Examine all users present on given mounted volume, and destroy data 16784 * belonging to users that are no longer valid, or whose user ID has been 16785 * recycled. 16786 */ 16787 private void reconcileUsers(String volumeUuid) { 16788 final File[] files = FileUtils 16789 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 16790 for (File file : files) { 16791 if (!file.isDirectory()) continue; 16792 16793 final int userId; 16794 final UserInfo info; 16795 try { 16796 userId = Integer.parseInt(file.getName()); 16797 info = sUserManager.getUserInfo(userId); 16798 } catch (NumberFormatException e) { 16799 Slog.w(TAG, "Invalid user directory " + file); 16800 continue; 16801 } 16802 16803 boolean destroyUser = false; 16804 if (info == null) { 16805 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16806 + " because no matching user was found"); 16807 destroyUser = true; 16808 } else { 16809 try { 16810 UserManagerService.enforceSerialNumber(file, info.serialNumber); 16811 } catch (IOException e) { 16812 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16813 + " because we failed to enforce serial number: " + e); 16814 destroyUser = true; 16815 } 16816 } 16817 16818 if (destroyUser) { 16819 synchronized (mInstallLock) { 16820 try { 16821 mInstaller.removeUserDataDirs(volumeUuid, userId); 16822 } catch (InstallerException e) { 16823 Slog.w(TAG, "Failed to clean up user dirs", e); 16824 } 16825 } 16826 } 16827 } 16828 16829 final StorageManager sm = mContext.getSystemService(StorageManager.class); 16830 final UserManager um = mContext.getSystemService(UserManager.class); 16831 for (UserInfo user : um.getUsers()) { 16832 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 16833 if (userDir.exists()) continue; 16834 16835 try { 16836 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, user.isEphemeral()); 16837 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 16838 } catch (IOException e) { 16839 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 16840 } 16841 } 16842 } 16843 16844 private void assertPackageKnown(String volumeUuid, String packageName) 16845 throws PackageManagerException { 16846 synchronized (mPackages) { 16847 final PackageSetting ps = mSettings.mPackages.get(packageName); 16848 if (ps == null) { 16849 throw new PackageManagerException("Package " + packageName + " is unknown"); 16850 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 16851 throw new PackageManagerException( 16852 "Package " + packageName + " found on unknown volume " + volumeUuid 16853 + "; expected volume " + ps.volumeUuid); 16854 } 16855 } 16856 } 16857 16858 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 16859 throws PackageManagerException { 16860 synchronized (mPackages) { 16861 final PackageSetting ps = mSettings.mPackages.get(packageName); 16862 if (ps == null) { 16863 throw new PackageManagerException("Package " + packageName + " is unknown"); 16864 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 16865 throw new PackageManagerException( 16866 "Package " + packageName + " found on unknown volume " + volumeUuid 16867 + "; expected volume " + ps.volumeUuid); 16868 } else if (!ps.getInstalled(userId)) { 16869 throw new PackageManagerException( 16870 "Package " + packageName + " not installed for user " + userId); 16871 } 16872 } 16873 } 16874 16875 /** 16876 * Examine all apps present on given mounted volume, and destroy apps that 16877 * aren't expected, either due to uninstallation or reinstallation on 16878 * another volume. 16879 */ 16880 private void reconcileApps(String volumeUuid) { 16881 final File[] files = FileUtils 16882 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 16883 for (File file : files) { 16884 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 16885 && !PackageInstallerService.isStageName(file.getName()); 16886 if (!isPackage) { 16887 // Ignore entries which are not packages 16888 continue; 16889 } 16890 16891 try { 16892 final PackageLite pkg = PackageParser.parsePackageLite(file, 16893 PackageParser.PARSE_MUST_BE_APK); 16894 assertPackageKnown(volumeUuid, pkg.packageName); 16895 16896 } catch (PackageParserException | PackageManagerException e) { 16897 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 16898 synchronized (mInstallLock) { 16899 removeCodePathLI(file); 16900 } 16901 } 16902 } 16903 } 16904 16905 /** 16906 * Reconcile all app data for the given user. 16907 * <p> 16908 * Verifies that directories exist and that ownership and labeling is 16909 * correct for all installed apps on all mounted volumes. 16910 */ 16911 void reconcileAppsData(int userId, @StorageFlags int flags) { 16912 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16913 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16914 final String volumeUuid = vol.getFsUuid(); 16915 reconcileAppsData(volumeUuid, userId, flags); 16916 } 16917 } 16918 16919 /** 16920 * Reconcile all app data on given mounted volume. 16921 * <p> 16922 * Destroys app data that isn't expected, either due to uninstallation or 16923 * reinstallation on another volume. 16924 * <p> 16925 * Verifies that directories exist and that ownership and labeling is 16926 * correct for all installed apps. 16927 */ 16928 private void reconcileAppsData(String volumeUuid, int userId, @StorageFlags int flags) { 16929 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 16930 + Integer.toHexString(flags)); 16931 16932 final File ceDir = Environment.getDataUserCredentialEncryptedDirectory(volumeUuid, userId); 16933 final File deDir = Environment.getDataUserDeviceEncryptedDirectory(volumeUuid, userId); 16934 16935 boolean restoreconNeeded = false; 16936 16937 // First look for stale data that doesn't belong, and check if things 16938 // have changed since we did our last restorecon 16939 if ((flags & Installer.FLAG_CE_STORAGE) != 0) { 16940 if (!isUserKeyUnlocked(userId)) { 16941 throw new RuntimeException( 16942 "Yikes, someone asked us to reconcile CE storage while " + userId 16943 + " was still locked; this would have caused massive data loss!"); 16944 } 16945 16946 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 16947 16948 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 16949 for (File file : files) { 16950 final String packageName = file.getName(); 16951 try { 16952 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 16953 } catch (PackageManagerException e) { 16954 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 16955 synchronized (mInstallLock) { 16956 destroyAppDataLI(volumeUuid, packageName, userId, 16957 Installer.FLAG_CE_STORAGE); 16958 } 16959 } 16960 } 16961 } 16962 if ((flags & Installer.FLAG_DE_STORAGE) != 0) { 16963 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 16964 16965 final File[] files = FileUtils.listFilesOrEmpty(deDir); 16966 for (File file : files) { 16967 final String packageName = file.getName(); 16968 try { 16969 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 16970 } catch (PackageManagerException e) { 16971 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 16972 synchronized (mInstallLock) { 16973 destroyAppDataLI(volumeUuid, packageName, userId, 16974 Installer.FLAG_DE_STORAGE); 16975 } 16976 } 16977 } 16978 } 16979 16980 // Ensure that data directories are ready to roll for all packages 16981 // installed for this volume and user 16982 final List<PackageSetting> packages; 16983 synchronized (mPackages) { 16984 packages = mSettings.getVolumePackagesLPr(volumeUuid); 16985 } 16986 int preparedCount = 0; 16987 for (PackageSetting ps : packages) { 16988 final String packageName = ps.name; 16989 if (ps.pkg == null) { 16990 Slog.w(TAG, "Odd, missing scanned package " + packageName); 16991 // TODO: might be due to legacy ASEC apps; we should circle back 16992 // and reconcile again once they're scanned 16993 continue; 16994 } 16995 16996 if (ps.getInstalled(userId)) { 16997 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 16998 preparedCount++; 16999 } 17000 } 17001 17002 if (restoreconNeeded) { 17003 if ((flags & Installer.FLAG_CE_STORAGE) != 0) { 17004 SELinuxMMAC.setRestoreconDone(ceDir); 17005 } 17006 if ((flags & Installer.FLAG_DE_STORAGE) != 0) { 17007 SELinuxMMAC.setRestoreconDone(deDir); 17008 } 17009 } 17010 17011 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 17012 + " packages; restoreconNeeded was " + restoreconNeeded); 17013 } 17014 17015 /** 17016 * Prepare app data for the given app just after it was installed or 17017 * upgraded. This method carefully only touches users that it's installed 17018 * for, and it forces a restorecon to handle any seinfo changes. 17019 * <p> 17020 * Verifies that directories exist and that ownership and labeling is 17021 * correct for all installed apps. If there is an ownership mismatch, it 17022 * will try recovering system apps by wiping data; third-party app data is 17023 * left intact. 17024 */ 17025 private void prepareAppDataAfterInstall(PackageParser.Package pkg) { 17026 final PackageSetting ps; 17027 synchronized (mPackages) { 17028 ps = mSettings.mPackages.get(pkg.packageName); 17029 } 17030 17031 final UserManager um = mContext.getSystemService(UserManager.class); 17032 for (UserInfo user : um.getUsers()) { 17033 final int flags; 17034 if (um.isUserUnlocked(user.id)) { 17035 flags = Installer.FLAG_DE_STORAGE | Installer.FLAG_CE_STORAGE; 17036 } else if (um.isUserRunning(user.id)) { 17037 flags = Installer.FLAG_DE_STORAGE; 17038 } else { 17039 continue; 17040 } 17041 17042 if (ps.getInstalled(user.id)) { 17043 // Whenever an app changes, force a restorecon of its data 17044 // TODO: when user data is locked, mark that we're still dirty 17045 prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true); 17046 } 17047 } 17048 } 17049 17050 /** 17051 * Prepare app data for the given app. 17052 * <p> 17053 * Verifies that directories exist and that ownership and labeling is 17054 * correct for all installed apps. If there is an ownership mismatch, this 17055 * will try recovering system apps by wiping data; third-party app data is 17056 * left intact. 17057 */ 17058 private void prepareAppData(String volumeUuid, int userId, @StorageFlags int flags, 17059 PackageParser.Package pkg, boolean restoreconNeeded) { 17060 if (DEBUG_APP_DATA) { 17061 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 17062 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 17063 } 17064 17065 final String packageName = pkg.packageName; 17066 final ApplicationInfo app = pkg.applicationInfo; 17067 final int appId = UserHandle.getAppId(app.uid); 17068 17069 Preconditions.checkNotNull(app.seinfo); 17070 17071 synchronized (mInstallLock) { 17072 try { 17073 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 17074 appId, app.seinfo, app.targetSdkVersion); 17075 } catch (InstallerException e) { 17076 if (app.isSystemApp()) { 17077 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 17078 + ", but trying to recover: " + e); 17079 destroyAppDataLI(volumeUuid, packageName, userId, flags); 17080 try { 17081 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 17082 appId, app.seinfo, app.targetSdkVersion); 17083 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 17084 } catch (InstallerException e2) { 17085 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 17086 } 17087 } else { 17088 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 17089 } 17090 } 17091 17092 if (restoreconNeeded) { 17093 restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo); 17094 } 17095 17096 if ((flags & Installer.FLAG_CE_STORAGE) != 0) { 17097 // Create a native library symlink only if we have native libraries 17098 // and if the native libraries are 32 bit libraries. We do not provide 17099 // this symlink for 64 bit libraries. 17100 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 17101 final String nativeLibPath = app.nativeLibraryDir; 17102 try { 17103 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 17104 nativeLibPath, userId); 17105 } catch (InstallerException e) { 17106 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 17107 } 17108 } 17109 } 17110 } 17111 } 17112 17113 private void unfreezePackage(String packageName) { 17114 synchronized (mPackages) { 17115 final PackageSetting ps = mSettings.mPackages.get(packageName); 17116 if (ps != null) { 17117 ps.frozen = false; 17118 } 17119 } 17120 } 17121 17122 @Override 17123 public int movePackage(final String packageName, final String volumeUuid) { 17124 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 17125 17126 final int moveId = mNextMoveId.getAndIncrement(); 17127 mHandler.post(new Runnable() { 17128 @Override 17129 public void run() { 17130 try { 17131 movePackageInternal(packageName, volumeUuid, moveId); 17132 } catch (PackageManagerException e) { 17133 Slog.w(TAG, "Failed to move " + packageName, e); 17134 mMoveCallbacks.notifyStatusChanged(moveId, 17135 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 17136 } 17137 } 17138 }); 17139 return moveId; 17140 } 17141 17142 private void movePackageInternal(final String packageName, final String volumeUuid, 17143 final int moveId) throws PackageManagerException { 17144 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 17145 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17146 final PackageManager pm = mContext.getPackageManager(); 17147 17148 final boolean currentAsec; 17149 final String currentVolumeUuid; 17150 final File codeFile; 17151 final String installerPackageName; 17152 final String packageAbiOverride; 17153 final int appId; 17154 final String seinfo; 17155 final String label; 17156 final int targetSdkVersion; 17157 17158 // reader 17159 synchronized (mPackages) { 17160 final PackageParser.Package pkg = mPackages.get(packageName); 17161 final PackageSetting ps = mSettings.mPackages.get(packageName); 17162 if (pkg == null || ps == null) { 17163 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 17164 } 17165 17166 if (pkg.applicationInfo.isSystemApp()) { 17167 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 17168 "Cannot move system application"); 17169 } 17170 17171 if (pkg.applicationInfo.isExternalAsec()) { 17172 currentAsec = true; 17173 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 17174 } else if (pkg.applicationInfo.isForwardLocked()) { 17175 currentAsec = true; 17176 currentVolumeUuid = "forward_locked"; 17177 } else { 17178 currentAsec = false; 17179 currentVolumeUuid = ps.volumeUuid; 17180 17181 final File probe = new File(pkg.codePath); 17182 final File probeOat = new File(probe, "oat"); 17183 if (!probe.isDirectory() || !probeOat.isDirectory()) { 17184 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17185 "Move only supported for modern cluster style installs"); 17186 } 17187 } 17188 17189 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 17190 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17191 "Package already moved to " + volumeUuid); 17192 } 17193 17194 if (ps.frozen) { 17195 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 17196 "Failed to move already frozen package"); 17197 } 17198 ps.frozen = true; 17199 17200 codeFile = new File(pkg.codePath); 17201 installerPackageName = ps.installerPackageName; 17202 packageAbiOverride = ps.cpuAbiOverrideString; 17203 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 17204 seinfo = pkg.applicationInfo.seinfo; 17205 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 17206 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 17207 } 17208 17209 // Now that we're guarded by frozen state, kill app during move 17210 final long token = Binder.clearCallingIdentity(); 17211 try { 17212 killApplication(packageName, appId, "move pkg"); 17213 } finally { 17214 Binder.restoreCallingIdentity(token); 17215 } 17216 17217 final Bundle extras = new Bundle(); 17218 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 17219 extras.putString(Intent.EXTRA_TITLE, label); 17220 mMoveCallbacks.notifyCreated(moveId, extras); 17221 17222 int installFlags; 17223 final boolean moveCompleteApp; 17224 final File measurePath; 17225 17226 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 17227 installFlags = INSTALL_INTERNAL; 17228 moveCompleteApp = !currentAsec; 17229 measurePath = Environment.getDataAppDirectory(volumeUuid); 17230 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 17231 installFlags = INSTALL_EXTERNAL; 17232 moveCompleteApp = false; 17233 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 17234 } else { 17235 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 17236 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 17237 || !volume.isMountedWritable()) { 17238 unfreezePackage(packageName); 17239 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17240 "Move location not mounted private volume"); 17241 } 17242 17243 Preconditions.checkState(!currentAsec); 17244 17245 installFlags = INSTALL_INTERNAL; 17246 moveCompleteApp = true; 17247 measurePath = Environment.getDataAppDirectory(volumeUuid); 17248 } 17249 17250 final PackageStats stats = new PackageStats(null, -1); 17251 synchronized (mInstaller) { 17252 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 17253 unfreezePackage(packageName); 17254 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17255 "Failed to measure package size"); 17256 } 17257 } 17258 17259 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 17260 + stats.dataSize); 17261 17262 final long startFreeBytes = measurePath.getFreeSpace(); 17263 final long sizeBytes; 17264 if (moveCompleteApp) { 17265 sizeBytes = stats.codeSize + stats.dataSize; 17266 } else { 17267 sizeBytes = stats.codeSize; 17268 } 17269 17270 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 17271 unfreezePackage(packageName); 17272 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17273 "Not enough free space to move"); 17274 } 17275 17276 mMoveCallbacks.notifyStatusChanged(moveId, 10); 17277 17278 final CountDownLatch installedLatch = new CountDownLatch(1); 17279 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 17280 @Override 17281 public void onUserActionRequired(Intent intent) throws RemoteException { 17282 throw new IllegalStateException(); 17283 } 17284 17285 @Override 17286 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 17287 Bundle extras) throws RemoteException { 17288 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 17289 + PackageManager.installStatusToString(returnCode, msg)); 17290 17291 installedLatch.countDown(); 17292 17293 // Regardless of success or failure of the move operation, 17294 // always unfreeze the package 17295 unfreezePackage(packageName); 17296 17297 final int status = PackageManager.installStatusToPublicStatus(returnCode); 17298 switch (status) { 17299 case PackageInstaller.STATUS_SUCCESS: 17300 mMoveCallbacks.notifyStatusChanged(moveId, 17301 PackageManager.MOVE_SUCCEEDED); 17302 break; 17303 case PackageInstaller.STATUS_FAILURE_STORAGE: 17304 mMoveCallbacks.notifyStatusChanged(moveId, 17305 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 17306 break; 17307 default: 17308 mMoveCallbacks.notifyStatusChanged(moveId, 17309 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 17310 break; 17311 } 17312 } 17313 }; 17314 17315 final MoveInfo move; 17316 if (moveCompleteApp) { 17317 // Kick off a thread to report progress estimates 17318 new Thread() { 17319 @Override 17320 public void run() { 17321 while (true) { 17322 try { 17323 if (installedLatch.await(1, TimeUnit.SECONDS)) { 17324 break; 17325 } 17326 } catch (InterruptedException ignored) { 17327 } 17328 17329 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 17330 final int progress = 10 + (int) MathUtils.constrain( 17331 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 17332 mMoveCallbacks.notifyStatusChanged(moveId, progress); 17333 } 17334 } 17335 }.start(); 17336 17337 final String dataAppName = codeFile.getName(); 17338 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 17339 dataAppName, appId, seinfo, targetSdkVersion); 17340 } else { 17341 move = null; 17342 } 17343 17344 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 17345 17346 final Message msg = mHandler.obtainMessage(INIT_COPY); 17347 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 17348 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 17349 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 17350 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 17351 msg.obj = params; 17352 17353 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 17354 System.identityHashCode(msg.obj)); 17355 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 17356 System.identityHashCode(msg.obj)); 17357 17358 mHandler.sendMessage(msg); 17359 } 17360 17361 @Override 17362 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 17363 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 17364 17365 final int realMoveId = mNextMoveId.getAndIncrement(); 17366 final Bundle extras = new Bundle(); 17367 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 17368 mMoveCallbacks.notifyCreated(realMoveId, extras); 17369 17370 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 17371 @Override 17372 public void onCreated(int moveId, Bundle extras) { 17373 // Ignored 17374 } 17375 17376 @Override 17377 public void onStatusChanged(int moveId, int status, long estMillis) { 17378 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 17379 } 17380 }; 17381 17382 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17383 storage.setPrimaryStorageUuid(volumeUuid, callback); 17384 return realMoveId; 17385 } 17386 17387 @Override 17388 public int getMoveStatus(int moveId) { 17389 mContext.enforceCallingOrSelfPermission( 17390 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 17391 return mMoveCallbacks.mLastStatus.get(moveId); 17392 } 17393 17394 @Override 17395 public void registerMoveCallback(IPackageMoveObserver callback) { 17396 mContext.enforceCallingOrSelfPermission( 17397 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 17398 mMoveCallbacks.register(callback); 17399 } 17400 17401 @Override 17402 public void unregisterMoveCallback(IPackageMoveObserver callback) { 17403 mContext.enforceCallingOrSelfPermission( 17404 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 17405 mMoveCallbacks.unregister(callback); 17406 } 17407 17408 @Override 17409 public boolean setInstallLocation(int loc) { 17410 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 17411 null); 17412 if (getInstallLocation() == loc) { 17413 return true; 17414 } 17415 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 17416 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 17417 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 17418 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 17419 return true; 17420 } 17421 return false; 17422 } 17423 17424 @Override 17425 public int getInstallLocation() { 17426 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 17427 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 17428 PackageHelper.APP_INSTALL_AUTO); 17429 } 17430 17431 /** Called by UserManagerService */ 17432 void cleanUpUser(UserManagerService userManager, int userHandle) { 17433 synchronized (mPackages) { 17434 mDirtyUsers.remove(userHandle); 17435 mUserNeedsBadging.delete(userHandle); 17436 mSettings.removeUserLPw(userHandle); 17437 mPendingBroadcasts.remove(userHandle); 17438 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 17439 } 17440 synchronized (mInstallLock) { 17441 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17442 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 17443 final String volumeUuid = vol.getFsUuid(); 17444 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 17445 try { 17446 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 17447 } catch (InstallerException e) { 17448 Slog.w(TAG, "Failed to remove user data", e); 17449 } 17450 } 17451 synchronized (mPackages) { 17452 removeUnusedPackagesLILPw(userManager, userHandle); 17453 } 17454 } 17455 } 17456 17457 /** 17458 * We're removing userHandle and would like to remove any downloaded packages 17459 * that are no longer in use by any other user. 17460 * @param userHandle the user being removed 17461 */ 17462 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 17463 final boolean DEBUG_CLEAN_APKS = false; 17464 int [] users = userManager.getUserIds(); 17465 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 17466 while (psit.hasNext()) { 17467 PackageSetting ps = psit.next(); 17468 if (ps.pkg == null) { 17469 continue; 17470 } 17471 final String packageName = ps.pkg.packageName; 17472 // Skip over if system app 17473 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 17474 continue; 17475 } 17476 if (DEBUG_CLEAN_APKS) { 17477 Slog.i(TAG, "Checking package " + packageName); 17478 } 17479 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 17480 if (keep) { 17481 if (DEBUG_CLEAN_APKS) { 17482 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 17483 } 17484 } else { 17485 for (int i = 0; i < users.length; i++) { 17486 if (users[i] != userHandle && ps.getInstalled(users[i])) { 17487 keep = true; 17488 if (DEBUG_CLEAN_APKS) { 17489 Slog.i(TAG, " Keeping package " + packageName + " for user " 17490 + users[i]); 17491 } 17492 break; 17493 } 17494 } 17495 } 17496 if (!keep) { 17497 if (DEBUG_CLEAN_APKS) { 17498 Slog.i(TAG, " Removing package " + packageName); 17499 } 17500 mHandler.post(new Runnable() { 17501 public void run() { 17502 deletePackageX(packageName, userHandle, 0); 17503 } //end run 17504 }); 17505 } 17506 } 17507 } 17508 17509 /** Called by UserManagerService */ 17510 void createNewUser(int userHandle) { 17511 synchronized (mInstallLock) { 17512 try { 17513 mInstaller.createUserConfig(userHandle); 17514 } catch (InstallerException e) { 17515 Slog.w(TAG, "Failed to create user config", e); 17516 } 17517 mSettings.createNewUserLI(this, mInstaller, userHandle); 17518 } 17519 synchronized (mPackages) { 17520 applyFactoryDefaultBrowserLPw(userHandle); 17521 primeDomainVerificationsLPw(userHandle); 17522 } 17523 } 17524 17525 void newUserCreated(final int userHandle) { 17526 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 17527 // If permission review for legacy apps is required, we represent 17528 // dagerous permissions for such apps as always granted runtime 17529 // permissions to keep per user flag state whether review is needed. 17530 // Hence, if a new user is added we have to propagate dangerous 17531 // permission grants for these legacy apps. 17532 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 17533 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 17534 | UPDATE_PERMISSIONS_REPLACE_ALL); 17535 } 17536 } 17537 17538 @Override 17539 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 17540 mContext.enforceCallingOrSelfPermission( 17541 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 17542 "Only package verification agents can read the verifier device identity"); 17543 17544 synchronized (mPackages) { 17545 return mSettings.getVerifierDeviceIdentityLPw(); 17546 } 17547 } 17548 17549 @Override 17550 public void setPermissionEnforced(String permission, boolean enforced) { 17551 // TODO: Now that we no longer change GID for storage, this should to away. 17552 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 17553 "setPermissionEnforced"); 17554 if (READ_EXTERNAL_STORAGE.equals(permission)) { 17555 synchronized (mPackages) { 17556 if (mSettings.mReadExternalStorageEnforced == null 17557 || mSettings.mReadExternalStorageEnforced != enforced) { 17558 mSettings.mReadExternalStorageEnforced = enforced; 17559 mSettings.writeLPr(); 17560 } 17561 } 17562 // kill any non-foreground processes so we restart them and 17563 // grant/revoke the GID. 17564 final IActivityManager am = ActivityManagerNative.getDefault(); 17565 if (am != null) { 17566 final long token = Binder.clearCallingIdentity(); 17567 try { 17568 am.killProcessesBelowForeground("setPermissionEnforcement"); 17569 } catch (RemoteException e) { 17570 } finally { 17571 Binder.restoreCallingIdentity(token); 17572 } 17573 } 17574 } else { 17575 throw new IllegalArgumentException("No selective enforcement for " + permission); 17576 } 17577 } 17578 17579 @Override 17580 @Deprecated 17581 public boolean isPermissionEnforced(String permission) { 17582 return true; 17583 } 17584 17585 @Override 17586 public boolean isStorageLow() { 17587 final long token = Binder.clearCallingIdentity(); 17588 try { 17589 final DeviceStorageMonitorInternal 17590 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 17591 if (dsm != null) { 17592 return dsm.isMemoryLow(); 17593 } else { 17594 return false; 17595 } 17596 } finally { 17597 Binder.restoreCallingIdentity(token); 17598 } 17599 } 17600 17601 @Override 17602 public IPackageInstaller getPackageInstaller() { 17603 return mInstallerService; 17604 } 17605 17606 private boolean userNeedsBadging(int userId) { 17607 int index = mUserNeedsBadging.indexOfKey(userId); 17608 if (index < 0) { 17609 final UserInfo userInfo; 17610 final long token = Binder.clearCallingIdentity(); 17611 try { 17612 userInfo = sUserManager.getUserInfo(userId); 17613 } finally { 17614 Binder.restoreCallingIdentity(token); 17615 } 17616 final boolean b; 17617 if (userInfo != null && userInfo.isManagedProfile()) { 17618 b = true; 17619 } else { 17620 b = false; 17621 } 17622 mUserNeedsBadging.put(userId, b); 17623 return b; 17624 } 17625 return mUserNeedsBadging.valueAt(index); 17626 } 17627 17628 @Override 17629 public KeySet getKeySetByAlias(String packageName, String alias) { 17630 if (packageName == null || alias == null) { 17631 return null; 17632 } 17633 synchronized(mPackages) { 17634 final PackageParser.Package pkg = mPackages.get(packageName); 17635 if (pkg == null) { 17636 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17637 throw new IllegalArgumentException("Unknown package: " + packageName); 17638 } 17639 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17640 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 17641 } 17642 } 17643 17644 @Override 17645 public KeySet getSigningKeySet(String packageName) { 17646 if (packageName == null) { 17647 return null; 17648 } 17649 synchronized(mPackages) { 17650 final PackageParser.Package pkg = mPackages.get(packageName); 17651 if (pkg == null) { 17652 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17653 throw new IllegalArgumentException("Unknown package: " + packageName); 17654 } 17655 if (pkg.applicationInfo.uid != Binder.getCallingUid() 17656 && Process.SYSTEM_UID != Binder.getCallingUid()) { 17657 throw new SecurityException("May not access signing KeySet of other apps."); 17658 } 17659 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17660 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 17661 } 17662 } 17663 17664 @Override 17665 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 17666 if (packageName == null || ks == null) { 17667 return false; 17668 } 17669 synchronized(mPackages) { 17670 final PackageParser.Package pkg = mPackages.get(packageName); 17671 if (pkg == null) { 17672 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17673 throw new IllegalArgumentException("Unknown package: " + packageName); 17674 } 17675 IBinder ksh = ks.getToken(); 17676 if (ksh instanceof KeySetHandle) { 17677 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17678 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 17679 } 17680 return false; 17681 } 17682 } 17683 17684 @Override 17685 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 17686 if (packageName == null || ks == null) { 17687 return false; 17688 } 17689 synchronized(mPackages) { 17690 final PackageParser.Package pkg = mPackages.get(packageName); 17691 if (pkg == null) { 17692 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17693 throw new IllegalArgumentException("Unknown package: " + packageName); 17694 } 17695 IBinder ksh = ks.getToken(); 17696 if (ksh instanceof KeySetHandle) { 17697 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17698 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 17699 } 17700 return false; 17701 } 17702 } 17703 17704 private void deletePackageIfUnusedLPr(final String packageName) { 17705 PackageSetting ps = mSettings.mPackages.get(packageName); 17706 if (ps == null) { 17707 return; 17708 } 17709 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 17710 // TODO Implement atomic delete if package is unused 17711 // It is currently possible that the package will be deleted even if it is installed 17712 // after this method returns. 17713 mHandler.post(new Runnable() { 17714 public void run() { 17715 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 17716 } 17717 }); 17718 } 17719 } 17720 17721 /** 17722 * Check and throw if the given before/after packages would be considered a 17723 * downgrade. 17724 */ 17725 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 17726 throws PackageManagerException { 17727 if (after.versionCode < before.mVersionCode) { 17728 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17729 "Update version code " + after.versionCode + " is older than current " 17730 + before.mVersionCode); 17731 } else if (after.versionCode == before.mVersionCode) { 17732 if (after.baseRevisionCode < before.baseRevisionCode) { 17733 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17734 "Update base revision code " + after.baseRevisionCode 17735 + " is older than current " + before.baseRevisionCode); 17736 } 17737 17738 if (!ArrayUtils.isEmpty(after.splitNames)) { 17739 for (int i = 0; i < after.splitNames.length; i++) { 17740 final String splitName = after.splitNames[i]; 17741 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 17742 if (j != -1) { 17743 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 17744 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17745 "Update split " + splitName + " revision code " 17746 + after.splitRevisionCodes[i] + " is older than current " 17747 + before.splitRevisionCodes[j]); 17748 } 17749 } 17750 } 17751 } 17752 } 17753 } 17754 17755 private static class MoveCallbacks extends Handler { 17756 private static final int MSG_CREATED = 1; 17757 private static final int MSG_STATUS_CHANGED = 2; 17758 17759 private final RemoteCallbackList<IPackageMoveObserver> 17760 mCallbacks = new RemoteCallbackList<>(); 17761 17762 private final SparseIntArray mLastStatus = new SparseIntArray(); 17763 17764 public MoveCallbacks(Looper looper) { 17765 super(looper); 17766 } 17767 17768 public void register(IPackageMoveObserver callback) { 17769 mCallbacks.register(callback); 17770 } 17771 17772 public void unregister(IPackageMoveObserver callback) { 17773 mCallbacks.unregister(callback); 17774 } 17775 17776 @Override 17777 public void handleMessage(Message msg) { 17778 final SomeArgs args = (SomeArgs) msg.obj; 17779 final int n = mCallbacks.beginBroadcast(); 17780 for (int i = 0; i < n; i++) { 17781 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 17782 try { 17783 invokeCallback(callback, msg.what, args); 17784 } catch (RemoteException ignored) { 17785 } 17786 } 17787 mCallbacks.finishBroadcast(); 17788 args.recycle(); 17789 } 17790 17791 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 17792 throws RemoteException { 17793 switch (what) { 17794 case MSG_CREATED: { 17795 callback.onCreated(args.argi1, (Bundle) args.arg2); 17796 break; 17797 } 17798 case MSG_STATUS_CHANGED: { 17799 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 17800 break; 17801 } 17802 } 17803 } 17804 17805 private void notifyCreated(int moveId, Bundle extras) { 17806 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 17807 17808 final SomeArgs args = SomeArgs.obtain(); 17809 args.argi1 = moveId; 17810 args.arg2 = extras; 17811 obtainMessage(MSG_CREATED, args).sendToTarget(); 17812 } 17813 17814 private void notifyStatusChanged(int moveId, int status) { 17815 notifyStatusChanged(moveId, status, -1); 17816 } 17817 17818 private void notifyStatusChanged(int moveId, int status, long estMillis) { 17819 Slog.v(TAG, "Move " + moveId + " status " + status); 17820 17821 final SomeArgs args = SomeArgs.obtain(); 17822 args.argi1 = moveId; 17823 args.argi2 = status; 17824 args.arg3 = estMillis; 17825 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 17826 17827 synchronized (mLastStatus) { 17828 mLastStatus.put(moveId, status); 17829 } 17830 } 17831 } 17832 17833 private final static class OnPermissionChangeListeners extends Handler { 17834 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 17835 17836 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 17837 new RemoteCallbackList<>(); 17838 17839 public OnPermissionChangeListeners(Looper looper) { 17840 super(looper); 17841 } 17842 17843 @Override 17844 public void handleMessage(Message msg) { 17845 switch (msg.what) { 17846 case MSG_ON_PERMISSIONS_CHANGED: { 17847 final int uid = msg.arg1; 17848 handleOnPermissionsChanged(uid); 17849 } break; 17850 } 17851 } 17852 17853 public void addListenerLocked(IOnPermissionsChangeListener listener) { 17854 mPermissionListeners.register(listener); 17855 17856 } 17857 17858 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 17859 mPermissionListeners.unregister(listener); 17860 } 17861 17862 public void onPermissionsChanged(int uid) { 17863 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 17864 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 17865 } 17866 } 17867 17868 private void handleOnPermissionsChanged(int uid) { 17869 final int count = mPermissionListeners.beginBroadcast(); 17870 try { 17871 for (int i = 0; i < count; i++) { 17872 IOnPermissionsChangeListener callback = mPermissionListeners 17873 .getBroadcastItem(i); 17874 try { 17875 callback.onPermissionsChanged(uid); 17876 } catch (RemoteException e) { 17877 Log.e(TAG, "Permission listener is dead", e); 17878 } 17879 } 17880 } finally { 17881 mPermissionListeners.finishBroadcast(); 17882 } 17883 } 17884 } 17885 17886 private class PackageManagerInternalImpl extends PackageManagerInternal { 17887 @Override 17888 public void setLocationPackagesProvider(PackagesProvider provider) { 17889 synchronized (mPackages) { 17890 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 17891 } 17892 } 17893 17894 @Override 17895 public void setImePackagesProvider(PackagesProvider provider) { 17896 synchronized (mPackages) { 17897 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 17898 } 17899 } 17900 17901 @Override 17902 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 17903 synchronized (mPackages) { 17904 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 17905 } 17906 } 17907 17908 @Override 17909 public void setSmsAppPackagesProvider(PackagesProvider provider) { 17910 synchronized (mPackages) { 17911 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 17912 } 17913 } 17914 17915 @Override 17916 public void setDialerAppPackagesProvider(PackagesProvider provider) { 17917 synchronized (mPackages) { 17918 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 17919 } 17920 } 17921 17922 @Override 17923 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 17924 synchronized (mPackages) { 17925 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 17926 } 17927 } 17928 17929 @Override 17930 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 17931 synchronized (mPackages) { 17932 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 17933 } 17934 } 17935 17936 @Override 17937 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 17938 synchronized (mPackages) { 17939 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 17940 packageName, userId); 17941 } 17942 } 17943 17944 @Override 17945 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 17946 synchronized (mPackages) { 17947 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 17948 packageName, userId); 17949 } 17950 } 17951 17952 @Override 17953 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 17954 synchronized (mPackages) { 17955 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 17956 packageName, userId); 17957 } 17958 } 17959 17960 @Override 17961 public void setKeepUninstalledPackages(final List<String> packageList) { 17962 Preconditions.checkNotNull(packageList); 17963 List<String> removedFromList = null; 17964 synchronized (mPackages) { 17965 if (mKeepUninstalledPackages != null) { 17966 final int packagesCount = mKeepUninstalledPackages.size(); 17967 for (int i = 0; i < packagesCount; i++) { 17968 String oldPackage = mKeepUninstalledPackages.get(i); 17969 if (packageList != null && packageList.contains(oldPackage)) { 17970 continue; 17971 } 17972 if (removedFromList == null) { 17973 removedFromList = new ArrayList<>(); 17974 } 17975 removedFromList.add(oldPackage); 17976 } 17977 } 17978 mKeepUninstalledPackages = new ArrayList<>(packageList); 17979 if (removedFromList != null) { 17980 final int removedCount = removedFromList.size(); 17981 for (int i = 0; i < removedCount; i++) { 17982 deletePackageIfUnusedLPr(removedFromList.get(i)); 17983 } 17984 } 17985 } 17986 } 17987 17988 @Override 17989 public boolean isPermissionsReviewRequired(String packageName, int userId) { 17990 synchronized (mPackages) { 17991 // If we do not support permission review, done. 17992 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 17993 return false; 17994 } 17995 17996 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 17997 if (packageSetting == null) { 17998 return false; 17999 } 18000 18001 // Permission review applies only to apps not supporting the new permission model. 18002 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 18003 return false; 18004 } 18005 18006 // Legacy apps have the permission and get user consent on launch. 18007 PermissionsState permissionsState = packageSetting.getPermissionsState(); 18008 return permissionsState.isPermissionReviewRequired(userId); 18009 } 18010 } 18011 } 18012 18013 @Override 18014 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 18015 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 18016 synchronized (mPackages) { 18017 final long identity = Binder.clearCallingIdentity(); 18018 try { 18019 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 18020 packageNames, userId); 18021 } finally { 18022 Binder.restoreCallingIdentity(identity); 18023 } 18024 } 18025 } 18026 18027 private static void enforceSystemOrPhoneCaller(String tag) { 18028 int callingUid = Binder.getCallingUid(); 18029 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 18030 throw new SecurityException( 18031 "Cannot call " + tag + " from UID " + callingUid); 18032 } 18033 } 18034} 18035