PackageManagerService.java revision 493411ace40a8b4a90be70576f361c5b7515f29d
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 && !resultTargetUser.isEmpty() 5373 && isUserEnabled(targetUserId)) { 5374 return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId); 5375 } 5376 return null; 5377 } 5378 5379 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5380 int sourceUserId, int targetUserId) { 5381 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5382 long ident = Binder.clearCallingIdentity(); 5383 boolean targetIsProfile; 5384 try { 5385 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5386 } finally { 5387 Binder.restoreCallingIdentity(ident); 5388 } 5389 String className; 5390 if (targetIsProfile) { 5391 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5392 } else { 5393 className = FORWARD_INTENT_TO_PARENT; 5394 } 5395 ComponentName forwardingActivityComponentName = new ComponentName( 5396 mAndroidApplication.packageName, className); 5397 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5398 sourceUserId); 5399 if (!targetIsProfile) { 5400 forwardingActivityInfo.showUserIcon = targetUserId; 5401 forwardingResolveInfo.noResourceId = true; 5402 } 5403 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5404 forwardingResolveInfo.priority = 0; 5405 forwardingResolveInfo.preferredOrder = 0; 5406 forwardingResolveInfo.match = 0; 5407 forwardingResolveInfo.isDefault = true; 5408 forwardingResolveInfo.filter = filter; 5409 forwardingResolveInfo.targetUserId = targetUserId; 5410 return forwardingResolveInfo; 5411 } 5412 5413 @Override 5414 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5415 Intent[] specifics, String[] specificTypes, Intent intent, 5416 String resolvedType, int flags, int userId) { 5417 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5418 flags = updateFlagsForResolve(flags, userId, intent); 5419 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 5420 false, "query intent activity options"); 5421 final String resultsAction = intent.getAction(); 5422 5423 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 5424 | PackageManager.GET_RESOLVED_FILTER, userId); 5425 5426 if (DEBUG_INTENT_MATCHING) { 5427 Log.v(TAG, "Query " + intent + ": " + results); 5428 } 5429 5430 int specificsPos = 0; 5431 int N; 5432 5433 // todo: note that the algorithm used here is O(N^2). This 5434 // isn't a problem in our current environment, but if we start running 5435 // into situations where we have more than 5 or 10 matches then this 5436 // should probably be changed to something smarter... 5437 5438 // First we go through and resolve each of the specific items 5439 // that were supplied, taking care of removing any corresponding 5440 // duplicate items in the generic resolve list. 5441 if (specifics != null) { 5442 for (int i=0; i<specifics.length; i++) { 5443 final Intent sintent = specifics[i]; 5444 if (sintent == null) { 5445 continue; 5446 } 5447 5448 if (DEBUG_INTENT_MATCHING) { 5449 Log.v(TAG, "Specific #" + i + ": " + sintent); 5450 } 5451 5452 String action = sintent.getAction(); 5453 if (resultsAction != null && resultsAction.equals(action)) { 5454 // If this action was explicitly requested, then don't 5455 // remove things that have it. 5456 action = null; 5457 } 5458 5459 ResolveInfo ri = null; 5460 ActivityInfo ai = null; 5461 5462 ComponentName comp = sintent.getComponent(); 5463 if (comp == null) { 5464 ri = resolveIntent( 5465 sintent, 5466 specificTypes != null ? specificTypes[i] : null, 5467 flags, userId); 5468 if (ri == null) { 5469 continue; 5470 } 5471 if (ri == mResolveInfo) { 5472 // ACK! Must do something better with this. 5473 } 5474 ai = ri.activityInfo; 5475 comp = new ComponentName(ai.applicationInfo.packageName, 5476 ai.name); 5477 } else { 5478 ai = getActivityInfo(comp, flags, userId); 5479 if (ai == null) { 5480 continue; 5481 } 5482 } 5483 5484 // Look for any generic query activities that are duplicates 5485 // of this specific one, and remove them from the results. 5486 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5487 N = results.size(); 5488 int j; 5489 for (j=specificsPos; j<N; j++) { 5490 ResolveInfo sri = results.get(j); 5491 if ((sri.activityInfo.name.equals(comp.getClassName()) 5492 && sri.activityInfo.applicationInfo.packageName.equals( 5493 comp.getPackageName())) 5494 || (action != null && sri.filter.matchAction(action))) { 5495 results.remove(j); 5496 if (DEBUG_INTENT_MATCHING) Log.v( 5497 TAG, "Removing duplicate item from " + j 5498 + " due to specific " + specificsPos); 5499 if (ri == null) { 5500 ri = sri; 5501 } 5502 j--; 5503 N--; 5504 } 5505 } 5506 5507 // Add this specific item to its proper place. 5508 if (ri == null) { 5509 ri = new ResolveInfo(); 5510 ri.activityInfo = ai; 5511 } 5512 results.add(specificsPos, ri); 5513 ri.specificIndex = i; 5514 specificsPos++; 5515 } 5516 } 5517 5518 // Now we go through the remaining generic results and remove any 5519 // duplicate actions that are found here. 5520 N = results.size(); 5521 for (int i=specificsPos; i<N-1; i++) { 5522 final ResolveInfo rii = results.get(i); 5523 if (rii.filter == null) { 5524 continue; 5525 } 5526 5527 // Iterate over all of the actions of this result's intent 5528 // filter... typically this should be just one. 5529 final Iterator<String> it = rii.filter.actionsIterator(); 5530 if (it == null) { 5531 continue; 5532 } 5533 while (it.hasNext()) { 5534 final String action = it.next(); 5535 if (resultsAction != null && resultsAction.equals(action)) { 5536 // If this action was explicitly requested, then don't 5537 // remove things that have it. 5538 continue; 5539 } 5540 for (int j=i+1; j<N; j++) { 5541 final ResolveInfo rij = results.get(j); 5542 if (rij.filter != null && rij.filter.hasAction(action)) { 5543 results.remove(j); 5544 if (DEBUG_INTENT_MATCHING) Log.v( 5545 TAG, "Removing duplicate item from " + j 5546 + " due to action " + action + " at " + i); 5547 j--; 5548 N--; 5549 } 5550 } 5551 } 5552 5553 // If the caller didn't request filter information, drop it now 5554 // so we don't have to marshall/unmarshall it. 5555 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5556 rii.filter = null; 5557 } 5558 } 5559 5560 // Filter out the caller activity if so requested. 5561 if (caller != null) { 5562 N = results.size(); 5563 for (int i=0; i<N; i++) { 5564 ActivityInfo ainfo = results.get(i).activityInfo; 5565 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5566 && caller.getClassName().equals(ainfo.name)) { 5567 results.remove(i); 5568 break; 5569 } 5570 } 5571 } 5572 5573 // If the caller didn't request filter information, 5574 // drop them now so we don't have to 5575 // marshall/unmarshall it. 5576 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5577 N = results.size(); 5578 for (int i=0; i<N; i++) { 5579 results.get(i).filter = null; 5580 } 5581 } 5582 5583 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5584 return results; 5585 } 5586 5587 @Override 5588 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5589 int userId) { 5590 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5591 flags = updateFlagsForResolve(flags, userId, intent); 5592 ComponentName comp = intent.getComponent(); 5593 if (comp == null) { 5594 if (intent.getSelector() != null) { 5595 intent = intent.getSelector(); 5596 comp = intent.getComponent(); 5597 } 5598 } 5599 if (comp != null) { 5600 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5601 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5602 if (ai != null) { 5603 ResolveInfo ri = new ResolveInfo(); 5604 ri.activityInfo = ai; 5605 list.add(ri); 5606 } 5607 return list; 5608 } 5609 5610 // reader 5611 synchronized (mPackages) { 5612 String pkgName = intent.getPackage(); 5613 if (pkgName == null) { 5614 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5615 } 5616 final PackageParser.Package pkg = mPackages.get(pkgName); 5617 if (pkg != null) { 5618 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5619 userId); 5620 } 5621 return null; 5622 } 5623 } 5624 5625 @Override 5626 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5627 if (!sUserManager.exists(userId)) return null; 5628 flags = updateFlagsForResolve(flags, userId, intent); 5629 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5630 if (query != null) { 5631 if (query.size() >= 1) { 5632 // If there is more than one service with the same priority, 5633 // just arbitrarily pick the first one. 5634 return query.get(0); 5635 } 5636 } 5637 return null; 5638 } 5639 5640 @Override 5641 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5642 int userId) { 5643 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5644 flags = updateFlagsForResolve(flags, userId, intent); 5645 ComponentName comp = intent.getComponent(); 5646 if (comp == null) { 5647 if (intent.getSelector() != null) { 5648 intent = intent.getSelector(); 5649 comp = intent.getComponent(); 5650 } 5651 } 5652 if (comp != null) { 5653 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5654 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5655 if (si != null) { 5656 final ResolveInfo ri = new ResolveInfo(); 5657 ri.serviceInfo = si; 5658 list.add(ri); 5659 } 5660 return list; 5661 } 5662 5663 // reader 5664 synchronized (mPackages) { 5665 String pkgName = intent.getPackage(); 5666 if (pkgName == null) { 5667 return mServices.queryIntent(intent, resolvedType, flags, userId); 5668 } 5669 final PackageParser.Package pkg = mPackages.get(pkgName); 5670 if (pkg != null) { 5671 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5672 userId); 5673 } 5674 return null; 5675 } 5676 } 5677 5678 @Override 5679 public List<ResolveInfo> queryIntentContentProviders( 5680 Intent intent, String resolvedType, int flags, int userId) { 5681 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5682 flags = updateFlagsForResolve(flags, userId, intent); 5683 ComponentName comp = intent.getComponent(); 5684 if (comp == null) { 5685 if (intent.getSelector() != null) { 5686 intent = intent.getSelector(); 5687 comp = intent.getComponent(); 5688 } 5689 } 5690 if (comp != null) { 5691 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5692 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5693 if (pi != null) { 5694 final ResolveInfo ri = new ResolveInfo(); 5695 ri.providerInfo = pi; 5696 list.add(ri); 5697 } 5698 return list; 5699 } 5700 5701 // reader 5702 synchronized (mPackages) { 5703 String pkgName = intent.getPackage(); 5704 if (pkgName == null) { 5705 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5706 } 5707 final PackageParser.Package pkg = mPackages.get(pkgName); 5708 if (pkg != null) { 5709 return mProviders.queryIntentForPackage( 5710 intent, resolvedType, flags, pkg.providers, userId); 5711 } 5712 return null; 5713 } 5714 } 5715 5716 @Override 5717 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5718 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5719 flags = updateFlagsForPackage(flags, userId, null); 5720 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5721 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5722 5723 // writer 5724 synchronized (mPackages) { 5725 ArrayList<PackageInfo> list; 5726 if (listUninstalled) { 5727 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5728 for (PackageSetting ps : mSettings.mPackages.values()) { 5729 PackageInfo pi; 5730 if (ps.pkg != null) { 5731 pi = generatePackageInfo(ps.pkg, flags, userId); 5732 } else { 5733 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5734 } 5735 if (pi != null) { 5736 list.add(pi); 5737 } 5738 } 5739 } else { 5740 list = new ArrayList<PackageInfo>(mPackages.size()); 5741 for (PackageParser.Package p : mPackages.values()) { 5742 PackageInfo pi = generatePackageInfo(p, flags, userId); 5743 if (pi != null) { 5744 list.add(pi); 5745 } 5746 } 5747 } 5748 5749 return new ParceledListSlice<PackageInfo>(list); 5750 } 5751 } 5752 5753 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5754 String[] permissions, boolean[] tmp, int flags, int userId) { 5755 int numMatch = 0; 5756 final PermissionsState permissionsState = ps.getPermissionsState(); 5757 for (int i=0; i<permissions.length; i++) { 5758 final String permission = permissions[i]; 5759 if (permissionsState.hasPermission(permission, userId)) { 5760 tmp[i] = true; 5761 numMatch++; 5762 } else { 5763 tmp[i] = false; 5764 } 5765 } 5766 if (numMatch == 0) { 5767 return; 5768 } 5769 PackageInfo pi; 5770 if (ps.pkg != null) { 5771 pi = generatePackageInfo(ps.pkg, flags, userId); 5772 } else { 5773 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5774 } 5775 // The above might return null in cases of uninstalled apps or install-state 5776 // skew across users/profiles. 5777 if (pi != null) { 5778 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5779 if (numMatch == permissions.length) { 5780 pi.requestedPermissions = permissions; 5781 } else { 5782 pi.requestedPermissions = new String[numMatch]; 5783 numMatch = 0; 5784 for (int i=0; i<permissions.length; i++) { 5785 if (tmp[i]) { 5786 pi.requestedPermissions[numMatch] = permissions[i]; 5787 numMatch++; 5788 } 5789 } 5790 } 5791 } 5792 list.add(pi); 5793 } 5794 } 5795 5796 @Override 5797 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5798 String[] permissions, int flags, int userId) { 5799 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5800 flags = updateFlagsForPackage(flags, userId, permissions); 5801 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5802 5803 // writer 5804 synchronized (mPackages) { 5805 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5806 boolean[] tmpBools = new boolean[permissions.length]; 5807 if (listUninstalled) { 5808 for (PackageSetting ps : mSettings.mPackages.values()) { 5809 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5810 } 5811 } else { 5812 for (PackageParser.Package pkg : mPackages.values()) { 5813 PackageSetting ps = (PackageSetting)pkg.mExtras; 5814 if (ps != null) { 5815 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5816 userId); 5817 } 5818 } 5819 } 5820 5821 return new ParceledListSlice<PackageInfo>(list); 5822 } 5823 } 5824 5825 @Override 5826 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5827 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5828 flags = updateFlagsForApplication(flags, userId, null); 5829 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5830 5831 // writer 5832 synchronized (mPackages) { 5833 ArrayList<ApplicationInfo> list; 5834 if (listUninstalled) { 5835 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5836 for (PackageSetting ps : mSettings.mPackages.values()) { 5837 ApplicationInfo ai; 5838 if (ps.pkg != null) { 5839 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5840 ps.readUserState(userId), userId); 5841 } else { 5842 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5843 } 5844 if (ai != null) { 5845 list.add(ai); 5846 } 5847 } 5848 } else { 5849 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5850 for (PackageParser.Package p : mPackages.values()) { 5851 if (p.mExtras != null) { 5852 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5853 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5854 if (ai != null) { 5855 list.add(ai); 5856 } 5857 } 5858 } 5859 } 5860 5861 return new ParceledListSlice<ApplicationInfo>(list); 5862 } 5863 } 5864 5865 @Override 5866 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 5867 if (DISABLE_EPHEMERAL_APPS) { 5868 return null; 5869 } 5870 5871 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 5872 "getEphemeralApplications"); 5873 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5874 "getEphemeralApplications"); 5875 synchronized (mPackages) { 5876 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 5877 .getEphemeralApplicationsLPw(userId); 5878 if (ephemeralApps != null) { 5879 return new ParceledListSlice<>(ephemeralApps); 5880 } 5881 } 5882 return null; 5883 } 5884 5885 @Override 5886 public boolean isEphemeralApplication(String packageName, int userId) { 5887 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5888 "isEphemeral"); 5889 if (DISABLE_EPHEMERAL_APPS) { 5890 return false; 5891 } 5892 5893 if (!isCallerSameApp(packageName)) { 5894 return false; 5895 } 5896 synchronized (mPackages) { 5897 PackageParser.Package pkg = mPackages.get(packageName); 5898 if (pkg != null) { 5899 return pkg.applicationInfo.isEphemeralApp(); 5900 } 5901 } 5902 return false; 5903 } 5904 5905 @Override 5906 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 5907 if (DISABLE_EPHEMERAL_APPS) { 5908 return null; 5909 } 5910 5911 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5912 "getCookie"); 5913 if (!isCallerSameApp(packageName)) { 5914 return null; 5915 } 5916 synchronized (mPackages) { 5917 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 5918 packageName, userId); 5919 } 5920 } 5921 5922 @Override 5923 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 5924 if (DISABLE_EPHEMERAL_APPS) { 5925 return true; 5926 } 5927 5928 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5929 "setCookie"); 5930 if (!isCallerSameApp(packageName)) { 5931 return false; 5932 } 5933 synchronized (mPackages) { 5934 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 5935 packageName, cookie, userId); 5936 } 5937 } 5938 5939 @Override 5940 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 5941 if (DISABLE_EPHEMERAL_APPS) { 5942 return null; 5943 } 5944 5945 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 5946 "getEphemeralApplicationIcon"); 5947 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5948 "getEphemeralApplicationIcon"); 5949 synchronized (mPackages) { 5950 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 5951 packageName, userId); 5952 } 5953 } 5954 5955 private boolean isCallerSameApp(String packageName) { 5956 PackageParser.Package pkg = mPackages.get(packageName); 5957 return pkg != null 5958 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 5959 } 5960 5961 public List<ApplicationInfo> getPersistentApplications(int flags) { 5962 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5963 5964 // reader 5965 synchronized (mPackages) { 5966 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5967 final int userId = UserHandle.getCallingUserId(); 5968 while (i.hasNext()) { 5969 final PackageParser.Package p = i.next(); 5970 if (p.applicationInfo != null 5971 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5972 && (!mSafeMode || isSystemApp(p))) { 5973 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5974 if (ps != null) { 5975 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5976 ps.readUserState(userId), userId); 5977 if (ai != null) { 5978 finalList.add(ai); 5979 } 5980 } 5981 } 5982 } 5983 } 5984 5985 return finalList; 5986 } 5987 5988 @Override 5989 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5990 if (!sUserManager.exists(userId)) return null; 5991 flags = updateFlagsForComponent(flags, userId, name); 5992 // reader 5993 synchronized (mPackages) { 5994 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5995 PackageSetting ps = provider != null 5996 ? mSettings.mPackages.get(provider.owner.packageName) 5997 : null; 5998 return ps != null 5999 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6000 ? PackageParser.generateProviderInfo(provider, flags, 6001 ps.readUserState(userId), userId) 6002 : null; 6003 } 6004 } 6005 6006 /** 6007 * @deprecated 6008 */ 6009 @Deprecated 6010 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6011 // reader 6012 synchronized (mPackages) { 6013 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6014 .entrySet().iterator(); 6015 final int userId = UserHandle.getCallingUserId(); 6016 while (i.hasNext()) { 6017 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6018 PackageParser.Provider p = entry.getValue(); 6019 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6020 6021 if (ps != null && p.syncable 6022 && (!mSafeMode || (p.info.applicationInfo.flags 6023 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6024 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6025 ps.readUserState(userId), userId); 6026 if (info != null) { 6027 outNames.add(entry.getKey()); 6028 outInfo.add(info); 6029 } 6030 } 6031 } 6032 } 6033 } 6034 6035 @Override 6036 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6037 int uid, int flags) { 6038 final int userId = processName != null ? UserHandle.getUserId(uid) 6039 : UserHandle.getCallingUserId(); 6040 if (!sUserManager.exists(userId)) return null; 6041 flags = updateFlagsForComponent(flags, userId, processName); 6042 6043 ArrayList<ProviderInfo> finalList = null; 6044 // reader 6045 synchronized (mPackages) { 6046 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6047 while (i.hasNext()) { 6048 final PackageParser.Provider p = i.next(); 6049 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6050 if (ps != null && p.info.authority != null 6051 && (processName == null 6052 || (p.info.processName.equals(processName) 6053 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6054 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6055 if (finalList == null) { 6056 finalList = new ArrayList<ProviderInfo>(3); 6057 } 6058 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6059 ps.readUserState(userId), userId); 6060 if (info != null) { 6061 finalList.add(info); 6062 } 6063 } 6064 } 6065 } 6066 6067 if (finalList != null) { 6068 Collections.sort(finalList, mProviderInitOrderSorter); 6069 return new ParceledListSlice<ProviderInfo>(finalList); 6070 } 6071 6072 return null; 6073 } 6074 6075 @Override 6076 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6077 // reader 6078 synchronized (mPackages) { 6079 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6080 return PackageParser.generateInstrumentationInfo(i, flags); 6081 } 6082 } 6083 6084 @Override 6085 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 6086 int flags) { 6087 ArrayList<InstrumentationInfo> finalList = 6088 new ArrayList<InstrumentationInfo>(); 6089 6090 // reader 6091 synchronized (mPackages) { 6092 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6093 while (i.hasNext()) { 6094 final PackageParser.Instrumentation p = i.next(); 6095 if (targetPackage == null 6096 || targetPackage.equals(p.info.targetPackage)) { 6097 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6098 flags); 6099 if (ii != null) { 6100 finalList.add(ii); 6101 } 6102 } 6103 } 6104 } 6105 6106 return finalList; 6107 } 6108 6109 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6110 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6111 if (overlays == null) { 6112 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6113 return; 6114 } 6115 for (PackageParser.Package opkg : overlays.values()) { 6116 // Not much to do if idmap fails: we already logged the error 6117 // and we certainly don't want to abort installation of pkg simply 6118 // because an overlay didn't fit properly. For these reasons, 6119 // ignore the return value of createIdmapForPackagePairLI. 6120 createIdmapForPackagePairLI(pkg, opkg); 6121 } 6122 } 6123 6124 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6125 PackageParser.Package opkg) { 6126 if (!opkg.mTrustedOverlay) { 6127 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6128 opkg.baseCodePath + ": overlay not trusted"); 6129 return false; 6130 } 6131 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6132 if (overlaySet == null) { 6133 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6134 opkg.baseCodePath + " but target package has no known overlays"); 6135 return false; 6136 } 6137 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6138 // TODO: generate idmap for split APKs 6139 try { 6140 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6141 } catch (InstallerException e) { 6142 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6143 + opkg.baseCodePath); 6144 return false; 6145 } 6146 PackageParser.Package[] overlayArray = 6147 overlaySet.values().toArray(new PackageParser.Package[0]); 6148 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6149 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6150 return p1.mOverlayPriority - p2.mOverlayPriority; 6151 } 6152 }; 6153 Arrays.sort(overlayArray, cmp); 6154 6155 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6156 int i = 0; 6157 for (PackageParser.Package p : overlayArray) { 6158 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6159 } 6160 return true; 6161 } 6162 6163 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6164 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6165 try { 6166 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6167 } finally { 6168 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6169 } 6170 } 6171 6172 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6173 final File[] files = dir.listFiles(); 6174 if (ArrayUtils.isEmpty(files)) { 6175 Log.d(TAG, "No files in app dir " + dir); 6176 return; 6177 } 6178 6179 if (DEBUG_PACKAGE_SCANNING) { 6180 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6181 + " flags=0x" + Integer.toHexString(parseFlags)); 6182 } 6183 6184 for (File file : files) { 6185 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6186 && !PackageInstallerService.isStageName(file.getName()); 6187 if (!isPackage) { 6188 // Ignore entries which are not packages 6189 continue; 6190 } 6191 try { 6192 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6193 scanFlags, currentTime, null); 6194 } catch (PackageManagerException e) { 6195 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6196 6197 // Delete invalid userdata apps 6198 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6199 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6200 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6201 removeCodePathLI(file); 6202 } 6203 } 6204 } 6205 } 6206 6207 private static File getSettingsProblemFile() { 6208 File dataDir = Environment.getDataDirectory(); 6209 File systemDir = new File(dataDir, "system"); 6210 File fname = new File(systemDir, "uiderrors.txt"); 6211 return fname; 6212 } 6213 6214 static void reportSettingsProblem(int priority, String msg) { 6215 logCriticalInfo(priority, msg); 6216 } 6217 6218 static void logCriticalInfo(int priority, String msg) { 6219 Slog.println(priority, TAG, msg); 6220 EventLogTags.writePmCriticalInfo(msg); 6221 try { 6222 File fname = getSettingsProblemFile(); 6223 FileOutputStream out = new FileOutputStream(fname, true); 6224 PrintWriter pw = new FastPrintWriter(out); 6225 SimpleDateFormat formatter = new SimpleDateFormat(); 6226 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6227 pw.println(dateString + ": " + msg); 6228 pw.close(); 6229 FileUtils.setPermissions( 6230 fname.toString(), 6231 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6232 -1, -1); 6233 } catch (java.io.IOException e) { 6234 } 6235 } 6236 6237 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 6238 PackageParser.Package pkg, File srcFile, int parseFlags) 6239 throws PackageManagerException { 6240 if (ps != null 6241 && ps.codePath.equals(srcFile) 6242 && ps.timeStamp == srcFile.lastModified() 6243 && !isCompatSignatureUpdateNeeded(pkg) 6244 && !isRecoverSignatureUpdateNeeded(pkg)) { 6245 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6246 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6247 ArraySet<PublicKey> signingKs; 6248 synchronized (mPackages) { 6249 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6250 } 6251 if (ps.signatures.mSignatures != null 6252 && ps.signatures.mSignatures.length != 0 6253 && signingKs != null) { 6254 // Optimization: reuse the existing cached certificates 6255 // if the package appears to be unchanged. 6256 pkg.mSignatures = ps.signatures.mSignatures; 6257 pkg.mSigningKeys = signingKs; 6258 return; 6259 } 6260 6261 Slog.w(TAG, "PackageSetting for " + ps.name 6262 + " is missing signatures. Collecting certs again to recover them."); 6263 } else { 6264 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6265 } 6266 6267 try { 6268 pp.collectCertificates(pkg, parseFlags); 6269 } catch (PackageParserException e) { 6270 throw PackageManagerException.from(e); 6271 } 6272 } 6273 6274 /** 6275 * Traces a package scan. 6276 * @see #scanPackageLI(File, int, int, long, UserHandle) 6277 */ 6278 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6279 long currentTime, UserHandle user) throws PackageManagerException { 6280 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6281 try { 6282 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6283 } finally { 6284 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6285 } 6286 } 6287 6288 /** 6289 * Scans a package and returns the newly parsed package. 6290 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6291 */ 6292 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6293 long currentTime, UserHandle user) throws PackageManagerException { 6294 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6295 parseFlags |= mDefParseFlags; 6296 PackageParser pp = new PackageParser(); 6297 pp.setSeparateProcesses(mSeparateProcesses); 6298 pp.setOnlyCoreApps(mOnlyCore); 6299 pp.setDisplayMetrics(mMetrics); 6300 6301 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6302 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6303 } 6304 6305 final PackageParser.Package pkg; 6306 try { 6307 pkg = pp.parsePackage(scanFile, parseFlags); 6308 } catch (PackageParserException e) { 6309 throw PackageManagerException.from(e); 6310 } 6311 6312 PackageSetting ps = null; 6313 PackageSetting updatedPkg; 6314 // reader 6315 synchronized (mPackages) { 6316 // Look to see if we already know about this package. 6317 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6318 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6319 // This package has been renamed to its original name. Let's 6320 // use that. 6321 ps = mSettings.peekPackageLPr(oldName); 6322 } 6323 // If there was no original package, see one for the real package name. 6324 if (ps == null) { 6325 ps = mSettings.peekPackageLPr(pkg.packageName); 6326 } 6327 // Check to see if this package could be hiding/updating a system 6328 // package. Must look for it either under the original or real 6329 // package name depending on our state. 6330 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6331 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6332 } 6333 boolean updatedPkgBetter = false; 6334 // First check if this is a system package that may involve an update 6335 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6336 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6337 // it needs to drop FLAG_PRIVILEGED. 6338 if (locationIsPrivileged(scanFile)) { 6339 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6340 } else { 6341 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6342 } 6343 6344 if (ps != null && !ps.codePath.equals(scanFile)) { 6345 // The path has changed from what was last scanned... check the 6346 // version of the new path against what we have stored to determine 6347 // what to do. 6348 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6349 if (pkg.mVersionCode <= ps.versionCode) { 6350 // The system package has been updated and the code path does not match 6351 // Ignore entry. Skip it. 6352 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6353 + " ignored: updated version " + ps.versionCode 6354 + " better than this " + pkg.mVersionCode); 6355 if (!updatedPkg.codePath.equals(scanFile)) { 6356 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6357 + ps.name + " changing from " + updatedPkg.codePathString 6358 + " to " + scanFile); 6359 updatedPkg.codePath = scanFile; 6360 updatedPkg.codePathString = scanFile.toString(); 6361 updatedPkg.resourcePath = scanFile; 6362 updatedPkg.resourcePathString = scanFile.toString(); 6363 } 6364 updatedPkg.pkg = pkg; 6365 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6366 "Package " + ps.name + " at " + scanFile 6367 + " ignored: updated version " + ps.versionCode 6368 + " better than this " + pkg.mVersionCode); 6369 } else { 6370 // The current app on the system partition is better than 6371 // what we have updated to on the data partition; switch 6372 // back to the system partition version. 6373 // At this point, its safely assumed that package installation for 6374 // apps in system partition will go through. If not there won't be a working 6375 // version of the app 6376 // writer 6377 synchronized (mPackages) { 6378 // Just remove the loaded entries from package lists. 6379 mPackages.remove(ps.name); 6380 } 6381 6382 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6383 + " reverting from " + ps.codePathString 6384 + ": new version " + pkg.mVersionCode 6385 + " better than installed " + ps.versionCode); 6386 6387 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6388 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6389 synchronized (mInstallLock) { 6390 args.cleanUpResourcesLI(); 6391 } 6392 synchronized (mPackages) { 6393 mSettings.enableSystemPackageLPw(ps.name); 6394 } 6395 updatedPkgBetter = true; 6396 } 6397 } 6398 } 6399 6400 if (updatedPkg != null) { 6401 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6402 // initially 6403 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6404 6405 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6406 // flag set initially 6407 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6408 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6409 } 6410 } 6411 6412 // Verify certificates against what was last scanned 6413 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 6414 6415 /* 6416 * A new system app appeared, but we already had a non-system one of the 6417 * same name installed earlier. 6418 */ 6419 boolean shouldHideSystemApp = false; 6420 if (updatedPkg == null && ps != null 6421 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6422 /* 6423 * Check to make sure the signatures match first. If they don't, 6424 * wipe the installed application and its data. 6425 */ 6426 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6427 != PackageManager.SIGNATURE_MATCH) { 6428 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6429 + " signatures don't match existing userdata copy; removing"); 6430 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 6431 ps = null; 6432 } else { 6433 /* 6434 * If the newly-added system app is an older version than the 6435 * already installed version, hide it. It will be scanned later 6436 * and re-added like an update. 6437 */ 6438 if (pkg.mVersionCode <= ps.versionCode) { 6439 shouldHideSystemApp = true; 6440 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6441 + " but new version " + pkg.mVersionCode + " better than installed " 6442 + ps.versionCode + "; hiding system"); 6443 } else { 6444 /* 6445 * The newly found system app is a newer version that the 6446 * one previously installed. Simply remove the 6447 * already-installed application and replace it with our own 6448 * while keeping the application data. 6449 */ 6450 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6451 + " reverting from " + ps.codePathString + ": new version " 6452 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6453 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6454 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6455 synchronized (mInstallLock) { 6456 args.cleanUpResourcesLI(); 6457 } 6458 } 6459 } 6460 } 6461 6462 // The apk is forward locked (not public) if its code and resources 6463 // are kept in different files. (except for app in either system or 6464 // vendor path). 6465 // TODO grab this value from PackageSettings 6466 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6467 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6468 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6469 } 6470 } 6471 6472 // TODO: extend to support forward-locked splits 6473 String resourcePath = null; 6474 String baseResourcePath = null; 6475 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6476 if (ps != null && ps.resourcePathString != null) { 6477 resourcePath = ps.resourcePathString; 6478 baseResourcePath = ps.resourcePathString; 6479 } else { 6480 // Should not happen at all. Just log an error. 6481 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6482 } 6483 } else { 6484 resourcePath = pkg.codePath; 6485 baseResourcePath = pkg.baseCodePath; 6486 } 6487 6488 // Set application objects path explicitly. 6489 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 6490 pkg.applicationInfo.setCodePath(pkg.codePath); 6491 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 6492 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 6493 pkg.applicationInfo.setResourcePath(resourcePath); 6494 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 6495 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 6496 6497 // Note that we invoke the following method only if we are about to unpack an application 6498 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6499 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6500 6501 /* 6502 * If the system app should be overridden by a previously installed 6503 * data, hide the system app now and let the /data/app scan pick it up 6504 * again. 6505 */ 6506 if (shouldHideSystemApp) { 6507 synchronized (mPackages) { 6508 mSettings.disableSystemPackageLPw(pkg.packageName); 6509 } 6510 } 6511 6512 return scannedPkg; 6513 } 6514 6515 private static String fixProcessName(String defProcessName, 6516 String processName, int uid) { 6517 if (processName == null) { 6518 return defProcessName; 6519 } 6520 return processName; 6521 } 6522 6523 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6524 throws PackageManagerException { 6525 if (pkgSetting.signatures.mSignatures != null) { 6526 // Already existing package. Make sure signatures match 6527 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6528 == PackageManager.SIGNATURE_MATCH; 6529 if (!match) { 6530 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6531 == PackageManager.SIGNATURE_MATCH; 6532 } 6533 if (!match) { 6534 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6535 == PackageManager.SIGNATURE_MATCH; 6536 } 6537 if (!match) { 6538 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6539 + pkg.packageName + " signatures do not match the " 6540 + "previously installed version; ignoring!"); 6541 } 6542 } 6543 6544 // Check for shared user signatures 6545 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6546 // Already existing package. Make sure signatures match 6547 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6548 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6549 if (!match) { 6550 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6551 == PackageManager.SIGNATURE_MATCH; 6552 } 6553 if (!match) { 6554 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6555 == PackageManager.SIGNATURE_MATCH; 6556 } 6557 if (!match) { 6558 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6559 "Package " + pkg.packageName 6560 + " has no signatures that match those in shared user " 6561 + pkgSetting.sharedUser.name + "; ignoring!"); 6562 } 6563 } 6564 } 6565 6566 /** 6567 * Enforces that only the system UID or root's UID can call a method exposed 6568 * via Binder. 6569 * 6570 * @param message used as message if SecurityException is thrown 6571 * @throws SecurityException if the caller is not system or root 6572 */ 6573 private static final void enforceSystemOrRoot(String message) { 6574 final int uid = Binder.getCallingUid(); 6575 if (uid != Process.SYSTEM_UID && uid != 0) { 6576 throw new SecurityException(message); 6577 } 6578 } 6579 6580 @Override 6581 public void performFstrimIfNeeded() { 6582 enforceSystemOrRoot("Only the system can request fstrim"); 6583 6584 // Before everything else, see whether we need to fstrim. 6585 try { 6586 IMountService ms = PackageHelper.getMountService(); 6587 if (ms != null) { 6588 final boolean isUpgrade = isUpgrade(); 6589 boolean doTrim = isUpgrade; 6590 if (doTrim) { 6591 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6592 } else { 6593 final long interval = android.provider.Settings.Global.getLong( 6594 mContext.getContentResolver(), 6595 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6596 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6597 if (interval > 0) { 6598 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6599 if (timeSinceLast > interval) { 6600 doTrim = true; 6601 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6602 + "; running immediately"); 6603 } 6604 } 6605 } 6606 if (doTrim) { 6607 if (!isFirstBoot()) { 6608 try { 6609 ActivityManagerNative.getDefault().showBootMessage( 6610 mContext.getResources().getString( 6611 R.string.android_upgrading_fstrim), true); 6612 } catch (RemoteException e) { 6613 } 6614 } 6615 ms.runMaintenance(); 6616 } 6617 } else { 6618 Slog.e(TAG, "Mount service unavailable!"); 6619 } 6620 } catch (RemoteException e) { 6621 // Can't happen; MountService is local 6622 } 6623 } 6624 6625 @Override 6626 public void extractPackagesIfNeeded() { 6627 enforceSystemOrRoot("Only the system can request package extraction"); 6628 6629 // Extract pacakges only if profile-guided compilation is enabled because 6630 // otherwise BackgroundDexOptService will not dexopt them later. 6631 if (mUseJitProfiles) { 6632 ArraySet<String> pkgs = getOptimizablePackages(); 6633 if (pkgs != null) { 6634 for (String pkg : pkgs) { 6635 performDexOpt(pkg, null /* instructionSet */, false /* useProfiles */, 6636 true /* extractOnly */, false /* force */); 6637 } 6638 } 6639 } 6640 } 6641 6642 private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) { 6643 List<ResolveInfo> ris = null; 6644 try { 6645 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6646 intent, null, 0, userId); 6647 } catch (RemoteException e) { 6648 } 6649 ArraySet<String> pkgNames = new ArraySet<String>(); 6650 if (ris != null) { 6651 for (ResolveInfo ri : ris) { 6652 pkgNames.add(ri.activityInfo.packageName); 6653 } 6654 } 6655 return pkgNames; 6656 } 6657 6658 @Override 6659 public void notifyPackageUse(String packageName) { 6660 synchronized (mPackages) { 6661 PackageParser.Package p = mPackages.get(packageName); 6662 if (p == null) { 6663 return; 6664 } 6665 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6666 } 6667 } 6668 6669 // TODO: this is not used nor needed. Delete it. 6670 @Override 6671 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6672 return performDexOptTraced(packageName, instructionSet, false /* useProfiles */, 6673 false /* extractOnly */, false /* force */); 6674 } 6675 6676 @Override 6677 public boolean performDexOpt(String packageName, String instructionSet, boolean useProfiles, 6678 boolean extractOnly, boolean force) { 6679 return performDexOptTraced(packageName, instructionSet, useProfiles, extractOnly, force); 6680 } 6681 6682 private boolean performDexOptTraced(String packageName, String instructionSet, 6683 boolean useProfiles, boolean extractOnly, boolean force) { 6684 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6685 try { 6686 return performDexOptInternal(packageName, instructionSet, useProfiles, extractOnly, 6687 force); 6688 } finally { 6689 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6690 } 6691 } 6692 6693 private boolean performDexOptInternal(String packageName, String instructionSet, 6694 boolean useProfiles, boolean extractOnly, boolean force) { 6695 PackageParser.Package p; 6696 final String targetInstructionSet; 6697 synchronized (mPackages) { 6698 p = mPackages.get(packageName); 6699 if (p == null) { 6700 return false; 6701 } 6702 mPackageUsage.write(false); 6703 6704 targetInstructionSet = instructionSet != null ? instructionSet : 6705 getPrimaryInstructionSet(p.applicationInfo); 6706 if (!force && !useProfiles && p.mDexOptPerformed.contains(targetInstructionSet)) { 6707 // Skip only if we do not use profiles since they might trigger a recompilation. 6708 return false; 6709 } 6710 } 6711 long callingId = Binder.clearCallingIdentity(); 6712 try { 6713 synchronized (mInstallLock) { 6714 final String[] instructionSets = new String[] { targetInstructionSet }; 6715 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6716 true /* inclDependencies */, useProfiles, extractOnly, force); 6717 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6718 } 6719 } finally { 6720 Binder.restoreCallingIdentity(callingId); 6721 } 6722 } 6723 6724 public ArraySet<String> getOptimizablePackages() { 6725 ArraySet<String> pkgs = new ArraySet<String>(); 6726 synchronized (mPackages) { 6727 for (PackageParser.Package p : mPackages.values()) { 6728 if (PackageDexOptimizer.canOptimizePackage(p)) { 6729 pkgs.add(p.packageName); 6730 } 6731 } 6732 } 6733 return pkgs; 6734 } 6735 6736 public void shutdown() { 6737 mPackageUsage.write(true); 6738 } 6739 6740 @Override 6741 public void forceDexOpt(String packageName) { 6742 enforceSystemOrRoot("forceDexOpt"); 6743 6744 PackageParser.Package pkg; 6745 synchronized (mPackages) { 6746 pkg = mPackages.get(packageName); 6747 if (pkg == null) { 6748 throw new IllegalArgumentException("Unknown package: " + packageName); 6749 } 6750 } 6751 6752 synchronized (mInstallLock) { 6753 final String[] instructionSets = new String[] { 6754 getPrimaryInstructionSet(pkg.applicationInfo) }; 6755 6756 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6757 6758 // Whoever is calling forceDexOpt wants a fully compiled package. 6759 // Don't use profiles since that may cause compilation to be skipped. 6760 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6761 true /* inclDependencies */, false /* useProfiles */, 6762 false /* extractOnly */, true /* force */); 6763 6764 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6765 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6766 throw new IllegalStateException("Failed to dexopt: " + res); 6767 } 6768 } 6769 } 6770 6771 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6772 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6773 Slog.w(TAG, "Unable to update from " + oldPkg.name 6774 + " to " + newPkg.packageName 6775 + ": old package not in system partition"); 6776 return false; 6777 } else if (mPackages.get(oldPkg.name) != null) { 6778 Slog.w(TAG, "Unable to update from " + oldPkg.name 6779 + " to " + newPkg.packageName 6780 + ": old package still exists"); 6781 return false; 6782 } 6783 return true; 6784 } 6785 6786 private boolean removeDataDirsLI(String volumeUuid, String packageName) { 6787 // TODO: triage flags as part of 26466827 6788 final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 6789 6790 boolean res = true; 6791 final int[] users = sUserManager.getUserIds(); 6792 for (int user : users) { 6793 try { 6794 mInstaller.destroyAppData(volumeUuid, packageName, user, flags); 6795 } catch (InstallerException e) { 6796 Slog.w(TAG, "Failed to delete data directory", e); 6797 res = false; 6798 } 6799 } 6800 return res; 6801 } 6802 6803 void removeCodePathLI(File codePath) { 6804 if (codePath.isDirectory()) { 6805 try { 6806 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 6807 } catch (InstallerException e) { 6808 Slog.w(TAG, "Failed to remove code path", e); 6809 } 6810 } else { 6811 codePath.delete(); 6812 } 6813 } 6814 6815 void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) { 6816 try { 6817 mInstaller.destroyAppData(volumeUuid, packageName, userId, flags); 6818 } catch (InstallerException e) { 6819 Slog.w(TAG, "Failed to destroy app data", e); 6820 } 6821 } 6822 6823 void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags, 6824 int appId, String seinfo) { 6825 try { 6826 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo); 6827 } catch (InstallerException e) { 6828 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 6829 } 6830 } 6831 6832 private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6833 // TODO: triage flags as part of 26466827 6834 final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 6835 6836 final int[] users = sUserManager.getUserIds(); 6837 for (int user : users) { 6838 try { 6839 mInstaller.clearAppData(volumeUuid, packageName, user, 6840 flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 6841 } catch (InstallerException e) { 6842 Slog.w(TAG, "Failed to delete code cache directory", e); 6843 } 6844 } 6845 } 6846 6847 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6848 PackageParser.Package changingLib) { 6849 if (file.path != null) { 6850 usesLibraryFiles.add(file.path); 6851 return; 6852 } 6853 PackageParser.Package p = mPackages.get(file.apk); 6854 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6855 // If we are doing this while in the middle of updating a library apk, 6856 // then we need to make sure to use that new apk for determining the 6857 // dependencies here. (We haven't yet finished committing the new apk 6858 // to the package manager state.) 6859 if (p == null || p.packageName.equals(changingLib.packageName)) { 6860 p = changingLib; 6861 } 6862 } 6863 if (p != null) { 6864 usesLibraryFiles.addAll(p.getAllCodePaths()); 6865 } 6866 } 6867 6868 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6869 PackageParser.Package changingLib) throws PackageManagerException { 6870 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6871 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6872 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6873 for (int i=0; i<N; i++) { 6874 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6875 if (file == null) { 6876 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6877 "Package " + pkg.packageName + " requires unavailable shared library " 6878 + pkg.usesLibraries.get(i) + "; failing!"); 6879 } 6880 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6881 } 6882 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6883 for (int i=0; i<N; i++) { 6884 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6885 if (file == null) { 6886 Slog.w(TAG, "Package " + pkg.packageName 6887 + " desires unavailable shared library " 6888 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6889 } else { 6890 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6891 } 6892 } 6893 N = usesLibraryFiles.size(); 6894 if (N > 0) { 6895 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6896 } else { 6897 pkg.usesLibraryFiles = null; 6898 } 6899 } 6900 } 6901 6902 private static boolean hasString(List<String> list, List<String> which) { 6903 if (list == null) { 6904 return false; 6905 } 6906 for (int i=list.size()-1; i>=0; i--) { 6907 for (int j=which.size()-1; j>=0; j--) { 6908 if (which.get(j).equals(list.get(i))) { 6909 return true; 6910 } 6911 } 6912 } 6913 return false; 6914 } 6915 6916 private void updateAllSharedLibrariesLPw() { 6917 for (PackageParser.Package pkg : mPackages.values()) { 6918 try { 6919 updateSharedLibrariesLPw(pkg, null); 6920 } catch (PackageManagerException e) { 6921 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6922 } 6923 } 6924 } 6925 6926 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6927 PackageParser.Package changingPkg) { 6928 ArrayList<PackageParser.Package> res = null; 6929 for (PackageParser.Package pkg : mPackages.values()) { 6930 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6931 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6932 if (res == null) { 6933 res = new ArrayList<PackageParser.Package>(); 6934 } 6935 res.add(pkg); 6936 try { 6937 updateSharedLibrariesLPw(pkg, changingPkg); 6938 } catch (PackageManagerException e) { 6939 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6940 } 6941 } 6942 } 6943 return res; 6944 } 6945 6946 /** 6947 * Derive the value of the {@code cpuAbiOverride} based on the provided 6948 * value and an optional stored value from the package settings. 6949 */ 6950 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6951 String cpuAbiOverride = null; 6952 6953 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6954 cpuAbiOverride = null; 6955 } else if (abiOverride != null) { 6956 cpuAbiOverride = abiOverride; 6957 } else if (settings != null) { 6958 cpuAbiOverride = settings.cpuAbiOverrideString; 6959 } 6960 6961 return cpuAbiOverride; 6962 } 6963 6964 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 6965 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6966 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6967 try { 6968 return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 6969 } finally { 6970 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6971 } 6972 } 6973 6974 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6975 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6976 boolean success = false; 6977 try { 6978 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6979 currentTime, user); 6980 success = true; 6981 return res; 6982 } finally { 6983 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6984 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6985 } 6986 } 6987 } 6988 6989 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6990 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6991 final File scanFile = new File(pkg.codePath); 6992 if (pkg.applicationInfo.getCodePath() == null || 6993 pkg.applicationInfo.getResourcePath() == null) { 6994 // Bail out. The resource and code paths haven't been set. 6995 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6996 "Code and resource paths haven't been set correctly"); 6997 } 6998 6999 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7000 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7001 } else { 7002 // Only allow system apps to be flagged as core apps. 7003 pkg.coreApp = false; 7004 } 7005 7006 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7007 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7008 } 7009 7010 if (mCustomResolverComponentName != null && 7011 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7012 setUpCustomResolverActivity(pkg); 7013 } 7014 7015 if (pkg.packageName.equals("android")) { 7016 synchronized (mPackages) { 7017 if (mAndroidApplication != null) { 7018 Slog.w(TAG, "*************************************************"); 7019 Slog.w(TAG, "Core android package being redefined. Skipping."); 7020 Slog.w(TAG, " file=" + scanFile); 7021 Slog.w(TAG, "*************************************************"); 7022 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7023 "Core android package being redefined. Skipping."); 7024 } 7025 7026 // Set up information for our fall-back user intent resolution activity. 7027 mPlatformPackage = pkg; 7028 pkg.mVersionCode = mSdkVersion; 7029 mAndroidApplication = pkg.applicationInfo; 7030 7031 if (!mResolverReplaced) { 7032 mResolveActivity.applicationInfo = mAndroidApplication; 7033 mResolveActivity.name = ResolverActivity.class.getName(); 7034 mResolveActivity.packageName = mAndroidApplication.packageName; 7035 mResolveActivity.processName = "system:ui"; 7036 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7037 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7038 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7039 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7040 mResolveActivity.exported = true; 7041 mResolveActivity.enabled = true; 7042 mResolveInfo.activityInfo = mResolveActivity; 7043 mResolveInfo.priority = 0; 7044 mResolveInfo.preferredOrder = 0; 7045 mResolveInfo.match = 0; 7046 mResolveComponentName = new ComponentName( 7047 mAndroidApplication.packageName, mResolveActivity.name); 7048 } 7049 } 7050 } 7051 7052 if (DEBUG_PACKAGE_SCANNING) { 7053 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7054 Log.d(TAG, "Scanning package " + pkg.packageName); 7055 } 7056 7057 if (mPackages.containsKey(pkg.packageName) 7058 || mSharedLibraries.containsKey(pkg.packageName)) { 7059 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7060 "Application package " + pkg.packageName 7061 + " already installed. Skipping duplicate."); 7062 } 7063 7064 // If we're only installing presumed-existing packages, require that the 7065 // scanned APK is both already known and at the path previously established 7066 // for it. Previously unknown packages we pick up normally, but if we have an 7067 // a priori expectation about this package's install presence, enforce it. 7068 // With a singular exception for new system packages. When an OTA contains 7069 // a new system package, we allow the codepath to change from a system location 7070 // to the user-installed location. If we don't allow this change, any newer, 7071 // user-installed version of the application will be ignored. 7072 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7073 if (mExpectingBetter.containsKey(pkg.packageName)) { 7074 logCriticalInfo(Log.WARN, 7075 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7076 } else { 7077 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7078 if (known != null) { 7079 if (DEBUG_PACKAGE_SCANNING) { 7080 Log.d(TAG, "Examining " + pkg.codePath 7081 + " and requiring known paths " + known.codePathString 7082 + " & " + known.resourcePathString); 7083 } 7084 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7085 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 7086 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7087 "Application package " + pkg.packageName 7088 + " found at " + pkg.applicationInfo.getCodePath() 7089 + " but expected at " + known.codePathString + "; ignoring."); 7090 } 7091 } 7092 } 7093 } 7094 7095 // Initialize package source and resource directories 7096 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7097 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7098 7099 SharedUserSetting suid = null; 7100 PackageSetting pkgSetting = null; 7101 7102 if (!isSystemApp(pkg)) { 7103 // Only system apps can use these features. 7104 pkg.mOriginalPackages = null; 7105 pkg.mRealPackage = null; 7106 pkg.mAdoptPermissions = null; 7107 } 7108 7109 // writer 7110 synchronized (mPackages) { 7111 if (pkg.mSharedUserId != null) { 7112 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7113 if (suid == null) { 7114 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7115 "Creating application package " + pkg.packageName 7116 + " for shared user failed"); 7117 } 7118 if (DEBUG_PACKAGE_SCANNING) { 7119 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7120 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7121 + "): packages=" + suid.packages); 7122 } 7123 } 7124 7125 // Check if we are renaming from an original package name. 7126 PackageSetting origPackage = null; 7127 String realName = null; 7128 if (pkg.mOriginalPackages != null) { 7129 // This package may need to be renamed to a previously 7130 // installed name. Let's check on that... 7131 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7132 if (pkg.mOriginalPackages.contains(renamed)) { 7133 // This package had originally been installed as the 7134 // original name, and we have already taken care of 7135 // transitioning to the new one. Just update the new 7136 // one to continue using the old name. 7137 realName = pkg.mRealPackage; 7138 if (!pkg.packageName.equals(renamed)) { 7139 // Callers into this function may have already taken 7140 // care of renaming the package; only do it here if 7141 // it is not already done. 7142 pkg.setPackageName(renamed); 7143 } 7144 7145 } else { 7146 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7147 if ((origPackage = mSettings.peekPackageLPr( 7148 pkg.mOriginalPackages.get(i))) != null) { 7149 // We do have the package already installed under its 7150 // original name... should we use it? 7151 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7152 // New package is not compatible with original. 7153 origPackage = null; 7154 continue; 7155 } else if (origPackage.sharedUser != null) { 7156 // Make sure uid is compatible between packages. 7157 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7158 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7159 + " to " + pkg.packageName + ": old uid " 7160 + origPackage.sharedUser.name 7161 + " differs from " + pkg.mSharedUserId); 7162 origPackage = null; 7163 continue; 7164 } 7165 } else { 7166 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7167 + pkg.packageName + " to old name " + origPackage.name); 7168 } 7169 break; 7170 } 7171 } 7172 } 7173 } 7174 7175 if (mTransferedPackages.contains(pkg.packageName)) { 7176 Slog.w(TAG, "Package " + pkg.packageName 7177 + " was transferred to another, but its .apk remains"); 7178 } 7179 7180 // Just create the setting, don't add it yet. For already existing packages 7181 // the PkgSetting exists already and doesn't have to be created. 7182 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7183 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7184 pkg.applicationInfo.primaryCpuAbi, 7185 pkg.applicationInfo.secondaryCpuAbi, 7186 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7187 user, false); 7188 if (pkgSetting == null) { 7189 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7190 "Creating application package " + pkg.packageName + " failed"); 7191 } 7192 7193 if (pkgSetting.origPackage != null) { 7194 // If we are first transitioning from an original package, 7195 // fix up the new package's name now. We need to do this after 7196 // looking up the package under its new name, so getPackageLP 7197 // can take care of fiddling things correctly. 7198 pkg.setPackageName(origPackage.name); 7199 7200 // File a report about this. 7201 String msg = "New package " + pkgSetting.realName 7202 + " renamed to replace old package " + pkgSetting.name; 7203 reportSettingsProblem(Log.WARN, msg); 7204 7205 // Make a note of it. 7206 mTransferedPackages.add(origPackage.name); 7207 7208 // No longer need to retain this. 7209 pkgSetting.origPackage = null; 7210 } 7211 7212 if (realName != null) { 7213 // Make a note of it. 7214 mTransferedPackages.add(pkg.packageName); 7215 } 7216 7217 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7218 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7219 } 7220 7221 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7222 // Check all shared libraries and map to their actual file path. 7223 // We only do this here for apps not on a system dir, because those 7224 // are the only ones that can fail an install due to this. We 7225 // will take care of the system apps by updating all of their 7226 // library paths after the scan is done. 7227 updateSharedLibrariesLPw(pkg, null); 7228 } 7229 7230 if (mFoundPolicyFile) { 7231 SELinuxMMAC.assignSeinfoValue(pkg); 7232 } 7233 7234 pkg.applicationInfo.uid = pkgSetting.appId; 7235 pkg.mExtras = pkgSetting; 7236 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7237 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7238 // We just determined the app is signed correctly, so bring 7239 // over the latest parsed certs. 7240 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7241 } else { 7242 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7243 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7244 "Package " + pkg.packageName + " upgrade keys do not match the " 7245 + "previously installed version"); 7246 } else { 7247 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7248 String msg = "System package " + pkg.packageName 7249 + " signature changed; retaining data."; 7250 reportSettingsProblem(Log.WARN, msg); 7251 } 7252 } 7253 } else { 7254 try { 7255 verifySignaturesLP(pkgSetting, pkg); 7256 // We just determined the app is signed correctly, so bring 7257 // over the latest parsed certs. 7258 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7259 } catch (PackageManagerException e) { 7260 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7261 throw e; 7262 } 7263 // The signature has changed, but this package is in the system 7264 // image... let's recover! 7265 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7266 // However... if this package is part of a shared user, but it 7267 // doesn't match the signature of the shared user, let's fail. 7268 // What this means is that you can't change the signatures 7269 // associated with an overall shared user, which doesn't seem all 7270 // that unreasonable. 7271 if (pkgSetting.sharedUser != null) { 7272 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7273 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7274 throw new PackageManagerException( 7275 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7276 "Signature mismatch for shared user: " 7277 + pkgSetting.sharedUser); 7278 } 7279 } 7280 // File a report about this. 7281 String msg = "System package " + pkg.packageName 7282 + " signature changed; retaining data."; 7283 reportSettingsProblem(Log.WARN, msg); 7284 } 7285 } 7286 // Verify that this new package doesn't have any content providers 7287 // that conflict with existing packages. Only do this if the 7288 // package isn't already installed, since we don't want to break 7289 // things that are installed. 7290 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7291 final int N = pkg.providers.size(); 7292 int i; 7293 for (i=0; i<N; i++) { 7294 PackageParser.Provider p = pkg.providers.get(i); 7295 if (p.info.authority != null) { 7296 String names[] = p.info.authority.split(";"); 7297 for (int j = 0; j < names.length; j++) { 7298 if (mProvidersByAuthority.containsKey(names[j])) { 7299 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7300 final String otherPackageName = 7301 ((other != null && other.getComponentName() != null) ? 7302 other.getComponentName().getPackageName() : "?"); 7303 throw new PackageManagerException( 7304 INSTALL_FAILED_CONFLICTING_PROVIDER, 7305 "Can't install because provider name " + names[j] 7306 + " (in package " + pkg.applicationInfo.packageName 7307 + ") is already used by " + otherPackageName); 7308 } 7309 } 7310 } 7311 } 7312 } 7313 7314 if (pkg.mAdoptPermissions != null) { 7315 // This package wants to adopt ownership of permissions from 7316 // another package. 7317 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7318 final String origName = pkg.mAdoptPermissions.get(i); 7319 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7320 if (orig != null) { 7321 if (verifyPackageUpdateLPr(orig, pkg)) { 7322 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7323 + pkg.packageName); 7324 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7325 } 7326 } 7327 } 7328 } 7329 } 7330 7331 final String pkgName = pkg.packageName; 7332 7333 final long scanFileTime = scanFile.lastModified(); 7334 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7335 pkg.applicationInfo.processName = fixProcessName( 7336 pkg.applicationInfo.packageName, 7337 pkg.applicationInfo.processName, 7338 pkg.applicationInfo.uid); 7339 7340 if (pkg != mPlatformPackage) { 7341 // Get all of our default paths setup 7342 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7343 } 7344 7345 final String path = scanFile.getPath(); 7346 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7347 7348 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7349 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7350 7351 // Some system apps still use directory structure for native libraries 7352 // in which case we might end up not detecting abi solely based on apk 7353 // structure. Try to detect abi based on directory structure. 7354 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7355 pkg.applicationInfo.primaryCpuAbi == null) { 7356 setBundledAppAbisAndRoots(pkg, pkgSetting); 7357 setNativeLibraryPaths(pkg); 7358 } 7359 7360 } else { 7361 if ((scanFlags & SCAN_MOVE) != 0) { 7362 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7363 // but we already have this packages package info in the PackageSetting. We just 7364 // use that and derive the native library path based on the new codepath. 7365 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7366 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7367 } 7368 7369 // Set native library paths again. For moves, the path will be updated based on the 7370 // ABIs we've determined above. For non-moves, the path will be updated based on the 7371 // ABIs we determined during compilation, but the path will depend on the final 7372 // package path (after the rename away from the stage path). 7373 setNativeLibraryPaths(pkg); 7374 } 7375 7376 // This is a special case for the "system" package, where the ABI is 7377 // dictated by the zygote configuration (and init.rc). We should keep track 7378 // of this ABI so that we can deal with "normal" applications that run under 7379 // the same UID correctly. 7380 if (mPlatformPackage == pkg) { 7381 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7382 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7383 } 7384 7385 // If there's a mismatch between the abi-override in the package setting 7386 // and the abiOverride specified for the install. Warn about this because we 7387 // would've already compiled the app without taking the package setting into 7388 // account. 7389 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7390 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7391 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7392 " for package " + pkg.packageName); 7393 } 7394 } 7395 7396 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7397 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7398 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7399 7400 // Copy the derived override back to the parsed package, so that we can 7401 // update the package settings accordingly. 7402 pkg.cpuAbiOverride = cpuAbiOverride; 7403 7404 if (DEBUG_ABI_SELECTION) { 7405 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7406 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7407 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7408 } 7409 7410 // Push the derived path down into PackageSettings so we know what to 7411 // clean up at uninstall time. 7412 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7413 7414 if (DEBUG_ABI_SELECTION) { 7415 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7416 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7417 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7418 } 7419 7420 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7421 // We don't do this here during boot because we can do it all 7422 // at once after scanning all existing packages. 7423 // 7424 // We also do this *before* we perform dexopt on this package, so that 7425 // we can avoid redundant dexopts, and also to make sure we've got the 7426 // code and package path correct. 7427 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7428 pkg, true /* boot complete */); 7429 } 7430 7431 if (mFactoryTest && pkg.requestedPermissions.contains( 7432 android.Manifest.permission.FACTORY_TEST)) { 7433 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7434 } 7435 7436 ArrayList<PackageParser.Package> clientLibPkgs = null; 7437 7438 // writer 7439 synchronized (mPackages) { 7440 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7441 // Only system apps can add new shared libraries. 7442 if (pkg.libraryNames != null) { 7443 for (int i=0; i<pkg.libraryNames.size(); i++) { 7444 String name = pkg.libraryNames.get(i); 7445 boolean allowed = false; 7446 if (pkg.isUpdatedSystemApp()) { 7447 // New library entries can only be added through the 7448 // system image. This is important to get rid of a lot 7449 // of nasty edge cases: for example if we allowed a non- 7450 // system update of the app to add a library, then uninstalling 7451 // the update would make the library go away, and assumptions 7452 // we made such as through app install filtering would now 7453 // have allowed apps on the device which aren't compatible 7454 // with it. Better to just have the restriction here, be 7455 // conservative, and create many fewer cases that can negatively 7456 // impact the user experience. 7457 final PackageSetting sysPs = mSettings 7458 .getDisabledSystemPkgLPr(pkg.packageName); 7459 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7460 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7461 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7462 allowed = true; 7463 break; 7464 } 7465 } 7466 } 7467 } else { 7468 allowed = true; 7469 } 7470 if (allowed) { 7471 if (!mSharedLibraries.containsKey(name)) { 7472 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7473 } else if (!name.equals(pkg.packageName)) { 7474 Slog.w(TAG, "Package " + pkg.packageName + " library " 7475 + name + " already exists; skipping"); 7476 } 7477 } else { 7478 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7479 + name + " that is not declared on system image; skipping"); 7480 } 7481 } 7482 if ((scanFlags & SCAN_BOOTING) == 0) { 7483 // If we are not booting, we need to update any applications 7484 // that are clients of our shared library. If we are booting, 7485 // this will all be done once the scan is complete. 7486 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7487 } 7488 } 7489 } 7490 } 7491 7492 // Request the ActivityManager to kill the process(only for existing packages) 7493 // so that we do not end up in a confused state while the user is still using the older 7494 // version of the application while the new one gets installed. 7495 if ((scanFlags & SCAN_REPLACING) != 0) { 7496 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7497 7498 killApplication(pkg.applicationInfo.packageName, 7499 pkg.applicationInfo.uid, "replace pkg"); 7500 7501 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7502 } 7503 7504 // Also need to kill any apps that are dependent on the library. 7505 if (clientLibPkgs != null) { 7506 for (int i=0; i<clientLibPkgs.size(); i++) { 7507 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7508 killApplication(clientPkg.applicationInfo.packageName, 7509 clientPkg.applicationInfo.uid, "update lib"); 7510 } 7511 } 7512 7513 // Make sure we're not adding any bogus keyset info 7514 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7515 ksms.assertScannedPackageValid(pkg); 7516 7517 // writer 7518 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7519 7520 boolean createIdmapFailed = false; 7521 synchronized (mPackages) { 7522 // We don't expect installation to fail beyond this point 7523 7524 // Add the new setting to mSettings 7525 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7526 // Add the new setting to mPackages 7527 mPackages.put(pkg.applicationInfo.packageName, pkg); 7528 // Make sure we don't accidentally delete its data. 7529 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7530 while (iter.hasNext()) { 7531 PackageCleanItem item = iter.next(); 7532 if (pkgName.equals(item.packageName)) { 7533 iter.remove(); 7534 } 7535 } 7536 7537 // Take care of first install / last update times. 7538 if (currentTime != 0) { 7539 if (pkgSetting.firstInstallTime == 0) { 7540 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7541 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7542 pkgSetting.lastUpdateTime = currentTime; 7543 } 7544 } else if (pkgSetting.firstInstallTime == 0) { 7545 // We need *something*. Take time time stamp of the file. 7546 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7547 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7548 if (scanFileTime != pkgSetting.timeStamp) { 7549 // A package on the system image has changed; consider this 7550 // to be an update. 7551 pkgSetting.lastUpdateTime = scanFileTime; 7552 } 7553 } 7554 7555 // Add the package's KeySets to the global KeySetManagerService 7556 ksms.addScannedPackageLPw(pkg); 7557 7558 int N = pkg.providers.size(); 7559 StringBuilder r = null; 7560 int i; 7561 for (i=0; i<N; i++) { 7562 PackageParser.Provider p = pkg.providers.get(i); 7563 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7564 p.info.processName, pkg.applicationInfo.uid); 7565 mProviders.addProvider(p); 7566 p.syncable = p.info.isSyncable; 7567 if (p.info.authority != null) { 7568 String names[] = p.info.authority.split(";"); 7569 p.info.authority = null; 7570 for (int j = 0; j < names.length; j++) { 7571 if (j == 1 && p.syncable) { 7572 // We only want the first authority for a provider to possibly be 7573 // syncable, so if we already added this provider using a different 7574 // authority clear the syncable flag. We copy the provider before 7575 // changing it because the mProviders object contains a reference 7576 // to a provider that we don't want to change. 7577 // Only do this for the second authority since the resulting provider 7578 // object can be the same for all future authorities for this provider. 7579 p = new PackageParser.Provider(p); 7580 p.syncable = false; 7581 } 7582 if (!mProvidersByAuthority.containsKey(names[j])) { 7583 mProvidersByAuthority.put(names[j], p); 7584 if (p.info.authority == null) { 7585 p.info.authority = names[j]; 7586 } else { 7587 p.info.authority = p.info.authority + ";" + names[j]; 7588 } 7589 if (DEBUG_PACKAGE_SCANNING) { 7590 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7591 Log.d(TAG, "Registered content provider: " + names[j] 7592 + ", className = " + p.info.name + ", isSyncable = " 7593 + p.info.isSyncable); 7594 } 7595 } else { 7596 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7597 Slog.w(TAG, "Skipping provider name " + names[j] + 7598 " (in package " + pkg.applicationInfo.packageName + 7599 "): name already used by " 7600 + ((other != null && other.getComponentName() != null) 7601 ? other.getComponentName().getPackageName() : "?")); 7602 } 7603 } 7604 } 7605 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7606 if (r == null) { 7607 r = new StringBuilder(256); 7608 } else { 7609 r.append(' '); 7610 } 7611 r.append(p.info.name); 7612 } 7613 } 7614 if (r != null) { 7615 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7616 } 7617 7618 N = pkg.services.size(); 7619 r = null; 7620 for (i=0; i<N; i++) { 7621 PackageParser.Service s = pkg.services.get(i); 7622 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7623 s.info.processName, pkg.applicationInfo.uid); 7624 mServices.addService(s); 7625 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7626 if (r == null) { 7627 r = new StringBuilder(256); 7628 } else { 7629 r.append(' '); 7630 } 7631 r.append(s.info.name); 7632 } 7633 } 7634 if (r != null) { 7635 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7636 } 7637 7638 N = pkg.receivers.size(); 7639 r = null; 7640 for (i=0; i<N; i++) { 7641 PackageParser.Activity a = pkg.receivers.get(i); 7642 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7643 a.info.processName, pkg.applicationInfo.uid); 7644 mReceivers.addActivity(a, "receiver"); 7645 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7646 if (r == null) { 7647 r = new StringBuilder(256); 7648 } else { 7649 r.append(' '); 7650 } 7651 r.append(a.info.name); 7652 } 7653 } 7654 if (r != null) { 7655 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7656 } 7657 7658 N = pkg.activities.size(); 7659 r = null; 7660 for (i=0; i<N; i++) { 7661 PackageParser.Activity a = pkg.activities.get(i); 7662 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7663 a.info.processName, pkg.applicationInfo.uid); 7664 mActivities.addActivity(a, "activity"); 7665 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7666 if (r == null) { 7667 r = new StringBuilder(256); 7668 } else { 7669 r.append(' '); 7670 } 7671 r.append(a.info.name); 7672 } 7673 } 7674 if (r != null) { 7675 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7676 } 7677 7678 N = pkg.permissionGroups.size(); 7679 r = null; 7680 for (i=0; i<N; i++) { 7681 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7682 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7683 if (cur == null) { 7684 mPermissionGroups.put(pg.info.name, pg); 7685 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7686 if (r == null) { 7687 r = new StringBuilder(256); 7688 } else { 7689 r.append(' '); 7690 } 7691 r.append(pg.info.name); 7692 } 7693 } else { 7694 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7695 + pg.info.packageName + " ignored: original from " 7696 + cur.info.packageName); 7697 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7698 if (r == null) { 7699 r = new StringBuilder(256); 7700 } else { 7701 r.append(' '); 7702 } 7703 r.append("DUP:"); 7704 r.append(pg.info.name); 7705 } 7706 } 7707 } 7708 if (r != null) { 7709 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7710 } 7711 7712 N = pkg.permissions.size(); 7713 r = null; 7714 for (i=0; i<N; i++) { 7715 PackageParser.Permission p = pkg.permissions.get(i); 7716 7717 // Assume by default that we did not install this permission into the system. 7718 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7719 7720 // Now that permission groups have a special meaning, we ignore permission 7721 // groups for legacy apps to prevent unexpected behavior. In particular, 7722 // permissions for one app being granted to someone just becuase they happen 7723 // to be in a group defined by another app (before this had no implications). 7724 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7725 p.group = mPermissionGroups.get(p.info.group); 7726 // Warn for a permission in an unknown group. 7727 if (p.info.group != null && p.group == null) { 7728 Slog.w(TAG, "Permission " + p.info.name + " from package " 7729 + p.info.packageName + " in an unknown group " + p.info.group); 7730 } 7731 } 7732 7733 ArrayMap<String, BasePermission> permissionMap = 7734 p.tree ? mSettings.mPermissionTrees 7735 : mSettings.mPermissions; 7736 BasePermission bp = permissionMap.get(p.info.name); 7737 7738 // Allow system apps to redefine non-system permissions 7739 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7740 final boolean currentOwnerIsSystem = (bp.perm != null 7741 && isSystemApp(bp.perm.owner)); 7742 if (isSystemApp(p.owner)) { 7743 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7744 // It's a built-in permission and no owner, take ownership now 7745 bp.packageSetting = pkgSetting; 7746 bp.perm = p; 7747 bp.uid = pkg.applicationInfo.uid; 7748 bp.sourcePackage = p.info.packageName; 7749 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7750 } else if (!currentOwnerIsSystem) { 7751 String msg = "New decl " + p.owner + " of permission " 7752 + p.info.name + " is system; overriding " + bp.sourcePackage; 7753 reportSettingsProblem(Log.WARN, msg); 7754 bp = null; 7755 } 7756 } 7757 } 7758 7759 if (bp == null) { 7760 bp = new BasePermission(p.info.name, p.info.packageName, 7761 BasePermission.TYPE_NORMAL); 7762 permissionMap.put(p.info.name, bp); 7763 } 7764 7765 if (bp.perm == null) { 7766 if (bp.sourcePackage == null 7767 || bp.sourcePackage.equals(p.info.packageName)) { 7768 BasePermission tree = findPermissionTreeLP(p.info.name); 7769 if (tree == null 7770 || tree.sourcePackage.equals(p.info.packageName)) { 7771 bp.packageSetting = pkgSetting; 7772 bp.perm = p; 7773 bp.uid = pkg.applicationInfo.uid; 7774 bp.sourcePackage = p.info.packageName; 7775 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7776 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7777 if (r == null) { 7778 r = new StringBuilder(256); 7779 } else { 7780 r.append(' '); 7781 } 7782 r.append(p.info.name); 7783 } 7784 } else { 7785 Slog.w(TAG, "Permission " + p.info.name + " from package " 7786 + p.info.packageName + " ignored: base tree " 7787 + tree.name + " is from package " 7788 + tree.sourcePackage); 7789 } 7790 } else { 7791 Slog.w(TAG, "Permission " + p.info.name + " from package " 7792 + p.info.packageName + " ignored: original from " 7793 + bp.sourcePackage); 7794 } 7795 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7796 if (r == null) { 7797 r = new StringBuilder(256); 7798 } else { 7799 r.append(' '); 7800 } 7801 r.append("DUP:"); 7802 r.append(p.info.name); 7803 } 7804 if (bp.perm == p) { 7805 bp.protectionLevel = p.info.protectionLevel; 7806 } 7807 } 7808 7809 if (r != null) { 7810 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7811 } 7812 7813 N = pkg.instrumentation.size(); 7814 r = null; 7815 for (i=0; i<N; i++) { 7816 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7817 a.info.packageName = pkg.applicationInfo.packageName; 7818 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7819 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7820 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7821 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7822 a.info.dataDir = pkg.applicationInfo.dataDir; 7823 a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir; 7824 a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir; 7825 7826 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7827 // need other information about the application, like the ABI and what not ? 7828 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7829 mInstrumentation.put(a.getComponentName(), a); 7830 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7831 if (r == null) { 7832 r = new StringBuilder(256); 7833 } else { 7834 r.append(' '); 7835 } 7836 r.append(a.info.name); 7837 } 7838 } 7839 if (r != null) { 7840 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7841 } 7842 7843 if (pkg.protectedBroadcasts != null) { 7844 N = pkg.protectedBroadcasts.size(); 7845 for (i=0; i<N; i++) { 7846 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7847 } 7848 } 7849 7850 pkgSetting.setTimeStamp(scanFileTime); 7851 7852 // Create idmap files for pairs of (packages, overlay packages). 7853 // Note: "android", ie framework-res.apk, is handled by native layers. 7854 if (pkg.mOverlayTarget != null) { 7855 // This is an overlay package. 7856 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7857 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7858 mOverlays.put(pkg.mOverlayTarget, 7859 new ArrayMap<String, PackageParser.Package>()); 7860 } 7861 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7862 map.put(pkg.packageName, pkg); 7863 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7864 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7865 createIdmapFailed = true; 7866 } 7867 } 7868 } else if (mOverlays.containsKey(pkg.packageName) && 7869 !pkg.packageName.equals("android")) { 7870 // This is a regular package, with one or more known overlay packages. 7871 createIdmapsForPackageLI(pkg); 7872 } 7873 } 7874 7875 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7876 7877 if (createIdmapFailed) { 7878 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7879 "scanPackageLI failed to createIdmap"); 7880 } 7881 return pkg; 7882 } 7883 7884 /** 7885 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7886 * is derived purely on the basis of the contents of {@code scanFile} and 7887 * {@code cpuAbiOverride}. 7888 * 7889 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7890 */ 7891 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7892 String cpuAbiOverride, boolean extractLibs) 7893 throws PackageManagerException { 7894 // TODO: We can probably be smarter about this stuff. For installed apps, 7895 // we can calculate this information at install time once and for all. For 7896 // system apps, we can probably assume that this information doesn't change 7897 // after the first boot scan. As things stand, we do lots of unnecessary work. 7898 7899 // Give ourselves some initial paths; we'll come back for another 7900 // pass once we've determined ABI below. 7901 setNativeLibraryPaths(pkg); 7902 7903 // We would never need to extract libs for forward-locked and external packages, 7904 // since the container service will do it for us. We shouldn't attempt to 7905 // extract libs from system app when it was not updated. 7906 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 7907 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 7908 extractLibs = false; 7909 } 7910 7911 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7912 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7913 7914 NativeLibraryHelper.Handle handle = null; 7915 try { 7916 handle = NativeLibraryHelper.Handle.create(pkg); 7917 // TODO(multiArch): This can be null for apps that didn't go through the 7918 // usual installation process. We can calculate it again, like we 7919 // do during install time. 7920 // 7921 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7922 // unnecessary. 7923 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7924 7925 // Null out the abis so that they can be recalculated. 7926 pkg.applicationInfo.primaryCpuAbi = null; 7927 pkg.applicationInfo.secondaryCpuAbi = null; 7928 if (isMultiArch(pkg.applicationInfo)) { 7929 // Warn if we've set an abiOverride for multi-lib packages.. 7930 // By definition, we need to copy both 32 and 64 bit libraries for 7931 // such packages. 7932 if (pkg.cpuAbiOverride != null 7933 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7934 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7935 } 7936 7937 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7938 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7939 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7940 if (extractLibs) { 7941 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7942 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7943 useIsaSpecificSubdirs); 7944 } else { 7945 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7946 } 7947 } 7948 7949 maybeThrowExceptionForMultiArchCopy( 7950 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7951 7952 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7953 if (extractLibs) { 7954 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7955 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7956 useIsaSpecificSubdirs); 7957 } else { 7958 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7959 } 7960 } 7961 7962 maybeThrowExceptionForMultiArchCopy( 7963 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7964 7965 if (abi64 >= 0) { 7966 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7967 } 7968 7969 if (abi32 >= 0) { 7970 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7971 if (abi64 >= 0) { 7972 pkg.applicationInfo.secondaryCpuAbi = abi; 7973 } else { 7974 pkg.applicationInfo.primaryCpuAbi = abi; 7975 } 7976 } 7977 } else { 7978 String[] abiList = (cpuAbiOverride != null) ? 7979 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7980 7981 // Enable gross and lame hacks for apps that are built with old 7982 // SDK tools. We must scan their APKs for renderscript bitcode and 7983 // not launch them if it's present. Don't bother checking on devices 7984 // that don't have 64 bit support. 7985 boolean needsRenderScriptOverride = false; 7986 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7987 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7988 abiList = Build.SUPPORTED_32_BIT_ABIS; 7989 needsRenderScriptOverride = true; 7990 } 7991 7992 final int copyRet; 7993 if (extractLibs) { 7994 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7995 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7996 } else { 7997 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7998 } 7999 8000 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8001 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8002 "Error unpackaging native libs for app, errorCode=" + copyRet); 8003 } 8004 8005 if (copyRet >= 0) { 8006 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8007 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8008 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8009 } else if (needsRenderScriptOverride) { 8010 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8011 } 8012 } 8013 } catch (IOException ioe) { 8014 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8015 } finally { 8016 IoUtils.closeQuietly(handle); 8017 } 8018 8019 // Now that we've calculated the ABIs and determined if it's an internal app, 8020 // we will go ahead and populate the nativeLibraryPath. 8021 setNativeLibraryPaths(pkg); 8022 } 8023 8024 /** 8025 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8026 * i.e, so that all packages can be run inside a single process if required. 8027 * 8028 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8029 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8030 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8031 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8032 * updating a package that belongs to a shared user. 8033 * 8034 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8035 * adds unnecessary complexity. 8036 */ 8037 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8038 PackageParser.Package scannedPackage, boolean bootComplete) { 8039 String requiredInstructionSet = null; 8040 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8041 requiredInstructionSet = VMRuntime.getInstructionSet( 8042 scannedPackage.applicationInfo.primaryCpuAbi); 8043 } 8044 8045 PackageSetting requirer = null; 8046 for (PackageSetting ps : packagesForUser) { 8047 // If packagesForUser contains scannedPackage, we skip it. This will happen 8048 // when scannedPackage is an update of an existing package. Without this check, 8049 // we will never be able to change the ABI of any package belonging to a shared 8050 // user, even if it's compatible with other packages. 8051 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8052 if (ps.primaryCpuAbiString == null) { 8053 continue; 8054 } 8055 8056 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8057 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8058 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8059 // this but there's not much we can do. 8060 String errorMessage = "Instruction set mismatch, " 8061 + ((requirer == null) ? "[caller]" : requirer) 8062 + " requires " + requiredInstructionSet + " whereas " + ps 8063 + " requires " + instructionSet; 8064 Slog.w(TAG, errorMessage); 8065 } 8066 8067 if (requiredInstructionSet == null) { 8068 requiredInstructionSet = instructionSet; 8069 requirer = ps; 8070 } 8071 } 8072 } 8073 8074 if (requiredInstructionSet != null) { 8075 String adjustedAbi; 8076 if (requirer != null) { 8077 // requirer != null implies that either scannedPackage was null or that scannedPackage 8078 // did not require an ABI, in which case we have to adjust scannedPackage to match 8079 // the ABI of the set (which is the same as requirer's ABI) 8080 adjustedAbi = requirer.primaryCpuAbiString; 8081 if (scannedPackage != null) { 8082 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8083 } 8084 } else { 8085 // requirer == null implies that we're updating all ABIs in the set to 8086 // match scannedPackage. 8087 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8088 } 8089 8090 for (PackageSetting ps : packagesForUser) { 8091 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8092 if (ps.primaryCpuAbiString != null) { 8093 continue; 8094 } 8095 8096 ps.primaryCpuAbiString = adjustedAbi; 8097 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8098 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8099 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8100 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8101 + " (requirer=" 8102 + (requirer == null ? "null" : requirer.pkg.packageName) 8103 + ", scannedPackage=" 8104 + (scannedPackage != null ? scannedPackage.packageName : "null") 8105 + ")"); 8106 try { 8107 mInstaller.rmdex(ps.codePathString, 8108 getDexCodeInstructionSet(getPreferredInstructionSet())); 8109 } catch (InstallerException ignored) { 8110 } 8111 } 8112 } 8113 } 8114 } 8115 } 8116 8117 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8118 synchronized (mPackages) { 8119 mResolverReplaced = true; 8120 // Set up information for custom user intent resolution activity. 8121 mResolveActivity.applicationInfo = pkg.applicationInfo; 8122 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8123 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8124 mResolveActivity.processName = pkg.applicationInfo.packageName; 8125 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8126 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8127 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8128 mResolveActivity.theme = 0; 8129 mResolveActivity.exported = true; 8130 mResolveActivity.enabled = true; 8131 mResolveInfo.activityInfo = mResolveActivity; 8132 mResolveInfo.priority = 0; 8133 mResolveInfo.preferredOrder = 0; 8134 mResolveInfo.match = 0; 8135 mResolveComponentName = mCustomResolverComponentName; 8136 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8137 mResolveComponentName); 8138 } 8139 } 8140 8141 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8142 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8143 8144 // Set up information for ephemeral installer activity 8145 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8146 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8147 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8148 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8149 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8150 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8151 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8152 mEphemeralInstallerActivity.theme = 0; 8153 mEphemeralInstallerActivity.exported = true; 8154 mEphemeralInstallerActivity.enabled = true; 8155 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8156 mEphemeralInstallerInfo.priority = 0; 8157 mEphemeralInstallerInfo.preferredOrder = 0; 8158 mEphemeralInstallerInfo.match = 0; 8159 8160 if (DEBUG_EPHEMERAL) { 8161 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8162 } 8163 } 8164 8165 private static String calculateBundledApkRoot(final String codePathString) { 8166 final File codePath = new File(codePathString); 8167 final File codeRoot; 8168 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8169 codeRoot = Environment.getRootDirectory(); 8170 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8171 codeRoot = Environment.getOemDirectory(); 8172 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8173 codeRoot = Environment.getVendorDirectory(); 8174 } else { 8175 // Unrecognized code path; take its top real segment as the apk root: 8176 // e.g. /something/app/blah.apk => /something 8177 try { 8178 File f = codePath.getCanonicalFile(); 8179 File parent = f.getParentFile(); // non-null because codePath is a file 8180 File tmp; 8181 while ((tmp = parent.getParentFile()) != null) { 8182 f = parent; 8183 parent = tmp; 8184 } 8185 codeRoot = f; 8186 Slog.w(TAG, "Unrecognized code path " 8187 + codePath + " - using " + codeRoot); 8188 } catch (IOException e) { 8189 // Can't canonicalize the code path -- shenanigans? 8190 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8191 return Environment.getRootDirectory().getPath(); 8192 } 8193 } 8194 return codeRoot.getPath(); 8195 } 8196 8197 /** 8198 * Derive and set the location of native libraries for the given package, 8199 * which varies depending on where and how the package was installed. 8200 */ 8201 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8202 final ApplicationInfo info = pkg.applicationInfo; 8203 final String codePath = pkg.codePath; 8204 final File codeFile = new File(codePath); 8205 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8206 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8207 8208 info.nativeLibraryRootDir = null; 8209 info.nativeLibraryRootRequiresIsa = false; 8210 info.nativeLibraryDir = null; 8211 info.secondaryNativeLibraryDir = null; 8212 8213 if (isApkFile(codeFile)) { 8214 // Monolithic install 8215 if (bundledApp) { 8216 // If "/system/lib64/apkname" exists, assume that is the per-package 8217 // native library directory to use; otherwise use "/system/lib/apkname". 8218 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8219 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8220 getPrimaryInstructionSet(info)); 8221 8222 // This is a bundled system app so choose the path based on the ABI. 8223 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8224 // is just the default path. 8225 final String apkName = deriveCodePathName(codePath); 8226 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8227 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8228 apkName).getAbsolutePath(); 8229 8230 if (info.secondaryCpuAbi != null) { 8231 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8232 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8233 secondaryLibDir, apkName).getAbsolutePath(); 8234 } 8235 } else if (asecApp) { 8236 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8237 .getAbsolutePath(); 8238 } else { 8239 final String apkName = deriveCodePathName(codePath); 8240 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8241 .getAbsolutePath(); 8242 } 8243 8244 info.nativeLibraryRootRequiresIsa = false; 8245 info.nativeLibraryDir = info.nativeLibraryRootDir; 8246 } else { 8247 // Cluster install 8248 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8249 info.nativeLibraryRootRequiresIsa = true; 8250 8251 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8252 getPrimaryInstructionSet(info)).getAbsolutePath(); 8253 8254 if (info.secondaryCpuAbi != null) { 8255 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8256 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8257 } 8258 } 8259 } 8260 8261 /** 8262 * Calculate the abis and roots for a bundled app. These can uniquely 8263 * be determined from the contents of the system partition, i.e whether 8264 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8265 * of this information, and instead assume that the system was built 8266 * sensibly. 8267 */ 8268 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8269 PackageSetting pkgSetting) { 8270 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8271 8272 // If "/system/lib64/apkname" exists, assume that is the per-package 8273 // native library directory to use; otherwise use "/system/lib/apkname". 8274 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8275 setBundledAppAbi(pkg, apkRoot, apkName); 8276 // pkgSetting might be null during rescan following uninstall of updates 8277 // to a bundled app, so accommodate that possibility. The settings in 8278 // that case will be established later from the parsed package. 8279 // 8280 // If the settings aren't null, sync them up with what we've just derived. 8281 // note that apkRoot isn't stored in the package settings. 8282 if (pkgSetting != null) { 8283 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8284 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8285 } 8286 } 8287 8288 /** 8289 * Deduces the ABI of a bundled app and sets the relevant fields on the 8290 * parsed pkg object. 8291 * 8292 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8293 * under which system libraries are installed. 8294 * @param apkName the name of the installed package. 8295 */ 8296 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8297 final File codeFile = new File(pkg.codePath); 8298 8299 final boolean has64BitLibs; 8300 final boolean has32BitLibs; 8301 if (isApkFile(codeFile)) { 8302 // Monolithic install 8303 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8304 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8305 } else { 8306 // Cluster install 8307 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8308 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8309 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8310 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8311 has64BitLibs = (new File(rootDir, isa)).exists(); 8312 } else { 8313 has64BitLibs = false; 8314 } 8315 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8316 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8317 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8318 has32BitLibs = (new File(rootDir, isa)).exists(); 8319 } else { 8320 has32BitLibs = false; 8321 } 8322 } 8323 8324 if (has64BitLibs && !has32BitLibs) { 8325 // The package has 64 bit libs, but not 32 bit libs. Its primary 8326 // ABI should be 64 bit. We can safely assume here that the bundled 8327 // native libraries correspond to the most preferred ABI in the list. 8328 8329 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8330 pkg.applicationInfo.secondaryCpuAbi = null; 8331 } else if (has32BitLibs && !has64BitLibs) { 8332 // The package has 32 bit libs but not 64 bit libs. Its primary 8333 // ABI should be 32 bit. 8334 8335 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8336 pkg.applicationInfo.secondaryCpuAbi = null; 8337 } else if (has32BitLibs && has64BitLibs) { 8338 // The application has both 64 and 32 bit bundled libraries. We check 8339 // here that the app declares multiArch support, and warn if it doesn't. 8340 // 8341 // We will be lenient here and record both ABIs. The primary will be the 8342 // ABI that's higher on the list, i.e, a device that's configured to prefer 8343 // 64 bit apps will see a 64 bit primary ABI, 8344 8345 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8346 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 8347 } 8348 8349 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8350 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8351 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8352 } else { 8353 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8354 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8355 } 8356 } else { 8357 pkg.applicationInfo.primaryCpuAbi = null; 8358 pkg.applicationInfo.secondaryCpuAbi = null; 8359 } 8360 } 8361 8362 private void killApplication(String pkgName, int appId, String reason) { 8363 // Request the ActivityManager to kill the process(only for existing packages) 8364 // so that we do not end up in a confused state while the user is still using the older 8365 // version of the application while the new one gets installed. 8366 IActivityManager am = ActivityManagerNative.getDefault(); 8367 if (am != null) { 8368 try { 8369 am.killApplicationWithAppId(pkgName, appId, reason); 8370 } catch (RemoteException e) { 8371 } 8372 } 8373 } 8374 8375 void removePackageLI(PackageSetting ps, boolean chatty) { 8376 if (DEBUG_INSTALL) { 8377 if (chatty) 8378 Log.d(TAG, "Removing package " + ps.name); 8379 } 8380 8381 // writer 8382 synchronized (mPackages) { 8383 mPackages.remove(ps.name); 8384 final PackageParser.Package pkg = ps.pkg; 8385 if (pkg != null) { 8386 cleanPackageDataStructuresLILPw(pkg, chatty); 8387 } 8388 } 8389 } 8390 8391 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8392 if (DEBUG_INSTALL) { 8393 if (chatty) 8394 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8395 } 8396 8397 // writer 8398 synchronized (mPackages) { 8399 mPackages.remove(pkg.applicationInfo.packageName); 8400 cleanPackageDataStructuresLILPw(pkg, chatty); 8401 } 8402 } 8403 8404 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8405 int N = pkg.providers.size(); 8406 StringBuilder r = null; 8407 int i; 8408 for (i=0; i<N; i++) { 8409 PackageParser.Provider p = pkg.providers.get(i); 8410 mProviders.removeProvider(p); 8411 if (p.info.authority == null) { 8412 8413 /* There was another ContentProvider with this authority when 8414 * this app was installed so this authority is null, 8415 * Ignore it as we don't have to unregister the provider. 8416 */ 8417 continue; 8418 } 8419 String names[] = p.info.authority.split(";"); 8420 for (int j = 0; j < names.length; j++) { 8421 if (mProvidersByAuthority.get(names[j]) == p) { 8422 mProvidersByAuthority.remove(names[j]); 8423 if (DEBUG_REMOVE) { 8424 if (chatty) 8425 Log.d(TAG, "Unregistered content provider: " + names[j] 8426 + ", className = " + p.info.name + ", isSyncable = " 8427 + p.info.isSyncable); 8428 } 8429 } 8430 } 8431 if (DEBUG_REMOVE && chatty) { 8432 if (r == null) { 8433 r = new StringBuilder(256); 8434 } else { 8435 r.append(' '); 8436 } 8437 r.append(p.info.name); 8438 } 8439 } 8440 if (r != null) { 8441 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8442 } 8443 8444 N = pkg.services.size(); 8445 r = null; 8446 for (i=0; i<N; i++) { 8447 PackageParser.Service s = pkg.services.get(i); 8448 mServices.removeService(s); 8449 if (chatty) { 8450 if (r == null) { 8451 r = new StringBuilder(256); 8452 } else { 8453 r.append(' '); 8454 } 8455 r.append(s.info.name); 8456 } 8457 } 8458 if (r != null) { 8459 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8460 } 8461 8462 N = pkg.receivers.size(); 8463 r = null; 8464 for (i=0; i<N; i++) { 8465 PackageParser.Activity a = pkg.receivers.get(i); 8466 mReceivers.removeActivity(a, "receiver"); 8467 if (DEBUG_REMOVE && chatty) { 8468 if (r == null) { 8469 r = new StringBuilder(256); 8470 } else { 8471 r.append(' '); 8472 } 8473 r.append(a.info.name); 8474 } 8475 } 8476 if (r != null) { 8477 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8478 } 8479 8480 N = pkg.activities.size(); 8481 r = null; 8482 for (i=0; i<N; i++) { 8483 PackageParser.Activity a = pkg.activities.get(i); 8484 mActivities.removeActivity(a, "activity"); 8485 if (DEBUG_REMOVE && chatty) { 8486 if (r == null) { 8487 r = new StringBuilder(256); 8488 } else { 8489 r.append(' '); 8490 } 8491 r.append(a.info.name); 8492 } 8493 } 8494 if (r != null) { 8495 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8496 } 8497 8498 N = pkg.permissions.size(); 8499 r = null; 8500 for (i=0; i<N; i++) { 8501 PackageParser.Permission p = pkg.permissions.get(i); 8502 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8503 if (bp == null) { 8504 bp = mSettings.mPermissionTrees.get(p.info.name); 8505 } 8506 if (bp != null && bp.perm == p) { 8507 bp.perm = null; 8508 if (DEBUG_REMOVE && chatty) { 8509 if (r == null) { 8510 r = new StringBuilder(256); 8511 } else { 8512 r.append(' '); 8513 } 8514 r.append(p.info.name); 8515 } 8516 } 8517 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8518 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 8519 if (appOpPkgs != null) { 8520 appOpPkgs.remove(pkg.packageName); 8521 } 8522 } 8523 } 8524 if (r != null) { 8525 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8526 } 8527 8528 N = pkg.requestedPermissions.size(); 8529 r = null; 8530 for (i=0; i<N; i++) { 8531 String perm = pkg.requestedPermissions.get(i); 8532 BasePermission bp = mSettings.mPermissions.get(perm); 8533 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8534 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 8535 if (appOpPkgs != null) { 8536 appOpPkgs.remove(pkg.packageName); 8537 if (appOpPkgs.isEmpty()) { 8538 mAppOpPermissionPackages.remove(perm); 8539 } 8540 } 8541 } 8542 } 8543 if (r != null) { 8544 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8545 } 8546 8547 N = pkg.instrumentation.size(); 8548 r = null; 8549 for (i=0; i<N; i++) { 8550 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8551 mInstrumentation.remove(a.getComponentName()); 8552 if (DEBUG_REMOVE && chatty) { 8553 if (r == null) { 8554 r = new StringBuilder(256); 8555 } else { 8556 r.append(' '); 8557 } 8558 r.append(a.info.name); 8559 } 8560 } 8561 if (r != null) { 8562 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8563 } 8564 8565 r = null; 8566 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8567 // Only system apps can hold shared libraries. 8568 if (pkg.libraryNames != null) { 8569 for (i=0; i<pkg.libraryNames.size(); i++) { 8570 String name = pkg.libraryNames.get(i); 8571 SharedLibraryEntry cur = mSharedLibraries.get(name); 8572 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8573 mSharedLibraries.remove(name); 8574 if (DEBUG_REMOVE && chatty) { 8575 if (r == null) { 8576 r = new StringBuilder(256); 8577 } else { 8578 r.append(' '); 8579 } 8580 r.append(name); 8581 } 8582 } 8583 } 8584 } 8585 } 8586 if (r != null) { 8587 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8588 } 8589 } 8590 8591 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8592 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8593 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8594 return true; 8595 } 8596 } 8597 return false; 8598 } 8599 8600 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8601 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8602 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8603 8604 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 8605 int flags) { 8606 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 8607 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 8608 } 8609 8610 private void updatePermissionsLPw(String changingPkg, 8611 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 8612 // Make sure there are no dangling permission trees. 8613 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8614 while (it.hasNext()) { 8615 final BasePermission bp = it.next(); 8616 if (bp.packageSetting == null) { 8617 // We may not yet have parsed the package, so just see if 8618 // we still know about its settings. 8619 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8620 } 8621 if (bp.packageSetting == null) { 8622 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8623 + " from package " + bp.sourcePackage); 8624 it.remove(); 8625 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8626 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8627 Slog.i(TAG, "Removing old permission tree: " + bp.name 8628 + " from package " + bp.sourcePackage); 8629 flags |= UPDATE_PERMISSIONS_ALL; 8630 it.remove(); 8631 } 8632 } 8633 } 8634 8635 // Make sure all dynamic permissions have been assigned to a package, 8636 // and make sure there are no dangling permissions. 8637 it = mSettings.mPermissions.values().iterator(); 8638 while (it.hasNext()) { 8639 final BasePermission bp = it.next(); 8640 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8641 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8642 + bp.name + " pkg=" + bp.sourcePackage 8643 + " info=" + bp.pendingInfo); 8644 if (bp.packageSetting == null && bp.pendingInfo != null) { 8645 final BasePermission tree = findPermissionTreeLP(bp.name); 8646 if (tree != null && tree.perm != null) { 8647 bp.packageSetting = tree.packageSetting; 8648 bp.perm = new PackageParser.Permission(tree.perm.owner, 8649 new PermissionInfo(bp.pendingInfo)); 8650 bp.perm.info.packageName = tree.perm.info.packageName; 8651 bp.perm.info.name = bp.name; 8652 bp.uid = tree.uid; 8653 } 8654 } 8655 } 8656 if (bp.packageSetting == null) { 8657 // We may not yet have parsed the package, so just see if 8658 // we still know about its settings. 8659 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8660 } 8661 if (bp.packageSetting == null) { 8662 Slog.w(TAG, "Removing dangling permission: " + bp.name 8663 + " from package " + bp.sourcePackage); 8664 it.remove(); 8665 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8666 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8667 Slog.i(TAG, "Removing old permission: " + bp.name 8668 + " from package " + bp.sourcePackage); 8669 flags |= UPDATE_PERMISSIONS_ALL; 8670 it.remove(); 8671 } 8672 } 8673 } 8674 8675 // Now update the permissions for all packages, in particular 8676 // replace the granted permissions of the system packages. 8677 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8678 for (PackageParser.Package pkg : mPackages.values()) { 8679 if (pkg != pkgInfo) { 8680 // Only replace for packages on requested volume 8681 final String volumeUuid = getVolumeUuidForPackage(pkg); 8682 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 8683 && Objects.equals(replaceVolumeUuid, volumeUuid); 8684 grantPermissionsLPw(pkg, replace, changingPkg); 8685 } 8686 } 8687 } 8688 8689 if (pkgInfo != null) { 8690 // Only replace for packages on requested volume 8691 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 8692 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 8693 && Objects.equals(replaceVolumeUuid, volumeUuid); 8694 grantPermissionsLPw(pkgInfo, replace, changingPkg); 8695 } 8696 } 8697 8698 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8699 String packageOfInterest) { 8700 // IMPORTANT: There are two types of permissions: install and runtime. 8701 // Install time permissions are granted when the app is installed to 8702 // all device users and users added in the future. Runtime permissions 8703 // are granted at runtime explicitly to specific users. Normal and signature 8704 // protected permissions are install time permissions. Dangerous permissions 8705 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8706 // otherwise they are runtime permissions. This function does not manage 8707 // runtime permissions except for the case an app targeting Lollipop MR1 8708 // being upgraded to target a newer SDK, in which case dangerous permissions 8709 // are transformed from install time to runtime ones. 8710 8711 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8712 if (ps == null) { 8713 return; 8714 } 8715 8716 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 8717 8718 PermissionsState permissionsState = ps.getPermissionsState(); 8719 PermissionsState origPermissions = permissionsState; 8720 8721 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8722 8723 boolean runtimePermissionsRevoked = false; 8724 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8725 8726 boolean changedInstallPermission = false; 8727 8728 if (replace) { 8729 ps.installPermissionsFixed = false; 8730 if (!ps.isSharedUser()) { 8731 origPermissions = new PermissionsState(permissionsState); 8732 permissionsState.reset(); 8733 } else { 8734 // We need to know only about runtime permission changes since the 8735 // calling code always writes the install permissions state but 8736 // the runtime ones are written only if changed. The only cases of 8737 // changed runtime permissions here are promotion of an install to 8738 // runtime and revocation of a runtime from a shared user. 8739 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 8740 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 8741 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 8742 runtimePermissionsRevoked = true; 8743 } 8744 } 8745 } 8746 8747 permissionsState.setGlobalGids(mGlobalGids); 8748 8749 final int N = pkg.requestedPermissions.size(); 8750 for (int i=0; i<N; i++) { 8751 final String name = pkg.requestedPermissions.get(i); 8752 final BasePermission bp = mSettings.mPermissions.get(name); 8753 8754 if (DEBUG_INSTALL) { 8755 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8756 } 8757 8758 if (bp == null || bp.packageSetting == null) { 8759 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8760 Slog.w(TAG, "Unknown permission " + name 8761 + " in package " + pkg.packageName); 8762 } 8763 continue; 8764 } 8765 8766 final String perm = bp.name; 8767 boolean allowedSig = false; 8768 int grant = GRANT_DENIED; 8769 8770 // Keep track of app op permissions. 8771 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8772 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8773 if (pkgs == null) { 8774 pkgs = new ArraySet<>(); 8775 mAppOpPermissionPackages.put(bp.name, pkgs); 8776 } 8777 pkgs.add(pkg.packageName); 8778 } 8779 8780 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8781 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 8782 >= Build.VERSION_CODES.M; 8783 switch (level) { 8784 case PermissionInfo.PROTECTION_NORMAL: { 8785 // For all apps normal permissions are install time ones. 8786 grant = GRANT_INSTALL; 8787 } break; 8788 8789 case PermissionInfo.PROTECTION_DANGEROUS: { 8790 // If a permission review is required for legacy apps we represent 8791 // their permissions as always granted runtime ones since we need 8792 // to keep the review required permission flag per user while an 8793 // install permission's state is shared across all users. 8794 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 8795 // For legacy apps dangerous permissions are install time ones. 8796 grant = GRANT_INSTALL; 8797 } else if (origPermissions.hasInstallPermission(bp.name)) { 8798 // For legacy apps that became modern, install becomes runtime. 8799 grant = GRANT_UPGRADE; 8800 } else if (mPromoteSystemApps 8801 && isSystemApp(ps) 8802 && mExistingSystemPackages.contains(ps.name)) { 8803 // For legacy system apps, install becomes runtime. 8804 // We cannot check hasInstallPermission() for system apps since those 8805 // permissions were granted implicitly and not persisted pre-M. 8806 grant = GRANT_UPGRADE; 8807 } else { 8808 // For modern apps keep runtime permissions unchanged. 8809 grant = GRANT_RUNTIME; 8810 } 8811 } break; 8812 8813 case PermissionInfo.PROTECTION_SIGNATURE: { 8814 // For all apps signature permissions are install time ones. 8815 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8816 if (allowedSig) { 8817 grant = GRANT_INSTALL; 8818 } 8819 } break; 8820 } 8821 8822 if (DEBUG_INSTALL) { 8823 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8824 } 8825 8826 if (grant != GRANT_DENIED) { 8827 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8828 // If this is an existing, non-system package, then 8829 // we can't add any new permissions to it. 8830 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8831 // Except... if this is a permission that was added 8832 // to the platform (note: need to only do this when 8833 // updating the platform). 8834 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8835 grant = GRANT_DENIED; 8836 } 8837 } 8838 } 8839 8840 switch (grant) { 8841 case GRANT_INSTALL: { 8842 // Revoke this as runtime permission to handle the case of 8843 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 8844 for (int userId : UserManagerService.getInstance().getUserIds()) { 8845 if (origPermissions.getRuntimePermissionState( 8846 bp.name, userId) != null) { 8847 // Revoke the runtime permission and clear the flags. 8848 origPermissions.revokeRuntimePermission(bp, userId); 8849 origPermissions.updatePermissionFlags(bp, userId, 8850 PackageManager.MASK_PERMISSION_FLAGS, 0); 8851 // If we revoked a permission permission, we have to write. 8852 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8853 changedRuntimePermissionUserIds, userId); 8854 } 8855 } 8856 // Grant an install permission. 8857 if (permissionsState.grantInstallPermission(bp) != 8858 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8859 changedInstallPermission = true; 8860 } 8861 } break; 8862 8863 case GRANT_RUNTIME: { 8864 // Grant previously granted runtime permissions. 8865 for (int userId : UserManagerService.getInstance().getUserIds()) { 8866 PermissionState permissionState = origPermissions 8867 .getRuntimePermissionState(bp.name, userId); 8868 int flags = permissionState != null 8869 ? permissionState.getFlags() : 0; 8870 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8871 if (permissionsState.grantRuntimePermission(bp, userId) == 8872 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8873 // If we cannot put the permission as it was, we have to write. 8874 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8875 changedRuntimePermissionUserIds, userId); 8876 } 8877 // If the app supports runtime permissions no need for a review. 8878 if (Build.PERMISSIONS_REVIEW_REQUIRED 8879 && appSupportsRuntimePermissions 8880 && (flags & PackageManager 8881 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 8882 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 8883 // Since we changed the flags, we have to write. 8884 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8885 changedRuntimePermissionUserIds, userId); 8886 } 8887 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 8888 && !appSupportsRuntimePermissions) { 8889 // For legacy apps that need a permission review, every new 8890 // runtime permission is granted but it is pending a review. 8891 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 8892 permissionsState.grantRuntimePermission(bp, userId); 8893 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 8894 // We changed the permission and flags, hence have to write. 8895 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8896 changedRuntimePermissionUserIds, userId); 8897 } 8898 } 8899 // Propagate the permission flags. 8900 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8901 } 8902 } break; 8903 8904 case GRANT_UPGRADE: { 8905 // Grant runtime permissions for a previously held install permission. 8906 PermissionState permissionState = origPermissions 8907 .getInstallPermissionState(bp.name); 8908 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8909 8910 if (origPermissions.revokeInstallPermission(bp) 8911 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8912 // We will be transferring the permission flags, so clear them. 8913 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8914 PackageManager.MASK_PERMISSION_FLAGS, 0); 8915 changedInstallPermission = true; 8916 } 8917 8918 // If the permission is not to be promoted to runtime we ignore it and 8919 // also its other flags as they are not applicable to install permissions. 8920 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8921 for (int userId : currentUserIds) { 8922 if (permissionsState.grantRuntimePermission(bp, userId) != 8923 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8924 // Transfer the permission flags. 8925 permissionsState.updatePermissionFlags(bp, userId, 8926 flags, flags); 8927 // If we granted the permission, we have to write. 8928 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8929 changedRuntimePermissionUserIds, userId); 8930 } 8931 } 8932 } 8933 } break; 8934 8935 default: { 8936 if (packageOfInterest == null 8937 || packageOfInterest.equals(pkg.packageName)) { 8938 Slog.w(TAG, "Not granting permission " + perm 8939 + " to package " + pkg.packageName 8940 + " because it was previously installed without"); 8941 } 8942 } break; 8943 } 8944 } else { 8945 if (permissionsState.revokeInstallPermission(bp) != 8946 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8947 // Also drop the permission flags. 8948 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8949 PackageManager.MASK_PERMISSION_FLAGS, 0); 8950 changedInstallPermission = true; 8951 Slog.i(TAG, "Un-granting permission " + perm 8952 + " from package " + pkg.packageName 8953 + " (protectionLevel=" + bp.protectionLevel 8954 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8955 + ")"); 8956 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8957 // Don't print warning for app op permissions, since it is fine for them 8958 // not to be granted, there is a UI for the user to decide. 8959 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8960 Slog.w(TAG, "Not granting permission " + perm 8961 + " to package " + pkg.packageName 8962 + " (protectionLevel=" + bp.protectionLevel 8963 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8964 + ")"); 8965 } 8966 } 8967 } 8968 } 8969 8970 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8971 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8972 // This is the first that we have heard about this package, so the 8973 // permissions we have now selected are fixed until explicitly 8974 // changed. 8975 ps.installPermissionsFixed = true; 8976 } 8977 8978 // Persist the runtime permissions state for users with changes. If permissions 8979 // were revoked because no app in the shared user declares them we have to 8980 // write synchronously to avoid losing runtime permissions state. 8981 for (int userId : changedRuntimePermissionUserIds) { 8982 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 8983 } 8984 8985 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8986 } 8987 8988 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8989 boolean allowed = false; 8990 final int NP = PackageParser.NEW_PERMISSIONS.length; 8991 for (int ip=0; ip<NP; ip++) { 8992 final PackageParser.NewPermissionInfo npi 8993 = PackageParser.NEW_PERMISSIONS[ip]; 8994 if (npi.name.equals(perm) 8995 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8996 allowed = true; 8997 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8998 + pkg.packageName); 8999 break; 9000 } 9001 } 9002 return allowed; 9003 } 9004 9005 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9006 BasePermission bp, PermissionsState origPermissions) { 9007 boolean allowed; 9008 allowed = (compareSignatures( 9009 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9010 == PackageManager.SIGNATURE_MATCH) 9011 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9012 == PackageManager.SIGNATURE_MATCH); 9013 if (!allowed && (bp.protectionLevel 9014 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9015 if (isSystemApp(pkg)) { 9016 // For updated system applications, a system permission 9017 // is granted only if it had been defined by the original application. 9018 if (pkg.isUpdatedSystemApp()) { 9019 final PackageSetting sysPs = mSettings 9020 .getDisabledSystemPkgLPr(pkg.packageName); 9021 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 9022 // If the original was granted this permission, we take 9023 // that grant decision as read and propagate it to the 9024 // update. 9025 if (sysPs.isPrivileged()) { 9026 allowed = true; 9027 } 9028 } else { 9029 // The system apk may have been updated with an older 9030 // version of the one on the data partition, but which 9031 // granted a new system permission that it didn't have 9032 // before. In this case we do want to allow the app to 9033 // now get the new permission if the ancestral apk is 9034 // privileged to get it. 9035 if (sysPs.pkg != null && sysPs.isPrivileged()) { 9036 for (int j=0; 9037 j<sysPs.pkg.requestedPermissions.size(); j++) { 9038 if (perm.equals( 9039 sysPs.pkg.requestedPermissions.get(j))) { 9040 allowed = true; 9041 break; 9042 } 9043 } 9044 } 9045 } 9046 } else { 9047 allowed = isPrivilegedApp(pkg); 9048 } 9049 } 9050 } 9051 if (!allowed) { 9052 if (!allowed && (bp.protectionLevel 9053 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9054 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9055 // If this was a previously normal/dangerous permission that got moved 9056 // to a system permission as part of the runtime permission redesign, then 9057 // we still want to blindly grant it to old apps. 9058 allowed = true; 9059 } 9060 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9061 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9062 // If this permission is to be granted to the system installer and 9063 // this app is an installer, then it gets the permission. 9064 allowed = true; 9065 } 9066 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9067 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9068 // If this permission is to be granted to the system verifier and 9069 // this app is a verifier, then it gets the permission. 9070 allowed = true; 9071 } 9072 if (!allowed && (bp.protectionLevel 9073 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9074 && isSystemApp(pkg)) { 9075 // Any pre-installed system app is allowed to get this permission. 9076 allowed = true; 9077 } 9078 if (!allowed && (bp.protectionLevel 9079 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9080 // For development permissions, a development permission 9081 // is granted only if it was already granted. 9082 allowed = origPermissions.hasInstallPermission(perm); 9083 } 9084 } 9085 return allowed; 9086 } 9087 9088 final class ActivityIntentResolver 9089 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9090 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9091 boolean defaultOnly, int userId) { 9092 if (!sUserManager.exists(userId)) return null; 9093 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9094 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9095 } 9096 9097 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9098 int userId) { 9099 if (!sUserManager.exists(userId)) return null; 9100 mFlags = flags; 9101 return super.queryIntent(intent, resolvedType, 9102 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9103 } 9104 9105 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9106 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9107 if (!sUserManager.exists(userId)) return null; 9108 if (packageActivities == null) { 9109 return null; 9110 } 9111 mFlags = flags; 9112 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9113 final int N = packageActivities.size(); 9114 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9115 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9116 9117 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9118 for (int i = 0; i < N; ++i) { 9119 intentFilters = packageActivities.get(i).intents; 9120 if (intentFilters != null && intentFilters.size() > 0) { 9121 PackageParser.ActivityIntentInfo[] array = 9122 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9123 intentFilters.toArray(array); 9124 listCut.add(array); 9125 } 9126 } 9127 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9128 } 9129 9130 public final void addActivity(PackageParser.Activity a, String type) { 9131 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 9132 mActivities.put(a.getComponentName(), a); 9133 if (DEBUG_SHOW_INFO) 9134 Log.v( 9135 TAG, " " + type + " " + 9136 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 9137 if (DEBUG_SHOW_INFO) 9138 Log.v(TAG, " Class=" + a.info.name); 9139 final int NI = a.intents.size(); 9140 for (int j=0; j<NI; j++) { 9141 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9142 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 9143 intent.setPriority(0); 9144 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 9145 + a.className + " with priority > 0, forcing to 0"); 9146 } 9147 if (DEBUG_SHOW_INFO) { 9148 Log.v(TAG, " IntentFilter:"); 9149 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9150 } 9151 if (!intent.debugCheck()) { 9152 Log.w(TAG, "==> For Activity " + a.info.name); 9153 } 9154 addFilter(intent); 9155 } 9156 } 9157 9158 public final void removeActivity(PackageParser.Activity a, String type) { 9159 mActivities.remove(a.getComponentName()); 9160 if (DEBUG_SHOW_INFO) { 9161 Log.v(TAG, " " + type + " " 9162 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 9163 : a.info.name) + ":"); 9164 Log.v(TAG, " Class=" + a.info.name); 9165 } 9166 final int NI = a.intents.size(); 9167 for (int j=0; j<NI; j++) { 9168 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9169 if (DEBUG_SHOW_INFO) { 9170 Log.v(TAG, " IntentFilter:"); 9171 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9172 } 9173 removeFilter(intent); 9174 } 9175 } 9176 9177 @Override 9178 protected boolean allowFilterResult( 9179 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 9180 ActivityInfo filterAi = filter.activity.info; 9181 for (int i=dest.size()-1; i>=0; i--) { 9182 ActivityInfo destAi = dest.get(i).activityInfo; 9183 if (destAi.name == filterAi.name 9184 && destAi.packageName == filterAi.packageName) { 9185 return false; 9186 } 9187 } 9188 return true; 9189 } 9190 9191 @Override 9192 protected ActivityIntentInfo[] newArray(int size) { 9193 return new ActivityIntentInfo[size]; 9194 } 9195 9196 @Override 9197 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 9198 if (!sUserManager.exists(userId)) return true; 9199 PackageParser.Package p = filter.activity.owner; 9200 if (p != null) { 9201 PackageSetting ps = (PackageSetting)p.mExtras; 9202 if (ps != null) { 9203 // System apps are never considered stopped for purposes of 9204 // filtering, because there may be no way for the user to 9205 // actually re-launch them. 9206 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 9207 && ps.getStopped(userId); 9208 } 9209 } 9210 return false; 9211 } 9212 9213 @Override 9214 protected boolean isPackageForFilter(String packageName, 9215 PackageParser.ActivityIntentInfo info) { 9216 return packageName.equals(info.activity.owner.packageName); 9217 } 9218 9219 @Override 9220 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 9221 int match, int userId) { 9222 if (!sUserManager.exists(userId)) return null; 9223 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 9224 return null; 9225 } 9226 final PackageParser.Activity activity = info.activity; 9227 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 9228 if (ps == null) { 9229 return null; 9230 } 9231 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 9232 ps.readUserState(userId), userId); 9233 if (ai == null) { 9234 return null; 9235 } 9236 final ResolveInfo res = new ResolveInfo(); 9237 res.activityInfo = ai; 9238 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9239 res.filter = info; 9240 } 9241 if (info != null) { 9242 res.handleAllWebDataURI = info.handleAllWebDataURI(); 9243 } 9244 res.priority = info.getPriority(); 9245 res.preferredOrder = activity.owner.mPreferredOrder; 9246 //System.out.println("Result: " + res.activityInfo.className + 9247 // " = " + res.priority); 9248 res.match = match; 9249 res.isDefault = info.hasDefault; 9250 res.labelRes = info.labelRes; 9251 res.nonLocalizedLabel = info.nonLocalizedLabel; 9252 if (userNeedsBadging(userId)) { 9253 res.noResourceId = true; 9254 } else { 9255 res.icon = info.icon; 9256 } 9257 res.iconResourceId = info.icon; 9258 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9259 return res; 9260 } 9261 9262 @Override 9263 protected void sortResults(List<ResolveInfo> results) { 9264 Collections.sort(results, mResolvePrioritySorter); 9265 } 9266 9267 @Override 9268 protected void dumpFilter(PrintWriter out, String prefix, 9269 PackageParser.ActivityIntentInfo filter) { 9270 out.print(prefix); out.print( 9271 Integer.toHexString(System.identityHashCode(filter.activity))); 9272 out.print(' '); 9273 filter.activity.printComponentShortName(out); 9274 out.print(" filter "); 9275 out.println(Integer.toHexString(System.identityHashCode(filter))); 9276 } 9277 9278 @Override 9279 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9280 return filter.activity; 9281 } 9282 9283 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9284 PackageParser.Activity activity = (PackageParser.Activity)label; 9285 out.print(prefix); out.print( 9286 Integer.toHexString(System.identityHashCode(activity))); 9287 out.print(' '); 9288 activity.printComponentShortName(out); 9289 if (count > 1) { 9290 out.print(" ("); out.print(count); out.print(" filters)"); 9291 } 9292 out.println(); 9293 } 9294 9295// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9296// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9297// final List<ResolveInfo> retList = Lists.newArrayList(); 9298// while (i.hasNext()) { 9299// final ResolveInfo resolveInfo = i.next(); 9300// if (isEnabledLP(resolveInfo.activityInfo)) { 9301// retList.add(resolveInfo); 9302// } 9303// } 9304// return retList; 9305// } 9306 9307 // Keys are String (activity class name), values are Activity. 9308 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9309 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9310 private int mFlags; 9311 } 9312 9313 private final class ServiceIntentResolver 9314 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9315 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9316 boolean defaultOnly, int userId) { 9317 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9318 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9319 } 9320 9321 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9322 int userId) { 9323 if (!sUserManager.exists(userId)) return null; 9324 mFlags = flags; 9325 return super.queryIntent(intent, resolvedType, 9326 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9327 } 9328 9329 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9330 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9331 if (!sUserManager.exists(userId)) return null; 9332 if (packageServices == null) { 9333 return null; 9334 } 9335 mFlags = flags; 9336 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9337 final int N = packageServices.size(); 9338 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9339 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9340 9341 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9342 for (int i = 0; i < N; ++i) { 9343 intentFilters = packageServices.get(i).intents; 9344 if (intentFilters != null && intentFilters.size() > 0) { 9345 PackageParser.ServiceIntentInfo[] array = 9346 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9347 intentFilters.toArray(array); 9348 listCut.add(array); 9349 } 9350 } 9351 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9352 } 9353 9354 public final void addService(PackageParser.Service s) { 9355 mServices.put(s.getComponentName(), s); 9356 if (DEBUG_SHOW_INFO) { 9357 Log.v(TAG, " " 9358 + (s.info.nonLocalizedLabel != null 9359 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9360 Log.v(TAG, " Class=" + s.info.name); 9361 } 9362 final int NI = s.intents.size(); 9363 int j; 9364 for (j=0; j<NI; j++) { 9365 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9366 if (DEBUG_SHOW_INFO) { 9367 Log.v(TAG, " IntentFilter:"); 9368 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9369 } 9370 if (!intent.debugCheck()) { 9371 Log.w(TAG, "==> For Service " + s.info.name); 9372 } 9373 addFilter(intent); 9374 } 9375 } 9376 9377 public final void removeService(PackageParser.Service s) { 9378 mServices.remove(s.getComponentName()); 9379 if (DEBUG_SHOW_INFO) { 9380 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9381 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9382 Log.v(TAG, " Class=" + s.info.name); 9383 } 9384 final int NI = s.intents.size(); 9385 int j; 9386 for (j=0; j<NI; j++) { 9387 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9388 if (DEBUG_SHOW_INFO) { 9389 Log.v(TAG, " IntentFilter:"); 9390 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9391 } 9392 removeFilter(intent); 9393 } 9394 } 9395 9396 @Override 9397 protected boolean allowFilterResult( 9398 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9399 ServiceInfo filterSi = filter.service.info; 9400 for (int i=dest.size()-1; i>=0; i--) { 9401 ServiceInfo destAi = dest.get(i).serviceInfo; 9402 if (destAi.name == filterSi.name 9403 && destAi.packageName == filterSi.packageName) { 9404 return false; 9405 } 9406 } 9407 return true; 9408 } 9409 9410 @Override 9411 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9412 return new PackageParser.ServiceIntentInfo[size]; 9413 } 9414 9415 @Override 9416 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9417 if (!sUserManager.exists(userId)) return true; 9418 PackageParser.Package p = filter.service.owner; 9419 if (p != null) { 9420 PackageSetting ps = (PackageSetting)p.mExtras; 9421 if (ps != null) { 9422 // System apps are never considered stopped for purposes of 9423 // filtering, because there may be no way for the user to 9424 // actually re-launch them. 9425 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9426 && ps.getStopped(userId); 9427 } 9428 } 9429 return false; 9430 } 9431 9432 @Override 9433 protected boolean isPackageForFilter(String packageName, 9434 PackageParser.ServiceIntentInfo info) { 9435 return packageName.equals(info.service.owner.packageName); 9436 } 9437 9438 @Override 9439 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9440 int match, int userId) { 9441 if (!sUserManager.exists(userId)) return null; 9442 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9443 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 9444 return null; 9445 } 9446 final PackageParser.Service service = info.service; 9447 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9448 if (ps == null) { 9449 return null; 9450 } 9451 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9452 ps.readUserState(userId), userId); 9453 if (si == null) { 9454 return null; 9455 } 9456 final ResolveInfo res = new ResolveInfo(); 9457 res.serviceInfo = si; 9458 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9459 res.filter = filter; 9460 } 9461 res.priority = info.getPriority(); 9462 res.preferredOrder = service.owner.mPreferredOrder; 9463 res.match = match; 9464 res.isDefault = info.hasDefault; 9465 res.labelRes = info.labelRes; 9466 res.nonLocalizedLabel = info.nonLocalizedLabel; 9467 res.icon = info.icon; 9468 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9469 return res; 9470 } 9471 9472 @Override 9473 protected void sortResults(List<ResolveInfo> results) { 9474 Collections.sort(results, mResolvePrioritySorter); 9475 } 9476 9477 @Override 9478 protected void dumpFilter(PrintWriter out, String prefix, 9479 PackageParser.ServiceIntentInfo filter) { 9480 out.print(prefix); out.print( 9481 Integer.toHexString(System.identityHashCode(filter.service))); 9482 out.print(' '); 9483 filter.service.printComponentShortName(out); 9484 out.print(" filter "); 9485 out.println(Integer.toHexString(System.identityHashCode(filter))); 9486 } 9487 9488 @Override 9489 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9490 return filter.service; 9491 } 9492 9493 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9494 PackageParser.Service service = (PackageParser.Service)label; 9495 out.print(prefix); out.print( 9496 Integer.toHexString(System.identityHashCode(service))); 9497 out.print(' '); 9498 service.printComponentShortName(out); 9499 if (count > 1) { 9500 out.print(" ("); out.print(count); out.print(" filters)"); 9501 } 9502 out.println(); 9503 } 9504 9505// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9506// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9507// final List<ResolveInfo> retList = Lists.newArrayList(); 9508// while (i.hasNext()) { 9509// final ResolveInfo resolveInfo = (ResolveInfo) i; 9510// if (isEnabledLP(resolveInfo.serviceInfo)) { 9511// retList.add(resolveInfo); 9512// } 9513// } 9514// return retList; 9515// } 9516 9517 // Keys are String (activity class name), values are Activity. 9518 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9519 = new ArrayMap<ComponentName, PackageParser.Service>(); 9520 private int mFlags; 9521 }; 9522 9523 private final class ProviderIntentResolver 9524 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9525 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9526 boolean defaultOnly, int userId) { 9527 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9528 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9529 } 9530 9531 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9532 int userId) { 9533 if (!sUserManager.exists(userId)) 9534 return null; 9535 mFlags = flags; 9536 return super.queryIntent(intent, resolvedType, 9537 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9538 } 9539 9540 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9541 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9542 if (!sUserManager.exists(userId)) 9543 return null; 9544 if (packageProviders == null) { 9545 return null; 9546 } 9547 mFlags = flags; 9548 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9549 final int N = packageProviders.size(); 9550 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9551 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9552 9553 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9554 for (int i = 0; i < N; ++i) { 9555 intentFilters = packageProviders.get(i).intents; 9556 if (intentFilters != null && intentFilters.size() > 0) { 9557 PackageParser.ProviderIntentInfo[] array = 9558 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9559 intentFilters.toArray(array); 9560 listCut.add(array); 9561 } 9562 } 9563 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9564 } 9565 9566 public final void addProvider(PackageParser.Provider p) { 9567 if (mProviders.containsKey(p.getComponentName())) { 9568 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9569 return; 9570 } 9571 9572 mProviders.put(p.getComponentName(), p); 9573 if (DEBUG_SHOW_INFO) { 9574 Log.v(TAG, " " 9575 + (p.info.nonLocalizedLabel != null 9576 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9577 Log.v(TAG, " Class=" + p.info.name); 9578 } 9579 final int NI = p.intents.size(); 9580 int j; 9581 for (j = 0; j < NI; j++) { 9582 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9583 if (DEBUG_SHOW_INFO) { 9584 Log.v(TAG, " IntentFilter:"); 9585 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9586 } 9587 if (!intent.debugCheck()) { 9588 Log.w(TAG, "==> For Provider " + p.info.name); 9589 } 9590 addFilter(intent); 9591 } 9592 } 9593 9594 public final void removeProvider(PackageParser.Provider p) { 9595 mProviders.remove(p.getComponentName()); 9596 if (DEBUG_SHOW_INFO) { 9597 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9598 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9599 Log.v(TAG, " Class=" + p.info.name); 9600 } 9601 final int NI = p.intents.size(); 9602 int j; 9603 for (j = 0; j < NI; j++) { 9604 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9605 if (DEBUG_SHOW_INFO) { 9606 Log.v(TAG, " IntentFilter:"); 9607 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9608 } 9609 removeFilter(intent); 9610 } 9611 } 9612 9613 @Override 9614 protected boolean allowFilterResult( 9615 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9616 ProviderInfo filterPi = filter.provider.info; 9617 for (int i = dest.size() - 1; i >= 0; i--) { 9618 ProviderInfo destPi = dest.get(i).providerInfo; 9619 if (destPi.name == filterPi.name 9620 && destPi.packageName == filterPi.packageName) { 9621 return false; 9622 } 9623 } 9624 return true; 9625 } 9626 9627 @Override 9628 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9629 return new PackageParser.ProviderIntentInfo[size]; 9630 } 9631 9632 @Override 9633 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9634 if (!sUserManager.exists(userId)) 9635 return true; 9636 PackageParser.Package p = filter.provider.owner; 9637 if (p != null) { 9638 PackageSetting ps = (PackageSetting) p.mExtras; 9639 if (ps != null) { 9640 // System apps are never considered stopped for purposes of 9641 // filtering, because there may be no way for the user to 9642 // actually re-launch them. 9643 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9644 && ps.getStopped(userId); 9645 } 9646 } 9647 return false; 9648 } 9649 9650 @Override 9651 protected boolean isPackageForFilter(String packageName, 9652 PackageParser.ProviderIntentInfo info) { 9653 return packageName.equals(info.provider.owner.packageName); 9654 } 9655 9656 @Override 9657 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9658 int match, int userId) { 9659 if (!sUserManager.exists(userId)) 9660 return null; 9661 final PackageParser.ProviderIntentInfo info = filter; 9662 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 9663 return null; 9664 } 9665 final PackageParser.Provider provider = info.provider; 9666 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9667 if (ps == null) { 9668 return null; 9669 } 9670 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9671 ps.readUserState(userId), userId); 9672 if (pi == null) { 9673 return null; 9674 } 9675 final ResolveInfo res = new ResolveInfo(); 9676 res.providerInfo = pi; 9677 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9678 res.filter = filter; 9679 } 9680 res.priority = info.getPriority(); 9681 res.preferredOrder = provider.owner.mPreferredOrder; 9682 res.match = match; 9683 res.isDefault = info.hasDefault; 9684 res.labelRes = info.labelRes; 9685 res.nonLocalizedLabel = info.nonLocalizedLabel; 9686 res.icon = info.icon; 9687 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9688 return res; 9689 } 9690 9691 @Override 9692 protected void sortResults(List<ResolveInfo> results) { 9693 Collections.sort(results, mResolvePrioritySorter); 9694 } 9695 9696 @Override 9697 protected void dumpFilter(PrintWriter out, String prefix, 9698 PackageParser.ProviderIntentInfo filter) { 9699 out.print(prefix); 9700 out.print( 9701 Integer.toHexString(System.identityHashCode(filter.provider))); 9702 out.print(' '); 9703 filter.provider.printComponentShortName(out); 9704 out.print(" filter "); 9705 out.println(Integer.toHexString(System.identityHashCode(filter))); 9706 } 9707 9708 @Override 9709 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9710 return filter.provider; 9711 } 9712 9713 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9714 PackageParser.Provider provider = (PackageParser.Provider)label; 9715 out.print(prefix); out.print( 9716 Integer.toHexString(System.identityHashCode(provider))); 9717 out.print(' '); 9718 provider.printComponentShortName(out); 9719 if (count > 1) { 9720 out.print(" ("); out.print(count); out.print(" filters)"); 9721 } 9722 out.println(); 9723 } 9724 9725 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9726 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9727 private int mFlags; 9728 } 9729 9730 private static final class EphemeralIntentResolver 9731 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 9732 @Override 9733 protected EphemeralResolveIntentInfo[] newArray(int size) { 9734 return new EphemeralResolveIntentInfo[size]; 9735 } 9736 9737 @Override 9738 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 9739 return true; 9740 } 9741 9742 @Override 9743 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 9744 int userId) { 9745 if (!sUserManager.exists(userId)) { 9746 return null; 9747 } 9748 return info.getEphemeralResolveInfo(); 9749 } 9750 } 9751 9752 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9753 new Comparator<ResolveInfo>() { 9754 public int compare(ResolveInfo r1, ResolveInfo r2) { 9755 int v1 = r1.priority; 9756 int v2 = r2.priority; 9757 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9758 if (v1 != v2) { 9759 return (v1 > v2) ? -1 : 1; 9760 } 9761 v1 = r1.preferredOrder; 9762 v2 = r2.preferredOrder; 9763 if (v1 != v2) { 9764 return (v1 > v2) ? -1 : 1; 9765 } 9766 if (r1.isDefault != r2.isDefault) { 9767 return r1.isDefault ? -1 : 1; 9768 } 9769 v1 = r1.match; 9770 v2 = r2.match; 9771 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9772 if (v1 != v2) { 9773 return (v1 > v2) ? -1 : 1; 9774 } 9775 if (r1.system != r2.system) { 9776 return r1.system ? -1 : 1; 9777 } 9778 if (r1.activityInfo != null) { 9779 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 9780 } 9781 if (r1.serviceInfo != null) { 9782 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 9783 } 9784 if (r1.providerInfo != null) { 9785 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 9786 } 9787 return 0; 9788 } 9789 }; 9790 9791 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9792 new Comparator<ProviderInfo>() { 9793 public int compare(ProviderInfo p1, ProviderInfo p2) { 9794 final int v1 = p1.initOrder; 9795 final int v2 = p2.initOrder; 9796 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9797 } 9798 }; 9799 9800 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 9801 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 9802 final int[] userIds) { 9803 mHandler.post(new Runnable() { 9804 @Override 9805 public void run() { 9806 try { 9807 final IActivityManager am = ActivityManagerNative.getDefault(); 9808 if (am == null) return; 9809 final int[] resolvedUserIds; 9810 if (userIds == null) { 9811 resolvedUserIds = am.getRunningUserIds(); 9812 } else { 9813 resolvedUserIds = userIds; 9814 } 9815 for (int id : resolvedUserIds) { 9816 final Intent intent = new Intent(action, 9817 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9818 if (extras != null) { 9819 intent.putExtras(extras); 9820 } 9821 if (targetPkg != null) { 9822 intent.setPackage(targetPkg); 9823 } 9824 // Modify the UID when posting to other users 9825 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9826 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9827 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9828 intent.putExtra(Intent.EXTRA_UID, uid); 9829 } 9830 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9831 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 9832 if (DEBUG_BROADCASTS) { 9833 RuntimeException here = new RuntimeException("here"); 9834 here.fillInStackTrace(); 9835 Slog.d(TAG, "Sending to user " + id + ": " 9836 + intent.toShortString(false, true, false, false) 9837 + " " + intent.getExtras(), here); 9838 } 9839 am.broadcastIntent(null, intent, null, finishedReceiver, 9840 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9841 null, finishedReceiver != null, false, id); 9842 } 9843 } catch (RemoteException ex) { 9844 } 9845 } 9846 }); 9847 } 9848 9849 /** 9850 * Check if the external storage media is available. This is true if there 9851 * is a mounted external storage medium or if the external storage is 9852 * emulated. 9853 */ 9854 private boolean isExternalMediaAvailable() { 9855 return mMediaMounted || Environment.isExternalStorageEmulated(); 9856 } 9857 9858 @Override 9859 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9860 // writer 9861 synchronized (mPackages) { 9862 if (!isExternalMediaAvailable()) { 9863 // If the external storage is no longer mounted at this point, 9864 // the caller may not have been able to delete all of this 9865 // packages files and can not delete any more. Bail. 9866 return null; 9867 } 9868 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9869 if (lastPackage != null) { 9870 pkgs.remove(lastPackage); 9871 } 9872 if (pkgs.size() > 0) { 9873 return pkgs.get(0); 9874 } 9875 } 9876 return null; 9877 } 9878 9879 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9880 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9881 userId, andCode ? 1 : 0, packageName); 9882 if (mSystemReady) { 9883 msg.sendToTarget(); 9884 } else { 9885 if (mPostSystemReadyMessages == null) { 9886 mPostSystemReadyMessages = new ArrayList<>(); 9887 } 9888 mPostSystemReadyMessages.add(msg); 9889 } 9890 } 9891 9892 void startCleaningPackages() { 9893 // reader 9894 synchronized (mPackages) { 9895 if (!isExternalMediaAvailable()) { 9896 return; 9897 } 9898 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9899 return; 9900 } 9901 } 9902 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9903 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9904 IActivityManager am = ActivityManagerNative.getDefault(); 9905 if (am != null) { 9906 try { 9907 am.startService(null, intent, null, mContext.getOpPackageName(), 9908 UserHandle.USER_SYSTEM); 9909 } catch (RemoteException e) { 9910 } 9911 } 9912 } 9913 9914 @Override 9915 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9916 int installFlags, String installerPackageName, VerificationParams verificationParams, 9917 String packageAbiOverride) { 9918 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9919 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9920 } 9921 9922 @Override 9923 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9924 int installFlags, String installerPackageName, VerificationParams verificationParams, 9925 String packageAbiOverride, int userId) { 9926 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9927 9928 final int callingUid = Binder.getCallingUid(); 9929 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9930 9931 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9932 try { 9933 if (observer != null) { 9934 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9935 } 9936 } catch (RemoteException re) { 9937 } 9938 return; 9939 } 9940 9941 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9942 installFlags |= PackageManager.INSTALL_FROM_ADB; 9943 9944 } else { 9945 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9946 // about installerPackageName. 9947 9948 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9949 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9950 } 9951 9952 UserHandle user; 9953 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9954 user = UserHandle.ALL; 9955 } else { 9956 user = new UserHandle(userId); 9957 } 9958 9959 // Only system components can circumvent runtime permissions when installing. 9960 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9961 && mContext.checkCallingOrSelfPermission(Manifest.permission 9962 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9963 throw new SecurityException("You need the " 9964 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9965 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9966 } 9967 9968 verificationParams.setInstallerUid(callingUid); 9969 9970 final File originFile = new File(originPath); 9971 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9972 9973 final Message msg = mHandler.obtainMessage(INIT_COPY); 9974 final InstallParams params = new InstallParams(origin, null, observer, installFlags, 9975 installerPackageName, null, verificationParams, user, packageAbiOverride, null); 9976 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 9977 msg.obj = params; 9978 9979 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 9980 System.identityHashCode(msg.obj)); 9981 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9982 System.identityHashCode(msg.obj)); 9983 9984 mHandler.sendMessage(msg); 9985 } 9986 9987 void installStage(String packageName, File stagedDir, String stagedCid, 9988 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 9989 String installerPackageName, int installerUid, UserHandle user) { 9990 if (DEBUG_EPHEMERAL) { 9991 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 9992 Slog.d(TAG, "Ephemeral install of " + packageName); 9993 } 9994 } 9995 final VerificationParams verifParams = new VerificationParams( 9996 null, sessionParams.originatingUri, sessionParams.referrerUri, 9997 sessionParams.originatingUid); 9998 verifParams.setInstallerUid(installerUid); 9999 10000 final OriginInfo origin; 10001 if (stagedDir != null) { 10002 origin = OriginInfo.fromStagedFile(stagedDir); 10003 } else { 10004 origin = OriginInfo.fromStagedContainer(stagedCid); 10005 } 10006 10007 final Message msg = mHandler.obtainMessage(INIT_COPY); 10008 final InstallParams params = new InstallParams(origin, null, observer, 10009 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 10010 verifParams, user, sessionParams.abiOverride, 10011 sessionParams.grantedRuntimePermissions); 10012 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 10013 msg.obj = params; 10014 10015 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 10016 System.identityHashCode(msg.obj)); 10017 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10018 System.identityHashCode(msg.obj)); 10019 10020 mHandler.sendMessage(msg); 10021 } 10022 10023 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 10024 Bundle extras = new Bundle(1); 10025 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 10026 10027 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 10028 packageName, extras, 0, null, null, new int[] {userId}); 10029 try { 10030 IActivityManager am = ActivityManagerNative.getDefault(); 10031 final boolean isSystem = 10032 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 10033 if (isSystem && am.isUserRunning(userId, 0)) { 10034 // The just-installed/enabled app is bundled on the system, so presumed 10035 // to be able to run automatically without needing an explicit launch. 10036 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 10037 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 10038 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 10039 .setPackage(packageName); 10040 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 10041 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 10042 } 10043 } catch (RemoteException e) { 10044 // shouldn't happen 10045 Slog.w(TAG, "Unable to bootstrap installed package", e); 10046 } 10047 } 10048 10049 @Override 10050 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 10051 int userId) { 10052 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10053 PackageSetting pkgSetting; 10054 final int uid = Binder.getCallingUid(); 10055 enforceCrossUserPermission(uid, userId, true, true, 10056 "setApplicationHiddenSetting for user " + userId); 10057 10058 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 10059 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 10060 return false; 10061 } 10062 10063 long callingId = Binder.clearCallingIdentity(); 10064 try { 10065 boolean sendAdded = false; 10066 boolean sendRemoved = false; 10067 // writer 10068 synchronized (mPackages) { 10069 pkgSetting = mSettings.mPackages.get(packageName); 10070 if (pkgSetting == null) { 10071 return false; 10072 } 10073 if (pkgSetting.getHidden(userId) != hidden) { 10074 pkgSetting.setHidden(hidden, userId); 10075 mSettings.writePackageRestrictionsLPr(userId); 10076 if (hidden) { 10077 sendRemoved = true; 10078 } else { 10079 sendAdded = true; 10080 } 10081 } 10082 } 10083 if (sendAdded) { 10084 sendPackageAddedForUser(packageName, pkgSetting, userId); 10085 return true; 10086 } 10087 if (sendRemoved) { 10088 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 10089 "hiding pkg"); 10090 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 10091 return true; 10092 } 10093 } finally { 10094 Binder.restoreCallingIdentity(callingId); 10095 } 10096 return false; 10097 } 10098 10099 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 10100 int userId) { 10101 final PackageRemovedInfo info = new PackageRemovedInfo(); 10102 info.removedPackage = packageName; 10103 info.removedUsers = new int[] {userId}; 10104 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 10105 info.sendBroadcast(false, false, false); 10106 } 10107 10108 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 10109 if (pkgList.length > 0) { 10110 Bundle extras = new Bundle(1); 10111 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 10112 10113 sendPackageBroadcast( 10114 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 10115 : Intent.ACTION_PACKAGES_UNSUSPENDED, 10116 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 10117 new int[] {userId}); 10118 } 10119 } 10120 10121 /** 10122 * Returns true if application is not found or there was an error. Otherwise it returns 10123 * the hidden state of the package for the given user. 10124 */ 10125 @Override 10126 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 10127 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10128 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 10129 false, "getApplicationHidden for user " + userId); 10130 PackageSetting pkgSetting; 10131 long callingId = Binder.clearCallingIdentity(); 10132 try { 10133 // writer 10134 synchronized (mPackages) { 10135 pkgSetting = mSettings.mPackages.get(packageName); 10136 if (pkgSetting == null) { 10137 return true; 10138 } 10139 return pkgSetting.getHidden(userId); 10140 } 10141 } finally { 10142 Binder.restoreCallingIdentity(callingId); 10143 } 10144 } 10145 10146 /** 10147 * @hide 10148 */ 10149 @Override 10150 public int installExistingPackageAsUser(String packageName, int userId) { 10151 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 10152 null); 10153 PackageSetting pkgSetting; 10154 final int uid = Binder.getCallingUid(); 10155 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 10156 + userId); 10157 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10158 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 10159 } 10160 10161 long callingId = Binder.clearCallingIdentity(); 10162 try { 10163 boolean installed = false; 10164 10165 // writer 10166 synchronized (mPackages) { 10167 pkgSetting = mSettings.mPackages.get(packageName); 10168 if (pkgSetting == null) { 10169 return PackageManager.INSTALL_FAILED_INVALID_URI; 10170 } 10171 if (!pkgSetting.getInstalled(userId)) { 10172 pkgSetting.setInstalled(true, userId); 10173 pkgSetting.setHidden(false, userId); 10174 mSettings.writePackageRestrictionsLPr(userId); 10175 if (pkgSetting.pkg != null) { 10176 prepareAppDataAfterInstall(pkgSetting.pkg); 10177 } 10178 installed = true; 10179 } 10180 } 10181 10182 if (installed) { 10183 sendPackageAddedForUser(packageName, pkgSetting, userId); 10184 } 10185 } finally { 10186 Binder.restoreCallingIdentity(callingId); 10187 } 10188 10189 return PackageManager.INSTALL_SUCCEEDED; 10190 } 10191 10192 boolean isUserRestricted(int userId, String restrictionKey) { 10193 Bundle restrictions = sUserManager.getUserRestrictions(userId); 10194 if (restrictions.getBoolean(restrictionKey, false)) { 10195 Log.w(TAG, "User is restricted: " + restrictionKey); 10196 return true; 10197 } 10198 return false; 10199 } 10200 10201 @Override 10202 public boolean setPackageSuspendedAsUser(String packageName, boolean suspended, int userId) { 10203 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10204 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true, 10205 "setPackageSuspended for user " + userId); 10206 10207 // TODO: investigate and add more restrictions for suspending crucial packages. 10208 if (isPackageDeviceAdmin(packageName, userId)) { 10209 Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName 10210 + "\": has active device admin"); 10211 return false; 10212 } 10213 10214 long callingId = Binder.clearCallingIdentity(); 10215 try { 10216 boolean changed = false; 10217 boolean success = false; 10218 int appId = -1; 10219 synchronized (mPackages) { 10220 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10221 if (pkgSetting != null) { 10222 if (pkgSetting.getSuspended(userId) != suspended) { 10223 pkgSetting.setSuspended(suspended, userId); 10224 mSettings.writePackageRestrictionsLPr(userId); 10225 appId = pkgSetting.appId; 10226 changed = true; 10227 } 10228 success = true; 10229 } 10230 } 10231 10232 if (changed) { 10233 sendPackagesSuspendedForUser(new String[]{packageName}, userId, suspended); 10234 if (suspended) { 10235 killApplication(packageName, UserHandle.getUid(userId, appId), 10236 "suspending package"); 10237 } 10238 } 10239 return success; 10240 } finally { 10241 Binder.restoreCallingIdentity(callingId); 10242 } 10243 } 10244 10245 @Override 10246 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 10247 mContext.enforceCallingOrSelfPermission( 10248 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10249 "Only package verification agents can verify applications"); 10250 10251 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10252 final PackageVerificationResponse response = new PackageVerificationResponse( 10253 verificationCode, Binder.getCallingUid()); 10254 msg.arg1 = id; 10255 msg.obj = response; 10256 mHandler.sendMessage(msg); 10257 } 10258 10259 @Override 10260 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 10261 long millisecondsToDelay) { 10262 mContext.enforceCallingOrSelfPermission( 10263 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10264 "Only package verification agents can extend verification timeouts"); 10265 10266 final PackageVerificationState state = mPendingVerification.get(id); 10267 final PackageVerificationResponse response = new PackageVerificationResponse( 10268 verificationCodeAtTimeout, Binder.getCallingUid()); 10269 10270 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 10271 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 10272 } 10273 if (millisecondsToDelay < 0) { 10274 millisecondsToDelay = 0; 10275 } 10276 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 10277 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 10278 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 10279 } 10280 10281 if ((state != null) && !state.timeoutExtended()) { 10282 state.extendTimeout(); 10283 10284 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10285 msg.arg1 = id; 10286 msg.obj = response; 10287 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 10288 } 10289 } 10290 10291 private void broadcastPackageVerified(int verificationId, Uri packageUri, 10292 int verificationCode, UserHandle user) { 10293 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 10294 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 10295 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10296 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10297 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 10298 10299 mContext.sendBroadcastAsUser(intent, user, 10300 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 10301 } 10302 10303 private ComponentName matchComponentForVerifier(String packageName, 10304 List<ResolveInfo> receivers) { 10305 ActivityInfo targetReceiver = null; 10306 10307 final int NR = receivers.size(); 10308 for (int i = 0; i < NR; i++) { 10309 final ResolveInfo info = receivers.get(i); 10310 if (info.activityInfo == null) { 10311 continue; 10312 } 10313 10314 if (packageName.equals(info.activityInfo.packageName)) { 10315 targetReceiver = info.activityInfo; 10316 break; 10317 } 10318 } 10319 10320 if (targetReceiver == null) { 10321 return null; 10322 } 10323 10324 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 10325 } 10326 10327 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 10328 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 10329 if (pkgInfo.verifiers.length == 0) { 10330 return null; 10331 } 10332 10333 final int N = pkgInfo.verifiers.length; 10334 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 10335 for (int i = 0; i < N; i++) { 10336 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 10337 10338 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 10339 receivers); 10340 if (comp == null) { 10341 continue; 10342 } 10343 10344 final int verifierUid = getUidForVerifier(verifierInfo); 10345 if (verifierUid == -1) { 10346 continue; 10347 } 10348 10349 if (DEBUG_VERIFY) { 10350 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 10351 + " with the correct signature"); 10352 } 10353 sufficientVerifiers.add(comp); 10354 verificationState.addSufficientVerifier(verifierUid); 10355 } 10356 10357 return sufficientVerifiers; 10358 } 10359 10360 private int getUidForVerifier(VerifierInfo verifierInfo) { 10361 synchronized (mPackages) { 10362 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 10363 if (pkg == null) { 10364 return -1; 10365 } else if (pkg.mSignatures.length != 1) { 10366 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10367 + " has more than one signature; ignoring"); 10368 return -1; 10369 } 10370 10371 /* 10372 * If the public key of the package's signature does not match 10373 * our expected public key, then this is a different package and 10374 * we should skip. 10375 */ 10376 10377 final byte[] expectedPublicKey; 10378 try { 10379 final Signature verifierSig = pkg.mSignatures[0]; 10380 final PublicKey publicKey = verifierSig.getPublicKey(); 10381 expectedPublicKey = publicKey.getEncoded(); 10382 } catch (CertificateException e) { 10383 return -1; 10384 } 10385 10386 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 10387 10388 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 10389 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10390 + " does not have the expected public key; ignoring"); 10391 return -1; 10392 } 10393 10394 return pkg.applicationInfo.uid; 10395 } 10396 } 10397 10398 @Override 10399 public void finishPackageInstall(int token) { 10400 enforceSystemOrRoot("Only the system is allowed to finish installs"); 10401 10402 if (DEBUG_INSTALL) { 10403 Slog.v(TAG, "BM finishing package install for " + token); 10404 } 10405 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10406 10407 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10408 mHandler.sendMessage(msg); 10409 } 10410 10411 /** 10412 * Get the verification agent timeout. 10413 * 10414 * @return verification timeout in milliseconds 10415 */ 10416 private long getVerificationTimeout() { 10417 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 10418 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 10419 DEFAULT_VERIFICATION_TIMEOUT); 10420 } 10421 10422 /** 10423 * Get the default verification agent response code. 10424 * 10425 * @return default verification response code 10426 */ 10427 private int getDefaultVerificationResponse() { 10428 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10429 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 10430 DEFAULT_VERIFICATION_RESPONSE); 10431 } 10432 10433 /** 10434 * Check whether or not package verification has been enabled. 10435 * 10436 * @return true if verification should be performed 10437 */ 10438 private boolean isVerificationEnabled(int userId, int installFlags) { 10439 if (!DEFAULT_VERIFY_ENABLE) { 10440 return false; 10441 } 10442 // Ephemeral apps don't get the full verification treatment 10443 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10444 if (DEBUG_EPHEMERAL) { 10445 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 10446 } 10447 return false; 10448 } 10449 10450 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 10451 10452 // Check if installing from ADB 10453 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 10454 // Do not run verification in a test harness environment 10455 if (ActivityManager.isRunningInTestHarness()) { 10456 return false; 10457 } 10458 if (ensureVerifyAppsEnabled) { 10459 return true; 10460 } 10461 // Check if the developer does not want package verification for ADB installs 10462 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10463 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 10464 return false; 10465 } 10466 } 10467 10468 if (ensureVerifyAppsEnabled) { 10469 return true; 10470 } 10471 10472 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10473 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 10474 } 10475 10476 @Override 10477 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 10478 throws RemoteException { 10479 mContext.enforceCallingOrSelfPermission( 10480 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 10481 "Only intentfilter verification agents can verify applications"); 10482 10483 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 10484 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 10485 Binder.getCallingUid(), verificationCode, failedDomains); 10486 msg.arg1 = id; 10487 msg.obj = response; 10488 mHandler.sendMessage(msg); 10489 } 10490 10491 @Override 10492 public int getIntentVerificationStatus(String packageName, int userId) { 10493 synchronized (mPackages) { 10494 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10495 } 10496 } 10497 10498 @Override 10499 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10500 mContext.enforceCallingOrSelfPermission( 10501 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10502 10503 boolean result = false; 10504 synchronized (mPackages) { 10505 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10506 } 10507 if (result) { 10508 scheduleWritePackageRestrictionsLocked(userId); 10509 } 10510 return result; 10511 } 10512 10513 @Override 10514 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10515 synchronized (mPackages) { 10516 return mSettings.getIntentFilterVerificationsLPr(packageName); 10517 } 10518 } 10519 10520 @Override 10521 public List<IntentFilter> getAllIntentFilters(String packageName) { 10522 if (TextUtils.isEmpty(packageName)) { 10523 return Collections.<IntentFilter>emptyList(); 10524 } 10525 synchronized (mPackages) { 10526 PackageParser.Package pkg = mPackages.get(packageName); 10527 if (pkg == null || pkg.activities == null) { 10528 return Collections.<IntentFilter>emptyList(); 10529 } 10530 final int count = pkg.activities.size(); 10531 ArrayList<IntentFilter> result = new ArrayList<>(); 10532 for (int n=0; n<count; n++) { 10533 PackageParser.Activity activity = pkg.activities.get(n); 10534 if (activity.intents != null && activity.intents.size() > 0) { 10535 result.addAll(activity.intents); 10536 } 10537 } 10538 return result; 10539 } 10540 } 10541 10542 @Override 10543 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10544 mContext.enforceCallingOrSelfPermission( 10545 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10546 10547 synchronized (mPackages) { 10548 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10549 if (packageName != null) { 10550 result |= updateIntentVerificationStatus(packageName, 10551 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10552 userId); 10553 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10554 packageName, userId); 10555 } 10556 return result; 10557 } 10558 } 10559 10560 @Override 10561 public String getDefaultBrowserPackageName(int userId) { 10562 synchronized (mPackages) { 10563 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10564 } 10565 } 10566 10567 /** 10568 * Get the "allow unknown sources" setting. 10569 * 10570 * @return the current "allow unknown sources" setting 10571 */ 10572 private int getUnknownSourcesSettings() { 10573 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10574 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10575 -1); 10576 } 10577 10578 @Override 10579 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10580 final int uid = Binder.getCallingUid(); 10581 // writer 10582 synchronized (mPackages) { 10583 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10584 if (targetPackageSetting == null) { 10585 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10586 } 10587 10588 PackageSetting installerPackageSetting; 10589 if (installerPackageName != null) { 10590 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10591 if (installerPackageSetting == null) { 10592 throw new IllegalArgumentException("Unknown installer package: " 10593 + installerPackageName); 10594 } 10595 } else { 10596 installerPackageSetting = null; 10597 } 10598 10599 Signature[] callerSignature; 10600 Object obj = mSettings.getUserIdLPr(uid); 10601 if (obj != null) { 10602 if (obj instanceof SharedUserSetting) { 10603 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10604 } else if (obj instanceof PackageSetting) { 10605 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10606 } else { 10607 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10608 } 10609 } else { 10610 throw new SecurityException("Unknown calling UID: " + uid); 10611 } 10612 10613 // Verify: can't set installerPackageName to a package that is 10614 // not signed with the same cert as the caller. 10615 if (installerPackageSetting != null) { 10616 if (compareSignatures(callerSignature, 10617 installerPackageSetting.signatures.mSignatures) 10618 != PackageManager.SIGNATURE_MATCH) { 10619 throw new SecurityException( 10620 "Caller does not have same cert as new installer package " 10621 + installerPackageName); 10622 } 10623 } 10624 10625 // Verify: if target already has an installer package, it must 10626 // be signed with the same cert as the caller. 10627 if (targetPackageSetting.installerPackageName != null) { 10628 PackageSetting setting = mSettings.mPackages.get( 10629 targetPackageSetting.installerPackageName); 10630 // If the currently set package isn't valid, then it's always 10631 // okay to change it. 10632 if (setting != null) { 10633 if (compareSignatures(callerSignature, 10634 setting.signatures.mSignatures) 10635 != PackageManager.SIGNATURE_MATCH) { 10636 throw new SecurityException( 10637 "Caller does not have same cert as old installer package " 10638 + targetPackageSetting.installerPackageName); 10639 } 10640 } 10641 } 10642 10643 // Okay! 10644 targetPackageSetting.installerPackageName = installerPackageName; 10645 scheduleWriteSettingsLocked(); 10646 } 10647 } 10648 10649 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10650 // Queue up an async operation since the package installation may take a little while. 10651 mHandler.post(new Runnable() { 10652 public void run() { 10653 mHandler.removeCallbacks(this); 10654 // Result object to be returned 10655 PackageInstalledInfo res = new PackageInstalledInfo(); 10656 res.returnCode = currentStatus; 10657 res.uid = -1; 10658 res.pkg = null; 10659 res.removedInfo = new PackageRemovedInfo(); 10660 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10661 args.doPreInstall(res.returnCode); 10662 synchronized (mInstallLock) { 10663 installPackageTracedLI(args, res); 10664 } 10665 args.doPostInstall(res.returnCode, res.uid); 10666 } 10667 10668 // A restore should be performed at this point if (a) the install 10669 // succeeded, (b) the operation is not an update, and (c) the new 10670 // package has not opted out of backup participation. 10671 final boolean update = res.removedInfo.removedPackage != null; 10672 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10673 boolean doRestore = !update 10674 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10675 10676 // Set up the post-install work request bookkeeping. This will be used 10677 // and cleaned up by the post-install event handling regardless of whether 10678 // there's a restore pass performed. Token values are >= 1. 10679 int token; 10680 if (mNextInstallToken < 0) mNextInstallToken = 1; 10681 token = mNextInstallToken++; 10682 10683 PostInstallData data = new PostInstallData(args, res); 10684 mRunningInstalls.put(token, data); 10685 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10686 10687 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10688 // Pass responsibility to the Backup Manager. It will perform a 10689 // restore if appropriate, then pass responsibility back to the 10690 // Package Manager to run the post-install observer callbacks 10691 // and broadcasts. 10692 IBackupManager bm = IBackupManager.Stub.asInterface( 10693 ServiceManager.getService(Context.BACKUP_SERVICE)); 10694 if (bm != null) { 10695 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10696 + " to BM for possible restore"); 10697 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10698 try { 10699 // TODO: http://b/22388012 10700 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 10701 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10702 } else { 10703 doRestore = false; 10704 } 10705 } catch (RemoteException e) { 10706 // can't happen; the backup manager is local 10707 } catch (Exception e) { 10708 Slog.e(TAG, "Exception trying to enqueue restore", e); 10709 doRestore = false; 10710 } 10711 } else { 10712 Slog.e(TAG, "Backup Manager not found!"); 10713 doRestore = false; 10714 } 10715 } 10716 10717 if (!doRestore) { 10718 // No restore possible, or the Backup Manager was mysteriously not 10719 // available -- just fire the post-install work request directly. 10720 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10721 10722 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 10723 10724 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10725 mHandler.sendMessage(msg); 10726 } 10727 } 10728 }); 10729 } 10730 10731 private abstract class HandlerParams { 10732 private static final int MAX_RETRIES = 4; 10733 10734 /** 10735 * Number of times startCopy() has been attempted and had a non-fatal 10736 * error. 10737 */ 10738 private int mRetries = 0; 10739 10740 /** User handle for the user requesting the information or installation. */ 10741 private final UserHandle mUser; 10742 String traceMethod; 10743 int traceCookie; 10744 10745 HandlerParams(UserHandle user) { 10746 mUser = user; 10747 } 10748 10749 UserHandle getUser() { 10750 return mUser; 10751 } 10752 10753 HandlerParams setTraceMethod(String traceMethod) { 10754 this.traceMethod = traceMethod; 10755 return this; 10756 } 10757 10758 HandlerParams setTraceCookie(int traceCookie) { 10759 this.traceCookie = traceCookie; 10760 return this; 10761 } 10762 10763 final boolean startCopy() { 10764 boolean res; 10765 try { 10766 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10767 10768 if (++mRetries > MAX_RETRIES) { 10769 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10770 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10771 handleServiceError(); 10772 return false; 10773 } else { 10774 handleStartCopy(); 10775 res = true; 10776 } 10777 } catch (RemoteException e) { 10778 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10779 mHandler.sendEmptyMessage(MCS_RECONNECT); 10780 res = false; 10781 } 10782 handleReturnCode(); 10783 return res; 10784 } 10785 10786 final void serviceError() { 10787 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10788 handleServiceError(); 10789 handleReturnCode(); 10790 } 10791 10792 abstract void handleStartCopy() throws RemoteException; 10793 abstract void handleServiceError(); 10794 abstract void handleReturnCode(); 10795 } 10796 10797 class MeasureParams extends HandlerParams { 10798 private final PackageStats mStats; 10799 private boolean mSuccess; 10800 10801 private final IPackageStatsObserver mObserver; 10802 10803 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10804 super(new UserHandle(stats.userHandle)); 10805 mObserver = observer; 10806 mStats = stats; 10807 } 10808 10809 @Override 10810 public String toString() { 10811 return "MeasureParams{" 10812 + Integer.toHexString(System.identityHashCode(this)) 10813 + " " + mStats.packageName + "}"; 10814 } 10815 10816 @Override 10817 void handleStartCopy() throws RemoteException { 10818 synchronized (mInstallLock) { 10819 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10820 } 10821 10822 if (mSuccess) { 10823 final boolean mounted; 10824 if (Environment.isExternalStorageEmulated()) { 10825 mounted = true; 10826 } else { 10827 final String status = Environment.getExternalStorageState(); 10828 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10829 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10830 } 10831 10832 if (mounted) { 10833 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10834 10835 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10836 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10837 10838 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10839 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10840 10841 // Always subtract cache size, since it's a subdirectory 10842 mStats.externalDataSize -= mStats.externalCacheSize; 10843 10844 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10845 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10846 10847 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10848 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10849 } 10850 } 10851 } 10852 10853 @Override 10854 void handleReturnCode() { 10855 if (mObserver != null) { 10856 try { 10857 mObserver.onGetStatsCompleted(mStats, mSuccess); 10858 } catch (RemoteException e) { 10859 Slog.i(TAG, "Observer no longer exists."); 10860 } 10861 } 10862 } 10863 10864 @Override 10865 void handleServiceError() { 10866 Slog.e(TAG, "Could not measure application " + mStats.packageName 10867 + " external storage"); 10868 } 10869 } 10870 10871 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10872 throws RemoteException { 10873 long result = 0; 10874 for (File path : paths) { 10875 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10876 } 10877 return result; 10878 } 10879 10880 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10881 for (File path : paths) { 10882 try { 10883 mcs.clearDirectory(path.getAbsolutePath()); 10884 } catch (RemoteException e) { 10885 } 10886 } 10887 } 10888 10889 static class OriginInfo { 10890 /** 10891 * Location where install is coming from, before it has been 10892 * copied/renamed into place. This could be a single monolithic APK 10893 * file, or a cluster directory. This location may be untrusted. 10894 */ 10895 final File file; 10896 final String cid; 10897 10898 /** 10899 * Flag indicating that {@link #file} or {@link #cid} has already been 10900 * staged, meaning downstream users don't need to defensively copy the 10901 * contents. 10902 */ 10903 final boolean staged; 10904 10905 /** 10906 * Flag indicating that {@link #file} or {@link #cid} is an already 10907 * installed app that is being moved. 10908 */ 10909 final boolean existing; 10910 10911 final String resolvedPath; 10912 final File resolvedFile; 10913 10914 static OriginInfo fromNothing() { 10915 return new OriginInfo(null, null, false, false); 10916 } 10917 10918 static OriginInfo fromUntrustedFile(File file) { 10919 return new OriginInfo(file, null, false, false); 10920 } 10921 10922 static OriginInfo fromExistingFile(File file) { 10923 return new OriginInfo(file, null, false, true); 10924 } 10925 10926 static OriginInfo fromStagedFile(File file) { 10927 return new OriginInfo(file, null, true, false); 10928 } 10929 10930 static OriginInfo fromStagedContainer(String cid) { 10931 return new OriginInfo(null, cid, true, false); 10932 } 10933 10934 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10935 this.file = file; 10936 this.cid = cid; 10937 this.staged = staged; 10938 this.existing = existing; 10939 10940 if (cid != null) { 10941 resolvedPath = PackageHelper.getSdDir(cid); 10942 resolvedFile = new File(resolvedPath); 10943 } else if (file != null) { 10944 resolvedPath = file.getAbsolutePath(); 10945 resolvedFile = file; 10946 } else { 10947 resolvedPath = null; 10948 resolvedFile = null; 10949 } 10950 } 10951 } 10952 10953 static class MoveInfo { 10954 final int moveId; 10955 final String fromUuid; 10956 final String toUuid; 10957 final String packageName; 10958 final String dataAppName; 10959 final int appId; 10960 final String seinfo; 10961 final int targetSdkVersion; 10962 10963 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10964 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 10965 this.moveId = moveId; 10966 this.fromUuid = fromUuid; 10967 this.toUuid = toUuid; 10968 this.packageName = packageName; 10969 this.dataAppName = dataAppName; 10970 this.appId = appId; 10971 this.seinfo = seinfo; 10972 this.targetSdkVersion = targetSdkVersion; 10973 } 10974 } 10975 10976 class InstallParams extends HandlerParams { 10977 final OriginInfo origin; 10978 final MoveInfo move; 10979 final IPackageInstallObserver2 observer; 10980 int installFlags; 10981 final String installerPackageName; 10982 final String volumeUuid; 10983 final VerificationParams verificationParams; 10984 private InstallArgs mArgs; 10985 private int mRet; 10986 final String packageAbiOverride; 10987 final String[] grantedRuntimePermissions; 10988 10989 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10990 int installFlags, String installerPackageName, String volumeUuid, 10991 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10992 String[] grantedPermissions) { 10993 super(user); 10994 this.origin = origin; 10995 this.move = move; 10996 this.observer = observer; 10997 this.installFlags = installFlags; 10998 this.installerPackageName = installerPackageName; 10999 this.volumeUuid = volumeUuid; 11000 this.verificationParams = verificationParams; 11001 this.packageAbiOverride = packageAbiOverride; 11002 this.grantedRuntimePermissions = grantedPermissions; 11003 } 11004 11005 @Override 11006 public String toString() { 11007 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 11008 + " file=" + origin.file + " cid=" + origin.cid + "}"; 11009 } 11010 11011 private int installLocationPolicy(PackageInfoLite pkgLite) { 11012 String packageName = pkgLite.packageName; 11013 int installLocation = pkgLite.installLocation; 11014 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11015 // reader 11016 synchronized (mPackages) { 11017 PackageParser.Package pkg = mPackages.get(packageName); 11018 if (pkg != null) { 11019 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11020 // Check for downgrading. 11021 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 11022 try { 11023 checkDowngrade(pkg, pkgLite); 11024 } catch (PackageManagerException e) { 11025 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 11026 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 11027 } 11028 } 11029 // Check for updated system application. 11030 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11031 if (onSd) { 11032 Slog.w(TAG, "Cannot install update to system app on sdcard"); 11033 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 11034 } 11035 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11036 } else { 11037 if (onSd) { 11038 // Install flag overrides everything. 11039 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11040 } 11041 // If current upgrade specifies particular preference 11042 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 11043 // Application explicitly specified internal. 11044 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11045 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 11046 // App explictly prefers external. Let policy decide 11047 } else { 11048 // Prefer previous location 11049 if (isExternal(pkg)) { 11050 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11051 } 11052 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11053 } 11054 } 11055 } else { 11056 // Invalid install. Return error code 11057 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 11058 } 11059 } 11060 } 11061 // All the special cases have been taken care of. 11062 // Return result based on recommended install location. 11063 if (onSd) { 11064 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11065 } 11066 return pkgLite.recommendedInstallLocation; 11067 } 11068 11069 /* 11070 * Invoke remote method to get package information and install 11071 * location values. Override install location based on default 11072 * policy if needed and then create install arguments based 11073 * on the install location. 11074 */ 11075 public void handleStartCopy() throws RemoteException { 11076 int ret = PackageManager.INSTALL_SUCCEEDED; 11077 11078 // If we're already staged, we've firmly committed to an install location 11079 if (origin.staged) { 11080 if (origin.file != null) { 11081 installFlags |= PackageManager.INSTALL_INTERNAL; 11082 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11083 } else if (origin.cid != null) { 11084 installFlags |= PackageManager.INSTALL_EXTERNAL; 11085 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11086 } else { 11087 throw new IllegalStateException("Invalid stage location"); 11088 } 11089 } 11090 11091 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11092 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 11093 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11094 PackageInfoLite pkgLite = null; 11095 11096 if (onInt && onSd) { 11097 // Check if both bits are set. 11098 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 11099 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11100 } else if (onSd && ephemeral) { 11101 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 11102 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11103 } else { 11104 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 11105 packageAbiOverride); 11106 11107 if (DEBUG_EPHEMERAL && ephemeral) { 11108 Slog.v(TAG, "pkgLite for install: " + pkgLite); 11109 } 11110 11111 /* 11112 * If we have too little free space, try to free cache 11113 * before giving up. 11114 */ 11115 if (!origin.staged && pkgLite.recommendedInstallLocation 11116 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11117 // TODO: focus freeing disk space on the target device 11118 final StorageManager storage = StorageManager.from(mContext); 11119 final long lowThreshold = storage.getStorageLowBytes( 11120 Environment.getDataDirectory()); 11121 11122 final long sizeBytes = mContainerService.calculateInstalledSize( 11123 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 11124 11125 try { 11126 mInstaller.freeCache(null, sizeBytes + lowThreshold); 11127 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 11128 installFlags, packageAbiOverride); 11129 } catch (InstallerException e) { 11130 Slog.w(TAG, "Failed to free cache", e); 11131 } 11132 11133 /* 11134 * The cache free must have deleted the file we 11135 * downloaded to install. 11136 * 11137 * TODO: fix the "freeCache" call to not delete 11138 * the file we care about. 11139 */ 11140 if (pkgLite.recommendedInstallLocation 11141 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11142 pkgLite.recommendedInstallLocation 11143 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 11144 } 11145 } 11146 } 11147 11148 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11149 int loc = pkgLite.recommendedInstallLocation; 11150 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 11151 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11152 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 11153 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 11154 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11155 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11156 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 11157 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 11158 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11159 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 11160 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 11161 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 11162 } else { 11163 // Override with defaults if needed. 11164 loc = installLocationPolicy(pkgLite); 11165 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 11166 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 11167 } else if (!onSd && !onInt) { 11168 // Override install location with flags 11169 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 11170 // Set the flag to install on external media. 11171 installFlags |= PackageManager.INSTALL_EXTERNAL; 11172 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11173 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 11174 if (DEBUG_EPHEMERAL) { 11175 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 11176 } 11177 installFlags |= PackageManager.INSTALL_EPHEMERAL; 11178 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 11179 |PackageManager.INSTALL_INTERNAL); 11180 } else { 11181 // Make sure the flag for installing on external 11182 // media is unset 11183 installFlags |= PackageManager.INSTALL_INTERNAL; 11184 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11185 } 11186 } 11187 } 11188 } 11189 11190 final InstallArgs args = createInstallArgs(this); 11191 mArgs = args; 11192 11193 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11194 // TODO: http://b/22976637 11195 // Apps installed for "all" users use the device owner to verify the app 11196 UserHandle verifierUser = getUser(); 11197 if (verifierUser == UserHandle.ALL) { 11198 verifierUser = UserHandle.SYSTEM; 11199 } 11200 11201 /* 11202 * Determine if we have any installed package verifiers. If we 11203 * do, then we'll defer to them to verify the packages. 11204 */ 11205 final int requiredUid = mRequiredVerifierPackage == null ? -1 11206 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 11207 verifierUser.getIdentifier()); 11208 if (!origin.existing && requiredUid != -1 11209 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 11210 final Intent verification = new Intent( 11211 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 11212 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 11213 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 11214 PACKAGE_MIME_TYPE); 11215 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11216 11217 // Query all live verifiers based on current user state 11218 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 11219 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 11220 11221 if (DEBUG_VERIFY) { 11222 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 11223 + verification.toString() + " with " + pkgLite.verifiers.length 11224 + " optional verifiers"); 11225 } 11226 11227 final int verificationId = mPendingVerificationToken++; 11228 11229 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11230 11231 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 11232 installerPackageName); 11233 11234 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 11235 installFlags); 11236 11237 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 11238 pkgLite.packageName); 11239 11240 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 11241 pkgLite.versionCode); 11242 11243 if (verificationParams != null) { 11244 if (verificationParams.getVerificationURI() != null) { 11245 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 11246 verificationParams.getVerificationURI()); 11247 } 11248 if (verificationParams.getOriginatingURI() != null) { 11249 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 11250 verificationParams.getOriginatingURI()); 11251 } 11252 if (verificationParams.getReferrer() != null) { 11253 verification.putExtra(Intent.EXTRA_REFERRER, 11254 verificationParams.getReferrer()); 11255 } 11256 if (verificationParams.getOriginatingUid() >= 0) { 11257 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 11258 verificationParams.getOriginatingUid()); 11259 } 11260 if (verificationParams.getInstallerUid() >= 0) { 11261 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 11262 verificationParams.getInstallerUid()); 11263 } 11264 } 11265 11266 final PackageVerificationState verificationState = new PackageVerificationState( 11267 requiredUid, args); 11268 11269 mPendingVerification.append(verificationId, verificationState); 11270 11271 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 11272 receivers, verificationState); 11273 11274 /* 11275 * If any sufficient verifiers were listed in the package 11276 * manifest, attempt to ask them. 11277 */ 11278 if (sufficientVerifiers != null) { 11279 final int N = sufficientVerifiers.size(); 11280 if (N == 0) { 11281 Slog.i(TAG, "Additional verifiers required, but none installed."); 11282 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 11283 } else { 11284 for (int i = 0; i < N; i++) { 11285 final ComponentName verifierComponent = sufficientVerifiers.get(i); 11286 11287 final Intent sufficientIntent = new Intent(verification); 11288 sufficientIntent.setComponent(verifierComponent); 11289 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 11290 } 11291 } 11292 } 11293 11294 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 11295 mRequiredVerifierPackage, receivers); 11296 if (ret == PackageManager.INSTALL_SUCCEEDED 11297 && mRequiredVerifierPackage != null) { 11298 Trace.asyncTraceBegin( 11299 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 11300 /* 11301 * Send the intent to the required verification agent, 11302 * but only start the verification timeout after the 11303 * target BroadcastReceivers have run. 11304 */ 11305 verification.setComponent(requiredVerifierComponent); 11306 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 11307 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11308 new BroadcastReceiver() { 11309 @Override 11310 public void onReceive(Context context, Intent intent) { 11311 final Message msg = mHandler 11312 .obtainMessage(CHECK_PENDING_VERIFICATION); 11313 msg.arg1 = verificationId; 11314 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 11315 } 11316 }, null, 0, null, null); 11317 11318 /* 11319 * We don't want the copy to proceed until verification 11320 * succeeds, so null out this field. 11321 */ 11322 mArgs = null; 11323 } 11324 } else { 11325 /* 11326 * No package verification is enabled, so immediately start 11327 * the remote call to initiate copy using temporary file. 11328 */ 11329 ret = args.copyApk(mContainerService, true); 11330 } 11331 } 11332 11333 mRet = ret; 11334 } 11335 11336 @Override 11337 void handleReturnCode() { 11338 // If mArgs is null, then MCS couldn't be reached. When it 11339 // reconnects, it will try again to install. At that point, this 11340 // will succeed. 11341 if (mArgs != null) { 11342 processPendingInstall(mArgs, mRet); 11343 } 11344 } 11345 11346 @Override 11347 void handleServiceError() { 11348 mArgs = createInstallArgs(this); 11349 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11350 } 11351 11352 public boolean isForwardLocked() { 11353 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11354 } 11355 } 11356 11357 /** 11358 * Used during creation of InstallArgs 11359 * 11360 * @param installFlags package installation flags 11361 * @return true if should be installed on external storage 11362 */ 11363 private static boolean installOnExternalAsec(int installFlags) { 11364 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 11365 return false; 11366 } 11367 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 11368 return true; 11369 } 11370 return false; 11371 } 11372 11373 /** 11374 * Used during creation of InstallArgs 11375 * 11376 * @param installFlags package installation flags 11377 * @return true if should be installed as forward locked 11378 */ 11379 private static boolean installForwardLocked(int installFlags) { 11380 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11381 } 11382 11383 private InstallArgs createInstallArgs(InstallParams params) { 11384 if (params.move != null) { 11385 return new MoveInstallArgs(params); 11386 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 11387 return new AsecInstallArgs(params); 11388 } else { 11389 return new FileInstallArgs(params); 11390 } 11391 } 11392 11393 /** 11394 * Create args that describe an existing installed package. Typically used 11395 * when cleaning up old installs, or used as a move source. 11396 */ 11397 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 11398 String resourcePath, String[] instructionSets) { 11399 final boolean isInAsec; 11400 if (installOnExternalAsec(installFlags)) { 11401 /* Apps on SD card are always in ASEC containers. */ 11402 isInAsec = true; 11403 } else if (installForwardLocked(installFlags) 11404 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 11405 /* 11406 * Forward-locked apps are only in ASEC containers if they're the 11407 * new style 11408 */ 11409 isInAsec = true; 11410 } else { 11411 isInAsec = false; 11412 } 11413 11414 if (isInAsec) { 11415 return new AsecInstallArgs(codePath, instructionSets, 11416 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 11417 } else { 11418 return new FileInstallArgs(codePath, resourcePath, instructionSets); 11419 } 11420 } 11421 11422 static abstract class InstallArgs { 11423 /** @see InstallParams#origin */ 11424 final OriginInfo origin; 11425 /** @see InstallParams#move */ 11426 final MoveInfo move; 11427 11428 final IPackageInstallObserver2 observer; 11429 // Always refers to PackageManager flags only 11430 final int installFlags; 11431 final String installerPackageName; 11432 final String volumeUuid; 11433 final UserHandle user; 11434 final String abiOverride; 11435 final String[] installGrantPermissions; 11436 /** If non-null, drop an async trace when the install completes */ 11437 final String traceMethod; 11438 final int traceCookie; 11439 11440 // The list of instruction sets supported by this app. This is currently 11441 // only used during the rmdex() phase to clean up resources. We can get rid of this 11442 // if we move dex files under the common app path. 11443 /* nullable */ String[] instructionSets; 11444 11445 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11446 int installFlags, String installerPackageName, String volumeUuid, 11447 UserHandle user, String[] instructionSets, 11448 String abiOverride, String[] installGrantPermissions, 11449 String traceMethod, int traceCookie) { 11450 this.origin = origin; 11451 this.move = move; 11452 this.installFlags = installFlags; 11453 this.observer = observer; 11454 this.installerPackageName = installerPackageName; 11455 this.volumeUuid = volumeUuid; 11456 this.user = user; 11457 this.instructionSets = instructionSets; 11458 this.abiOverride = abiOverride; 11459 this.installGrantPermissions = installGrantPermissions; 11460 this.traceMethod = traceMethod; 11461 this.traceCookie = traceCookie; 11462 } 11463 11464 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 11465 abstract int doPreInstall(int status); 11466 11467 /** 11468 * Rename package into final resting place. All paths on the given 11469 * scanned package should be updated to reflect the rename. 11470 */ 11471 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 11472 abstract int doPostInstall(int status, int uid); 11473 11474 /** @see PackageSettingBase#codePathString */ 11475 abstract String getCodePath(); 11476 /** @see PackageSettingBase#resourcePathString */ 11477 abstract String getResourcePath(); 11478 11479 // Need installer lock especially for dex file removal. 11480 abstract void cleanUpResourcesLI(); 11481 abstract boolean doPostDeleteLI(boolean delete); 11482 11483 /** 11484 * Called before the source arguments are copied. This is used mostly 11485 * for MoveParams when it needs to read the source file to put it in the 11486 * destination. 11487 */ 11488 int doPreCopy() { 11489 return PackageManager.INSTALL_SUCCEEDED; 11490 } 11491 11492 /** 11493 * Called after the source arguments are copied. This is used mostly for 11494 * MoveParams when it needs to read the source file to put it in the 11495 * destination. 11496 * 11497 * @return 11498 */ 11499 int doPostCopy(int uid) { 11500 return PackageManager.INSTALL_SUCCEEDED; 11501 } 11502 11503 protected boolean isFwdLocked() { 11504 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11505 } 11506 11507 protected boolean isExternalAsec() { 11508 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11509 } 11510 11511 protected boolean isEphemeral() { 11512 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11513 } 11514 11515 UserHandle getUser() { 11516 return user; 11517 } 11518 } 11519 11520 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 11521 if (!allCodePaths.isEmpty()) { 11522 if (instructionSets == null) { 11523 throw new IllegalStateException("instructionSet == null"); 11524 } 11525 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11526 for (String codePath : allCodePaths) { 11527 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11528 try { 11529 mInstaller.rmdex(codePath, dexCodeInstructionSet); 11530 } catch (InstallerException ignored) { 11531 } 11532 } 11533 } 11534 } 11535 } 11536 11537 /** 11538 * Logic to handle installation of non-ASEC applications, including copying 11539 * and renaming logic. 11540 */ 11541 class FileInstallArgs extends InstallArgs { 11542 private File codeFile; 11543 private File resourceFile; 11544 11545 // Example topology: 11546 // /data/app/com.example/base.apk 11547 // /data/app/com.example/split_foo.apk 11548 // /data/app/com.example/lib/arm/libfoo.so 11549 // /data/app/com.example/lib/arm64/libfoo.so 11550 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11551 11552 /** New install */ 11553 FileInstallArgs(InstallParams params) { 11554 super(params.origin, params.move, params.observer, params.installFlags, 11555 params.installerPackageName, params.volumeUuid, 11556 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11557 params.grantedRuntimePermissions, 11558 params.traceMethod, params.traceCookie); 11559 if (isFwdLocked()) { 11560 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11561 } 11562 } 11563 11564 /** Existing install */ 11565 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11566 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 11567 null, null, null, 0); 11568 this.codeFile = (codePath != null) ? new File(codePath) : null; 11569 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11570 } 11571 11572 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11573 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 11574 try { 11575 return doCopyApk(imcs, temp); 11576 } finally { 11577 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11578 } 11579 } 11580 11581 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11582 if (origin.staged) { 11583 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11584 codeFile = origin.file; 11585 resourceFile = origin.file; 11586 return PackageManager.INSTALL_SUCCEEDED; 11587 } 11588 11589 try { 11590 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11591 final File tempDir = 11592 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 11593 codeFile = tempDir; 11594 resourceFile = tempDir; 11595 } catch (IOException e) { 11596 Slog.w(TAG, "Failed to create copy file: " + e); 11597 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11598 } 11599 11600 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11601 @Override 11602 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11603 if (!FileUtils.isValidExtFilename(name)) { 11604 throw new IllegalArgumentException("Invalid filename: " + name); 11605 } 11606 try { 11607 final File file = new File(codeFile, name); 11608 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11609 O_RDWR | O_CREAT, 0644); 11610 Os.chmod(file.getAbsolutePath(), 0644); 11611 return new ParcelFileDescriptor(fd); 11612 } catch (ErrnoException e) { 11613 throw new RemoteException("Failed to open: " + e.getMessage()); 11614 } 11615 } 11616 }; 11617 11618 int ret = PackageManager.INSTALL_SUCCEEDED; 11619 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11620 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11621 Slog.e(TAG, "Failed to copy package"); 11622 return ret; 11623 } 11624 11625 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11626 NativeLibraryHelper.Handle handle = null; 11627 try { 11628 handle = NativeLibraryHelper.Handle.create(codeFile); 11629 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11630 abiOverride); 11631 } catch (IOException e) { 11632 Slog.e(TAG, "Copying native libraries failed", e); 11633 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11634 } finally { 11635 IoUtils.closeQuietly(handle); 11636 } 11637 11638 return ret; 11639 } 11640 11641 int doPreInstall(int status) { 11642 if (status != PackageManager.INSTALL_SUCCEEDED) { 11643 cleanUp(); 11644 } 11645 return status; 11646 } 11647 11648 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11649 if (status != PackageManager.INSTALL_SUCCEEDED) { 11650 cleanUp(); 11651 return false; 11652 } 11653 11654 final File targetDir = codeFile.getParentFile(); 11655 final File beforeCodeFile = codeFile; 11656 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11657 11658 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11659 try { 11660 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11661 } catch (ErrnoException e) { 11662 Slog.w(TAG, "Failed to rename", e); 11663 return false; 11664 } 11665 11666 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11667 Slog.w(TAG, "Failed to restorecon"); 11668 return false; 11669 } 11670 11671 // Reflect the rename internally 11672 codeFile = afterCodeFile; 11673 resourceFile = afterCodeFile; 11674 11675 // Reflect the rename in scanned details 11676 pkg.codePath = afterCodeFile.getAbsolutePath(); 11677 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11678 pkg.baseCodePath); 11679 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11680 pkg.splitCodePaths); 11681 11682 // Reflect the rename in app info 11683 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11684 pkg.applicationInfo.setCodePath(pkg.codePath); 11685 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11686 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11687 pkg.applicationInfo.setResourcePath(pkg.codePath); 11688 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11689 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11690 11691 return true; 11692 } 11693 11694 int doPostInstall(int status, int uid) { 11695 if (status != PackageManager.INSTALL_SUCCEEDED) { 11696 cleanUp(); 11697 } 11698 return status; 11699 } 11700 11701 @Override 11702 String getCodePath() { 11703 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11704 } 11705 11706 @Override 11707 String getResourcePath() { 11708 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11709 } 11710 11711 private boolean cleanUp() { 11712 if (codeFile == null || !codeFile.exists()) { 11713 return false; 11714 } 11715 11716 removeCodePathLI(codeFile); 11717 11718 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11719 resourceFile.delete(); 11720 } 11721 11722 return true; 11723 } 11724 11725 void cleanUpResourcesLI() { 11726 // Try enumerating all code paths before deleting 11727 List<String> allCodePaths = Collections.EMPTY_LIST; 11728 if (codeFile != null && codeFile.exists()) { 11729 try { 11730 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11731 allCodePaths = pkg.getAllCodePaths(); 11732 } catch (PackageParserException e) { 11733 // Ignored; we tried our best 11734 } 11735 } 11736 11737 cleanUp(); 11738 removeDexFiles(allCodePaths, instructionSets); 11739 } 11740 11741 boolean doPostDeleteLI(boolean delete) { 11742 // XXX err, shouldn't we respect the delete flag? 11743 cleanUpResourcesLI(); 11744 return true; 11745 } 11746 } 11747 11748 private boolean isAsecExternal(String cid) { 11749 final String asecPath = PackageHelper.getSdFilesystem(cid); 11750 return !asecPath.startsWith(mAsecInternalPath); 11751 } 11752 11753 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11754 PackageManagerException { 11755 if (copyRet < 0) { 11756 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11757 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11758 throw new PackageManagerException(copyRet, message); 11759 } 11760 } 11761 } 11762 11763 /** 11764 * Extract the MountService "container ID" from the full code path of an 11765 * .apk. 11766 */ 11767 static String cidFromCodePath(String fullCodePath) { 11768 int eidx = fullCodePath.lastIndexOf("/"); 11769 String subStr1 = fullCodePath.substring(0, eidx); 11770 int sidx = subStr1.lastIndexOf("/"); 11771 return subStr1.substring(sidx+1, eidx); 11772 } 11773 11774 /** 11775 * Logic to handle installation of ASEC applications, including copying and 11776 * renaming logic. 11777 */ 11778 class AsecInstallArgs extends InstallArgs { 11779 static final String RES_FILE_NAME = "pkg.apk"; 11780 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11781 11782 String cid; 11783 String packagePath; 11784 String resourcePath; 11785 11786 /** New install */ 11787 AsecInstallArgs(InstallParams params) { 11788 super(params.origin, params.move, params.observer, params.installFlags, 11789 params.installerPackageName, params.volumeUuid, 11790 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11791 params.grantedRuntimePermissions, 11792 params.traceMethod, params.traceCookie); 11793 } 11794 11795 /** Existing install */ 11796 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11797 boolean isExternal, boolean isForwardLocked) { 11798 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11799 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 11800 instructionSets, null, null, null, 0); 11801 // Hackily pretend we're still looking at a full code path 11802 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11803 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11804 } 11805 11806 // Extract cid from fullCodePath 11807 int eidx = fullCodePath.lastIndexOf("/"); 11808 String subStr1 = fullCodePath.substring(0, eidx); 11809 int sidx = subStr1.lastIndexOf("/"); 11810 cid = subStr1.substring(sidx+1, eidx); 11811 setMountPath(subStr1); 11812 } 11813 11814 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11815 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11816 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 11817 instructionSets, null, null, null, 0); 11818 this.cid = cid; 11819 setMountPath(PackageHelper.getSdDir(cid)); 11820 } 11821 11822 void createCopyFile() { 11823 cid = mInstallerService.allocateExternalStageCidLegacy(); 11824 } 11825 11826 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11827 if (origin.staged && origin.cid != null) { 11828 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11829 cid = origin.cid; 11830 setMountPath(PackageHelper.getSdDir(cid)); 11831 return PackageManager.INSTALL_SUCCEEDED; 11832 } 11833 11834 if (temp) { 11835 createCopyFile(); 11836 } else { 11837 /* 11838 * Pre-emptively destroy the container since it's destroyed if 11839 * copying fails due to it existing anyway. 11840 */ 11841 PackageHelper.destroySdDir(cid); 11842 } 11843 11844 final String newMountPath = imcs.copyPackageToContainer( 11845 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11846 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11847 11848 if (newMountPath != null) { 11849 setMountPath(newMountPath); 11850 return PackageManager.INSTALL_SUCCEEDED; 11851 } else { 11852 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11853 } 11854 } 11855 11856 @Override 11857 String getCodePath() { 11858 return packagePath; 11859 } 11860 11861 @Override 11862 String getResourcePath() { 11863 return resourcePath; 11864 } 11865 11866 int doPreInstall(int status) { 11867 if (status != PackageManager.INSTALL_SUCCEEDED) { 11868 // Destroy container 11869 PackageHelper.destroySdDir(cid); 11870 } else { 11871 boolean mounted = PackageHelper.isContainerMounted(cid); 11872 if (!mounted) { 11873 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11874 Process.SYSTEM_UID); 11875 if (newMountPath != null) { 11876 setMountPath(newMountPath); 11877 } else { 11878 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11879 } 11880 } 11881 } 11882 return status; 11883 } 11884 11885 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11886 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11887 String newMountPath = null; 11888 if (PackageHelper.isContainerMounted(cid)) { 11889 // Unmount the container 11890 if (!PackageHelper.unMountSdDir(cid)) { 11891 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11892 return false; 11893 } 11894 } 11895 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11896 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11897 " which might be stale. Will try to clean up."); 11898 // Clean up the stale container and proceed to recreate. 11899 if (!PackageHelper.destroySdDir(newCacheId)) { 11900 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11901 return false; 11902 } 11903 // Successfully cleaned up stale container. Try to rename again. 11904 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11905 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11906 + " inspite of cleaning it up."); 11907 return false; 11908 } 11909 } 11910 if (!PackageHelper.isContainerMounted(newCacheId)) { 11911 Slog.w(TAG, "Mounting container " + newCacheId); 11912 newMountPath = PackageHelper.mountSdDir(newCacheId, 11913 getEncryptKey(), Process.SYSTEM_UID); 11914 } else { 11915 newMountPath = PackageHelper.getSdDir(newCacheId); 11916 } 11917 if (newMountPath == null) { 11918 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11919 return false; 11920 } 11921 Log.i(TAG, "Succesfully renamed " + cid + 11922 " to " + newCacheId + 11923 " at new path: " + newMountPath); 11924 cid = newCacheId; 11925 11926 final File beforeCodeFile = new File(packagePath); 11927 setMountPath(newMountPath); 11928 final File afterCodeFile = new File(packagePath); 11929 11930 // Reflect the rename in scanned details 11931 pkg.codePath = afterCodeFile.getAbsolutePath(); 11932 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11933 pkg.baseCodePath); 11934 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11935 pkg.splitCodePaths); 11936 11937 // Reflect the rename in app info 11938 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11939 pkg.applicationInfo.setCodePath(pkg.codePath); 11940 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11941 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11942 pkg.applicationInfo.setResourcePath(pkg.codePath); 11943 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11944 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11945 11946 return true; 11947 } 11948 11949 private void setMountPath(String mountPath) { 11950 final File mountFile = new File(mountPath); 11951 11952 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11953 if (monolithicFile.exists()) { 11954 packagePath = monolithicFile.getAbsolutePath(); 11955 if (isFwdLocked()) { 11956 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11957 } else { 11958 resourcePath = packagePath; 11959 } 11960 } else { 11961 packagePath = mountFile.getAbsolutePath(); 11962 resourcePath = packagePath; 11963 } 11964 } 11965 11966 int doPostInstall(int status, int uid) { 11967 if (status != PackageManager.INSTALL_SUCCEEDED) { 11968 cleanUp(); 11969 } else { 11970 final int groupOwner; 11971 final String protectedFile; 11972 if (isFwdLocked()) { 11973 groupOwner = UserHandle.getSharedAppGid(uid); 11974 protectedFile = RES_FILE_NAME; 11975 } else { 11976 groupOwner = -1; 11977 protectedFile = null; 11978 } 11979 11980 if (uid < Process.FIRST_APPLICATION_UID 11981 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11982 Slog.e(TAG, "Failed to finalize " + cid); 11983 PackageHelper.destroySdDir(cid); 11984 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11985 } 11986 11987 boolean mounted = PackageHelper.isContainerMounted(cid); 11988 if (!mounted) { 11989 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11990 } 11991 } 11992 return status; 11993 } 11994 11995 private void cleanUp() { 11996 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11997 11998 // Destroy secure container 11999 PackageHelper.destroySdDir(cid); 12000 } 12001 12002 private List<String> getAllCodePaths() { 12003 final File codeFile = new File(getCodePath()); 12004 if (codeFile != null && codeFile.exists()) { 12005 try { 12006 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12007 return pkg.getAllCodePaths(); 12008 } catch (PackageParserException e) { 12009 // Ignored; we tried our best 12010 } 12011 } 12012 return Collections.EMPTY_LIST; 12013 } 12014 12015 void cleanUpResourcesLI() { 12016 // Enumerate all code paths before deleting 12017 cleanUpResourcesLI(getAllCodePaths()); 12018 } 12019 12020 private void cleanUpResourcesLI(List<String> allCodePaths) { 12021 cleanUp(); 12022 removeDexFiles(allCodePaths, instructionSets); 12023 } 12024 12025 String getPackageName() { 12026 return getAsecPackageName(cid); 12027 } 12028 12029 boolean doPostDeleteLI(boolean delete) { 12030 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 12031 final List<String> allCodePaths = getAllCodePaths(); 12032 boolean mounted = PackageHelper.isContainerMounted(cid); 12033 if (mounted) { 12034 // Unmount first 12035 if (PackageHelper.unMountSdDir(cid)) { 12036 mounted = false; 12037 } 12038 } 12039 if (!mounted && delete) { 12040 cleanUpResourcesLI(allCodePaths); 12041 } 12042 return !mounted; 12043 } 12044 12045 @Override 12046 int doPreCopy() { 12047 if (isFwdLocked()) { 12048 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 12049 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 12050 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12051 } 12052 } 12053 12054 return PackageManager.INSTALL_SUCCEEDED; 12055 } 12056 12057 @Override 12058 int doPostCopy(int uid) { 12059 if (isFwdLocked()) { 12060 if (uid < Process.FIRST_APPLICATION_UID 12061 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 12062 RES_FILE_NAME)) { 12063 Slog.e(TAG, "Failed to finalize " + cid); 12064 PackageHelper.destroySdDir(cid); 12065 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12066 } 12067 } 12068 12069 return PackageManager.INSTALL_SUCCEEDED; 12070 } 12071 } 12072 12073 /** 12074 * Logic to handle movement of existing installed applications. 12075 */ 12076 class MoveInstallArgs extends InstallArgs { 12077 private File codeFile; 12078 private File resourceFile; 12079 12080 /** New install */ 12081 MoveInstallArgs(InstallParams params) { 12082 super(params.origin, params.move, params.observer, params.installFlags, 12083 params.installerPackageName, params.volumeUuid, 12084 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12085 params.grantedRuntimePermissions, 12086 params.traceMethod, params.traceCookie); 12087 } 12088 12089 int copyApk(IMediaContainerService imcs, boolean temp) { 12090 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 12091 + move.fromUuid + " to " + move.toUuid); 12092 synchronized (mInstaller) { 12093 try { 12094 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 12095 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 12096 } catch (InstallerException e) { 12097 Slog.w(TAG, "Failed to move app", e); 12098 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12099 } 12100 } 12101 12102 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 12103 resourceFile = codeFile; 12104 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 12105 12106 return PackageManager.INSTALL_SUCCEEDED; 12107 } 12108 12109 int doPreInstall(int status) { 12110 if (status != PackageManager.INSTALL_SUCCEEDED) { 12111 cleanUp(move.toUuid); 12112 } 12113 return status; 12114 } 12115 12116 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12117 if (status != PackageManager.INSTALL_SUCCEEDED) { 12118 cleanUp(move.toUuid); 12119 return false; 12120 } 12121 12122 // Reflect the move in app info 12123 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 12124 pkg.applicationInfo.setCodePath(pkg.codePath); 12125 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 12126 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 12127 pkg.applicationInfo.setResourcePath(pkg.codePath); 12128 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 12129 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 12130 12131 return true; 12132 } 12133 12134 int doPostInstall(int status, int uid) { 12135 if (status == PackageManager.INSTALL_SUCCEEDED) { 12136 cleanUp(move.fromUuid); 12137 } else { 12138 cleanUp(move.toUuid); 12139 } 12140 return status; 12141 } 12142 12143 @Override 12144 String getCodePath() { 12145 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12146 } 12147 12148 @Override 12149 String getResourcePath() { 12150 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12151 } 12152 12153 private boolean cleanUp(String volumeUuid) { 12154 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 12155 move.dataAppName); 12156 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 12157 synchronized (mInstallLock) { 12158 // Clean up both app data and code 12159 removeDataDirsLI(volumeUuid, move.packageName); 12160 removeCodePathLI(codeFile); 12161 } 12162 return true; 12163 } 12164 12165 void cleanUpResourcesLI() { 12166 throw new UnsupportedOperationException(); 12167 } 12168 12169 boolean doPostDeleteLI(boolean delete) { 12170 throw new UnsupportedOperationException(); 12171 } 12172 } 12173 12174 static String getAsecPackageName(String packageCid) { 12175 int idx = packageCid.lastIndexOf("-"); 12176 if (idx == -1) { 12177 return packageCid; 12178 } 12179 return packageCid.substring(0, idx); 12180 } 12181 12182 // Utility method used to create code paths based on package name and available index. 12183 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 12184 String idxStr = ""; 12185 int idx = 1; 12186 // Fall back to default value of idx=1 if prefix is not 12187 // part of oldCodePath 12188 if (oldCodePath != null) { 12189 String subStr = oldCodePath; 12190 // Drop the suffix right away 12191 if (suffix != null && subStr.endsWith(suffix)) { 12192 subStr = subStr.substring(0, subStr.length() - suffix.length()); 12193 } 12194 // If oldCodePath already contains prefix find out the 12195 // ending index to either increment or decrement. 12196 int sidx = subStr.lastIndexOf(prefix); 12197 if (sidx != -1) { 12198 subStr = subStr.substring(sidx + prefix.length()); 12199 if (subStr != null) { 12200 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 12201 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 12202 } 12203 try { 12204 idx = Integer.parseInt(subStr); 12205 if (idx <= 1) { 12206 idx++; 12207 } else { 12208 idx--; 12209 } 12210 } catch(NumberFormatException e) { 12211 } 12212 } 12213 } 12214 } 12215 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 12216 return prefix + idxStr; 12217 } 12218 12219 private File getNextCodePath(File targetDir, String packageName) { 12220 int suffix = 1; 12221 File result; 12222 do { 12223 result = new File(targetDir, packageName + "-" + suffix); 12224 suffix++; 12225 } while (result.exists()); 12226 return result; 12227 } 12228 12229 // Utility method that returns the relative package path with respect 12230 // to the installation directory. Like say for /data/data/com.test-1.apk 12231 // string com.test-1 is returned. 12232 static String deriveCodePathName(String codePath) { 12233 if (codePath == null) { 12234 return null; 12235 } 12236 final File codeFile = new File(codePath); 12237 final String name = codeFile.getName(); 12238 if (codeFile.isDirectory()) { 12239 return name; 12240 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 12241 final int lastDot = name.lastIndexOf('.'); 12242 return name.substring(0, lastDot); 12243 } else { 12244 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 12245 return null; 12246 } 12247 } 12248 12249 static class PackageInstalledInfo { 12250 String name; 12251 int uid; 12252 // The set of users that originally had this package installed. 12253 int[] origUsers; 12254 // The set of users that now have this package installed. 12255 int[] newUsers; 12256 PackageParser.Package pkg; 12257 int returnCode; 12258 String returnMsg; 12259 PackageRemovedInfo removedInfo; 12260 12261 public void setError(int code, String msg) { 12262 returnCode = code; 12263 returnMsg = msg; 12264 Slog.w(TAG, msg); 12265 } 12266 12267 public void setError(String msg, PackageParserException e) { 12268 returnCode = e.error; 12269 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12270 Slog.w(TAG, msg, e); 12271 } 12272 12273 public void setError(String msg, PackageManagerException e) { 12274 returnCode = e.error; 12275 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12276 Slog.w(TAG, msg, e); 12277 } 12278 12279 // In some error cases we want to convey more info back to the observer 12280 String origPackage; 12281 String origPermission; 12282 } 12283 12284 /* 12285 * Install a non-existing package. 12286 */ 12287 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12288 UserHandle user, String installerPackageName, String volumeUuid, 12289 PackageInstalledInfo res) { 12290 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 12291 12292 // Remember this for later, in case we need to rollback this install 12293 String pkgName = pkg.packageName; 12294 12295 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 12296 // TODO: b/23350563 12297 final boolean dataDirExists = Environment 12298 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists(); 12299 12300 synchronized(mPackages) { 12301 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 12302 // A package with the same name is already installed, though 12303 // it has been renamed to an older name. The package we 12304 // are trying to install should be installed as an update to 12305 // the existing one, but that has not been requested, so bail. 12306 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12307 + " without first uninstalling package running as " 12308 + mSettings.mRenamedPackages.get(pkgName)); 12309 return; 12310 } 12311 if (mPackages.containsKey(pkgName)) { 12312 // Don't allow installation over an existing package with the same name. 12313 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12314 + " without first uninstalling."); 12315 return; 12316 } 12317 } 12318 12319 try { 12320 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 12321 System.currentTimeMillis(), user); 12322 12323 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 12324 prepareAppDataAfterInstall(newPackage); 12325 12326 // delete the partially installed application. the data directory will have to be 12327 // restored if it was already existing 12328 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12329 // remove package from internal structures. Note that we want deletePackageX to 12330 // delete the package data and cache directories that it created in 12331 // scanPackageLocked, unless those directories existed before we even tried to 12332 // install. 12333 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 12334 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 12335 res.removedInfo, true); 12336 } 12337 12338 } catch (PackageManagerException e) { 12339 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12340 } 12341 12342 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12343 } 12344 12345 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 12346 // Can't rotate keys during boot or if sharedUser. 12347 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 12348 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 12349 return false; 12350 } 12351 // app is using upgradeKeySets; make sure all are valid 12352 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12353 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 12354 for (int i = 0; i < upgradeKeySets.length; i++) { 12355 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 12356 Slog.wtf(TAG, "Package " 12357 + (oldPs.name != null ? oldPs.name : "<null>") 12358 + " contains upgrade-key-set reference to unknown key-set: " 12359 + upgradeKeySets[i] 12360 + " reverting to signatures check."); 12361 return false; 12362 } 12363 } 12364 return true; 12365 } 12366 12367 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 12368 // Upgrade keysets are being used. Determine if new package has a superset of the 12369 // required keys. 12370 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 12371 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12372 for (int i = 0; i < upgradeKeySets.length; i++) { 12373 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 12374 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 12375 return true; 12376 } 12377 } 12378 return false; 12379 } 12380 12381 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12382 UserHandle user, String installerPackageName, String volumeUuid, 12383 PackageInstalledInfo res) { 12384 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 12385 12386 final PackageParser.Package oldPackage; 12387 final String pkgName = pkg.packageName; 12388 final int[] allUsers; 12389 final boolean[] perUserInstalled; 12390 12391 // First find the old package info and check signatures 12392 synchronized(mPackages) { 12393 oldPackage = mPackages.get(pkgName); 12394 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 12395 if (isEphemeral && !oldIsEphemeral) { 12396 // can't downgrade from full to ephemeral 12397 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 12398 res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 12399 return; 12400 } 12401 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 12402 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12403 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12404 if(!checkUpgradeKeySetLP(ps, pkg)) { 12405 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12406 "New package not signed by keys specified by upgrade-keysets: " 12407 + pkgName); 12408 return; 12409 } 12410 } else { 12411 // default to original signature matching 12412 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 12413 != PackageManager.SIGNATURE_MATCH) { 12414 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12415 "New package has a different signature: " + pkgName); 12416 return; 12417 } 12418 } 12419 12420 // In case of rollback, remember per-user/profile install state 12421 allUsers = sUserManager.getUserIds(); 12422 perUserInstalled = new boolean[allUsers.length]; 12423 for (int i = 0; i < allUsers.length; i++) { 12424 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12425 } 12426 } 12427 12428 boolean sysPkg = (isSystemApp(oldPackage)); 12429 if (sysPkg) { 12430 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12431 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12432 } else { 12433 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12434 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12435 } 12436 } 12437 12438 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 12439 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12440 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12441 String volumeUuid, PackageInstalledInfo res) { 12442 String pkgName = deletedPackage.packageName; 12443 boolean deletedPkg = true; 12444 boolean updatedSettings = false; 12445 12446 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 12447 + deletedPackage); 12448 long origUpdateTime; 12449 if (pkg.mExtras != null) { 12450 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 12451 } else { 12452 origUpdateTime = 0; 12453 } 12454 12455 // First delete the existing package while retaining the data directory 12456 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 12457 res.removedInfo, true)) { 12458 // If the existing package wasn't successfully deleted 12459 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 12460 deletedPkg = false; 12461 } else { 12462 // Successfully deleted the old package; proceed with replace. 12463 12464 // If deleted package lived in a container, give users a chance to 12465 // relinquish resources before killing. 12466 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 12467 if (DEBUG_INSTALL) { 12468 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 12469 } 12470 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 12471 final ArrayList<String> pkgList = new ArrayList<String>(1); 12472 pkgList.add(deletedPackage.applicationInfo.packageName); 12473 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 12474 } 12475 12476 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 12477 try { 12478 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 12479 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 12480 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12481 perUserInstalled, res, user); 12482 prepareAppDataAfterInstall(newPackage); 12483 updatedSettings = true; 12484 } catch (PackageManagerException e) { 12485 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12486 } 12487 } 12488 12489 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12490 // remove package from internal structures. Note that we want deletePackageX to 12491 // delete the package data and cache directories that it created in 12492 // scanPackageLocked, unless those directories existed before we even tried to 12493 // install. 12494 if(updatedSettings) { 12495 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 12496 deletePackageLI( 12497 pkgName, null, true, allUsers, perUserInstalled, 12498 PackageManager.DELETE_KEEP_DATA, 12499 res.removedInfo, true); 12500 } 12501 // Since we failed to install the new package we need to restore the old 12502 // package that we deleted. 12503 if (deletedPkg) { 12504 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 12505 File restoreFile = new File(deletedPackage.codePath); 12506 // Parse old package 12507 boolean oldExternal = isExternal(deletedPackage); 12508 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 12509 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 12510 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12511 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 12512 try { 12513 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 12514 null); 12515 } catch (PackageManagerException e) { 12516 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 12517 + e.getMessage()); 12518 return; 12519 } 12520 // Restore of old package succeeded. Update permissions. 12521 // writer 12522 synchronized (mPackages) { 12523 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 12524 UPDATE_PERMISSIONS_ALL); 12525 // can downgrade to reader 12526 mSettings.writeLPr(); 12527 } 12528 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 12529 } 12530 } 12531 } 12532 12533 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 12534 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12535 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12536 String volumeUuid, PackageInstalledInfo res) { 12537 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 12538 + ", old=" + deletedPackage); 12539 boolean disabledSystem = false; 12540 boolean updatedSettings = false; 12541 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 12542 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 12543 != 0) { 12544 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12545 } 12546 String packageName = deletedPackage.packageName; 12547 if (packageName == null) { 12548 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12549 "Attempt to delete null packageName."); 12550 return; 12551 } 12552 PackageParser.Package oldPkg; 12553 PackageSetting oldPkgSetting; 12554 // reader 12555 synchronized (mPackages) { 12556 oldPkg = mPackages.get(packageName); 12557 oldPkgSetting = mSettings.mPackages.get(packageName); 12558 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 12559 (oldPkgSetting == null)) { 12560 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12561 "Couldn't find package " + packageName + " information"); 12562 return; 12563 } 12564 } 12565 12566 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12567 12568 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12569 res.removedInfo.removedPackage = packageName; 12570 // Remove existing system package 12571 removePackageLI(oldPkgSetting, true); 12572 // writer 12573 synchronized (mPackages) { 12574 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12575 if (!disabledSystem && deletedPackage != null) { 12576 // We didn't need to disable the .apk as a current system package, 12577 // which means we are replacing another update that is already 12578 // installed. We need to make sure to delete the older one's .apk. 12579 res.removedInfo.args = createInstallArgsForExisting(0, 12580 deletedPackage.applicationInfo.getCodePath(), 12581 deletedPackage.applicationInfo.getResourcePath(), 12582 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12583 } else { 12584 res.removedInfo.args = null; 12585 } 12586 } 12587 12588 // Successfully disabled the old package. Now proceed with re-installation 12589 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12590 12591 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12592 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12593 12594 PackageParser.Package newPackage = null; 12595 try { 12596 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 12597 if (newPackage.mExtras != null) { 12598 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12599 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12600 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12601 12602 // is the update attempting to change shared user? that isn't going to work... 12603 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12604 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12605 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12606 + " to " + newPkgSetting.sharedUser); 12607 updatedSettings = true; 12608 } 12609 } 12610 12611 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12612 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12613 perUserInstalled, res, user); 12614 prepareAppDataAfterInstall(newPackage); 12615 updatedSettings = true; 12616 } 12617 12618 } catch (PackageManagerException e) { 12619 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12620 } 12621 12622 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12623 // Re installation failed. Restore old information 12624 // Remove new pkg information 12625 if (newPackage != null) { 12626 removeInstalledPackageLI(newPackage, true); 12627 } 12628 // Add back the old system package 12629 try { 12630 scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12631 } catch (PackageManagerException e) { 12632 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12633 } 12634 // Restore the old system information in Settings 12635 synchronized (mPackages) { 12636 if (disabledSystem) { 12637 mSettings.enableSystemPackageLPw(packageName); 12638 } 12639 if (updatedSettings) { 12640 mSettings.setInstallerPackageName(packageName, 12641 oldPkgSetting.installerPackageName); 12642 } 12643 mSettings.writeLPr(); 12644 } 12645 } 12646 } 12647 12648 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 12649 // Collect all used permissions in the UID 12650 ArraySet<String> usedPermissions = new ArraySet<>(); 12651 final int packageCount = su.packages.size(); 12652 for (int i = 0; i < packageCount; i++) { 12653 PackageSetting ps = su.packages.valueAt(i); 12654 if (ps.pkg == null) { 12655 continue; 12656 } 12657 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 12658 for (int j = 0; j < requestedPermCount; j++) { 12659 String permission = ps.pkg.requestedPermissions.get(j); 12660 BasePermission bp = mSettings.mPermissions.get(permission); 12661 if (bp != null) { 12662 usedPermissions.add(permission); 12663 } 12664 } 12665 } 12666 12667 PermissionsState permissionsState = su.getPermissionsState(); 12668 // Prune install permissions 12669 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 12670 final int installPermCount = installPermStates.size(); 12671 for (int i = installPermCount - 1; i >= 0; i--) { 12672 PermissionState permissionState = installPermStates.get(i); 12673 if (!usedPermissions.contains(permissionState.getName())) { 12674 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12675 if (bp != null) { 12676 permissionsState.revokeInstallPermission(bp); 12677 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 12678 PackageManager.MASK_PERMISSION_FLAGS, 0); 12679 } 12680 } 12681 } 12682 12683 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 12684 12685 // Prune runtime permissions 12686 for (int userId : allUserIds) { 12687 List<PermissionState> runtimePermStates = permissionsState 12688 .getRuntimePermissionStates(userId); 12689 final int runtimePermCount = runtimePermStates.size(); 12690 for (int i = runtimePermCount - 1; i >= 0; i--) { 12691 PermissionState permissionState = runtimePermStates.get(i); 12692 if (!usedPermissions.contains(permissionState.getName())) { 12693 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12694 if (bp != null) { 12695 permissionsState.revokeRuntimePermission(bp, userId); 12696 permissionsState.updatePermissionFlags(bp, userId, 12697 PackageManager.MASK_PERMISSION_FLAGS, 0); 12698 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 12699 runtimePermissionChangedUserIds, userId); 12700 } 12701 } 12702 } 12703 } 12704 12705 return runtimePermissionChangedUserIds; 12706 } 12707 12708 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12709 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12710 UserHandle user) { 12711 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 12712 12713 String pkgName = newPackage.packageName; 12714 synchronized (mPackages) { 12715 //write settings. the installStatus will be incomplete at this stage. 12716 //note that the new package setting would have already been 12717 //added to mPackages. It hasn't been persisted yet. 12718 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12719 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12720 mSettings.writeLPr(); 12721 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12722 } 12723 12724 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12725 synchronized (mPackages) { 12726 updatePermissionsLPw(newPackage.packageName, newPackage, 12727 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12728 ? UPDATE_PERMISSIONS_ALL : 0)); 12729 // For system-bundled packages, we assume that installing an upgraded version 12730 // of the package implies that the user actually wants to run that new code, 12731 // so we enable the package. 12732 PackageSetting ps = mSettings.mPackages.get(pkgName); 12733 if (ps != null) { 12734 if (isSystemApp(newPackage)) { 12735 // NB: implicit assumption that system package upgrades apply to all users 12736 if (DEBUG_INSTALL) { 12737 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12738 } 12739 if (res.origUsers != null) { 12740 for (int userHandle : res.origUsers) { 12741 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12742 userHandle, installerPackageName); 12743 } 12744 } 12745 // Also convey the prior install/uninstall state 12746 if (allUsers != null && perUserInstalled != null) { 12747 for (int i = 0; i < allUsers.length; i++) { 12748 if (DEBUG_INSTALL) { 12749 Slog.d(TAG, " user " + allUsers[i] 12750 + " => " + perUserInstalled[i]); 12751 } 12752 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12753 } 12754 // these install state changes will be persisted in the 12755 // upcoming call to mSettings.writeLPr(). 12756 } 12757 } 12758 // It's implied that when a user requests installation, they want the app to be 12759 // installed and enabled. 12760 int userId = user.getIdentifier(); 12761 if (userId != UserHandle.USER_ALL) { 12762 ps.setInstalled(true, userId); 12763 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12764 } 12765 } 12766 res.name = pkgName; 12767 res.uid = newPackage.applicationInfo.uid; 12768 res.pkg = newPackage; 12769 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12770 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12771 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12772 //to update install status 12773 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12774 mSettings.writeLPr(); 12775 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12776 } 12777 12778 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12779 } 12780 12781 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 12782 try { 12783 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 12784 installPackageLI(args, res); 12785 } finally { 12786 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12787 } 12788 } 12789 12790 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12791 final int installFlags = args.installFlags; 12792 final String installerPackageName = args.installerPackageName; 12793 final String volumeUuid = args.volumeUuid; 12794 final File tmpPackageFile = new File(args.getCodePath()); 12795 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12796 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12797 || (args.volumeUuid != null)); 12798 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 12799 boolean replace = false; 12800 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12801 if (args.move != null) { 12802 // moving a complete application; perfom an initial scan on the new install location 12803 scanFlags |= SCAN_INITIAL; 12804 } 12805 // Result object to be returned 12806 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12807 12808 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12809 12810 // Sanity check 12811 if (ephemeral && (forwardLocked || onExternal)) { 12812 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 12813 + " external=" + onExternal); 12814 res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 12815 return; 12816 } 12817 12818 // Retrieve PackageSettings and parse package 12819 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12820 | PackageParser.PARSE_ENFORCE_CODE 12821 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12822 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 12823 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 12824 PackageParser pp = new PackageParser(); 12825 pp.setSeparateProcesses(mSeparateProcesses); 12826 pp.setDisplayMetrics(mMetrics); 12827 12828 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 12829 final PackageParser.Package pkg; 12830 try { 12831 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12832 } catch (PackageParserException e) { 12833 res.setError("Failed parse during installPackageLI", e); 12834 return; 12835 } finally { 12836 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12837 } 12838 12839 // Mark that we have an install time CPU ABI override. 12840 pkg.cpuAbiOverride = args.abiOverride; 12841 12842 String pkgName = res.name = pkg.packageName; 12843 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12844 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12845 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12846 return; 12847 } 12848 } 12849 12850 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 12851 try { 12852 pp.collectCertificates(pkg, parseFlags); 12853 } catch (PackageParserException e) { 12854 res.setError("Failed collect during installPackageLI", e); 12855 return; 12856 } finally { 12857 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12858 } 12859 12860 // Get rid of all references to package scan path via parser. 12861 pp = null; 12862 String oldCodePath = null; 12863 boolean systemApp = false; 12864 synchronized (mPackages) { 12865 // Check if installing already existing package 12866 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12867 String oldName = mSettings.mRenamedPackages.get(pkgName); 12868 if (pkg.mOriginalPackages != null 12869 && pkg.mOriginalPackages.contains(oldName) 12870 && mPackages.containsKey(oldName)) { 12871 // This package is derived from an original package, 12872 // and this device has been updating from that original 12873 // name. We must continue using the original name, so 12874 // rename the new package here. 12875 pkg.setPackageName(oldName); 12876 pkgName = pkg.packageName; 12877 replace = true; 12878 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12879 + oldName + " pkgName=" + pkgName); 12880 } else if (mPackages.containsKey(pkgName)) { 12881 // This package, under its official name, already exists 12882 // on the device; we should replace it. 12883 replace = true; 12884 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12885 } 12886 12887 // Prevent apps opting out from runtime permissions 12888 if (replace) { 12889 PackageParser.Package oldPackage = mPackages.get(pkgName); 12890 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12891 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12892 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12893 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12894 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12895 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12896 + " doesn't support runtime permissions but the old" 12897 + " target SDK " + oldTargetSdk + " does."); 12898 return; 12899 } 12900 } 12901 } 12902 12903 PackageSetting ps = mSettings.mPackages.get(pkgName); 12904 if (ps != null) { 12905 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12906 12907 // Quick sanity check that we're signed correctly if updating; 12908 // we'll check this again later when scanning, but we want to 12909 // bail early here before tripping over redefined permissions. 12910 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12911 if (!checkUpgradeKeySetLP(ps, pkg)) { 12912 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12913 + pkg.packageName + " upgrade keys do not match the " 12914 + "previously installed version"); 12915 return; 12916 } 12917 } else { 12918 try { 12919 verifySignaturesLP(ps, pkg); 12920 } catch (PackageManagerException e) { 12921 res.setError(e.error, e.getMessage()); 12922 return; 12923 } 12924 } 12925 12926 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12927 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12928 systemApp = (ps.pkg.applicationInfo.flags & 12929 ApplicationInfo.FLAG_SYSTEM) != 0; 12930 } 12931 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12932 } 12933 12934 // Check whether the newly-scanned package wants to define an already-defined perm 12935 int N = pkg.permissions.size(); 12936 for (int i = N-1; i >= 0; i--) { 12937 PackageParser.Permission perm = pkg.permissions.get(i); 12938 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12939 if (bp != null) { 12940 // If the defining package is signed with our cert, it's okay. This 12941 // also includes the "updating the same package" case, of course. 12942 // "updating same package" could also involve key-rotation. 12943 final boolean sigsOk; 12944 if (bp.sourcePackage.equals(pkg.packageName) 12945 && (bp.packageSetting instanceof PackageSetting) 12946 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12947 scanFlags))) { 12948 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12949 } else { 12950 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12951 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12952 } 12953 if (!sigsOk) { 12954 // If the owning package is the system itself, we log but allow 12955 // install to proceed; we fail the install on all other permission 12956 // redefinitions. 12957 if (!bp.sourcePackage.equals("android")) { 12958 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12959 + pkg.packageName + " attempting to redeclare permission " 12960 + perm.info.name + " already owned by " + bp.sourcePackage); 12961 res.origPermission = perm.info.name; 12962 res.origPackage = bp.sourcePackage; 12963 return; 12964 } else { 12965 Slog.w(TAG, "Package " + pkg.packageName 12966 + " attempting to redeclare system permission " 12967 + perm.info.name + "; ignoring new declaration"); 12968 pkg.permissions.remove(i); 12969 } 12970 } 12971 } 12972 } 12973 12974 } 12975 12976 if (systemApp) { 12977 if (onExternal) { 12978 // Abort update; system app can't be replaced with app on sdcard 12979 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12980 "Cannot install updates to system apps on sdcard"); 12981 return; 12982 } else if (ephemeral) { 12983 // Abort update; system app can't be replaced with an ephemeral app 12984 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 12985 "Cannot update a system app with an ephemeral app"); 12986 return; 12987 } 12988 } 12989 12990 if (args.move != null) { 12991 // We did an in-place move, so dex is ready to roll 12992 scanFlags |= SCAN_NO_DEX; 12993 scanFlags |= SCAN_MOVE; 12994 12995 synchronized (mPackages) { 12996 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12997 if (ps == null) { 12998 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12999 "Missing settings for moved package " + pkgName); 13000 } 13001 13002 // We moved the entire application as-is, so bring over the 13003 // previously derived ABI information. 13004 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 13005 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 13006 } 13007 13008 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 13009 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 13010 scanFlags |= SCAN_NO_DEX; 13011 13012 try { 13013 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 13014 true /* extract libs */); 13015 } catch (PackageManagerException pme) { 13016 Slog.e(TAG, "Error deriving application ABI", pme); 13017 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 13018 return; 13019 } 13020 13021 // Extract package to save the VM unzipping the APK in memory during 13022 // launch. Only do this if profile-guided compilation is enabled because 13023 // otherwise BackgroundDexOptService will not dexopt the package later. 13024 if (mUseJitProfiles) { 13025 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 13026 // Do not run PackageDexOptimizer through the local performDexOpt 13027 // method because `pkg` is not in `mPackages` yet. 13028 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 13029 false /* inclDependencies */, false /* useProfiles */, 13030 true /* extractOnly */, false /* force */); 13031 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13032 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 13033 String msg = "Extracking package failed for " + pkgName; 13034 res.setError(INSTALL_FAILED_DEXOPT, msg); 13035 return; 13036 } 13037 } 13038 } 13039 13040 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 13041 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 13042 return; 13043 } 13044 13045 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 13046 13047 if (replace) { 13048 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 13049 installerPackageName, volumeUuid, res); 13050 } else { 13051 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 13052 args.user, installerPackageName, volumeUuid, res); 13053 } 13054 synchronized (mPackages) { 13055 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13056 if (ps != null) { 13057 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13058 } 13059 } 13060 } 13061 13062 private void startIntentFilterVerifications(int userId, boolean replacing, 13063 PackageParser.Package pkg) { 13064 if (mIntentFilterVerifierComponent == null) { 13065 Slog.w(TAG, "No IntentFilter verification will not be done as " 13066 + "there is no IntentFilterVerifier available!"); 13067 return; 13068 } 13069 13070 final int verifierUid = getPackageUid( 13071 mIntentFilterVerifierComponent.getPackageName(), 13072 MATCH_DEBUG_TRIAGED_MISSING, 13073 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 13074 13075 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 13076 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 13077 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 13078 mHandler.sendMessage(msg); 13079 } 13080 13081 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 13082 PackageParser.Package pkg) { 13083 int size = pkg.activities.size(); 13084 if (size == 0) { 13085 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13086 "No activity, so no need to verify any IntentFilter!"); 13087 return; 13088 } 13089 13090 final boolean hasDomainURLs = hasDomainURLs(pkg); 13091 if (!hasDomainURLs) { 13092 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13093 "No domain URLs, so no need to verify any IntentFilter!"); 13094 return; 13095 } 13096 13097 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 13098 + " if any IntentFilter from the " + size 13099 + " Activities needs verification ..."); 13100 13101 int count = 0; 13102 final String packageName = pkg.packageName; 13103 13104 synchronized (mPackages) { 13105 // If this is a new install and we see that we've already run verification for this 13106 // package, we have nothing to do: it means the state was restored from backup. 13107 if (!replacing) { 13108 IntentFilterVerificationInfo ivi = 13109 mSettings.getIntentFilterVerificationLPr(packageName); 13110 if (ivi != null) { 13111 if (DEBUG_DOMAIN_VERIFICATION) { 13112 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 13113 + ivi.getStatusString()); 13114 } 13115 return; 13116 } 13117 } 13118 13119 // If any filters need to be verified, then all need to be. 13120 boolean needToVerify = false; 13121 for (PackageParser.Activity a : pkg.activities) { 13122 for (ActivityIntentInfo filter : a.intents) { 13123 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 13124 if (DEBUG_DOMAIN_VERIFICATION) { 13125 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 13126 } 13127 needToVerify = true; 13128 break; 13129 } 13130 } 13131 } 13132 13133 if (needToVerify) { 13134 final int verificationId = mIntentFilterVerificationToken++; 13135 for (PackageParser.Activity a : pkg.activities) { 13136 for (ActivityIntentInfo filter : a.intents) { 13137 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 13138 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13139 "Verification needed for IntentFilter:" + filter.toString()); 13140 mIntentFilterVerifier.addOneIntentFilterVerification( 13141 verifierUid, userId, verificationId, filter, packageName); 13142 count++; 13143 } 13144 } 13145 } 13146 } 13147 } 13148 13149 if (count > 0) { 13150 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 13151 + " IntentFilter verification" + (count > 1 ? "s" : "") 13152 + " for userId:" + userId); 13153 mIntentFilterVerifier.startVerifications(userId); 13154 } else { 13155 if (DEBUG_DOMAIN_VERIFICATION) { 13156 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 13157 } 13158 } 13159 } 13160 13161 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 13162 final ComponentName cn = filter.activity.getComponentName(); 13163 final String packageName = cn.getPackageName(); 13164 13165 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 13166 packageName); 13167 if (ivi == null) { 13168 return true; 13169 } 13170 int status = ivi.getStatus(); 13171 switch (status) { 13172 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 13173 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 13174 return true; 13175 13176 default: 13177 // Nothing to do 13178 return false; 13179 } 13180 } 13181 13182 private static boolean isMultiArch(ApplicationInfo info) { 13183 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 13184 } 13185 13186 private static boolean isExternal(PackageParser.Package pkg) { 13187 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13188 } 13189 13190 private static boolean isExternal(PackageSetting ps) { 13191 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13192 } 13193 13194 private static boolean isEphemeral(PackageParser.Package pkg) { 13195 return pkg.applicationInfo.isEphemeralApp(); 13196 } 13197 13198 private static boolean isEphemeral(PackageSetting ps) { 13199 return ps.pkg != null && isEphemeral(ps.pkg); 13200 } 13201 13202 private static boolean isSystemApp(PackageParser.Package pkg) { 13203 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 13204 } 13205 13206 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 13207 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 13208 } 13209 13210 private static boolean hasDomainURLs(PackageParser.Package pkg) { 13211 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 13212 } 13213 13214 private static boolean isSystemApp(PackageSetting ps) { 13215 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 13216 } 13217 13218 private static boolean isUpdatedSystemApp(PackageSetting ps) { 13219 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 13220 } 13221 13222 private int packageFlagsToInstallFlags(PackageSetting ps) { 13223 int installFlags = 0; 13224 if (isEphemeral(ps)) { 13225 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13226 } 13227 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 13228 // This existing package was an external ASEC install when we have 13229 // the external flag without a UUID 13230 installFlags |= PackageManager.INSTALL_EXTERNAL; 13231 } 13232 if (ps.isForwardLocked()) { 13233 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13234 } 13235 return installFlags; 13236 } 13237 13238 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 13239 if (isExternal(pkg)) { 13240 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13241 return StorageManager.UUID_PRIMARY_PHYSICAL; 13242 } else { 13243 return pkg.volumeUuid; 13244 } 13245 } else { 13246 return StorageManager.UUID_PRIVATE_INTERNAL; 13247 } 13248 } 13249 13250 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 13251 if (isExternal(pkg)) { 13252 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13253 return mSettings.getExternalVersion(); 13254 } else { 13255 return mSettings.findOrCreateVersion(pkg.volumeUuid); 13256 } 13257 } else { 13258 return mSettings.getInternalVersion(); 13259 } 13260 } 13261 13262 private void deleteTempPackageFiles() { 13263 final FilenameFilter filter = new FilenameFilter() { 13264 public boolean accept(File dir, String name) { 13265 return name.startsWith("vmdl") && name.endsWith(".tmp"); 13266 } 13267 }; 13268 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 13269 file.delete(); 13270 } 13271 } 13272 13273 @Override 13274 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 13275 int flags) { 13276 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 13277 flags); 13278 } 13279 13280 @Override 13281 public void deletePackage(final String packageName, 13282 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 13283 mContext.enforceCallingOrSelfPermission( 13284 android.Manifest.permission.DELETE_PACKAGES, null); 13285 Preconditions.checkNotNull(packageName); 13286 Preconditions.checkNotNull(observer); 13287 final int uid = Binder.getCallingUid(); 13288 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 13289 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 13290 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 13291 mContext.enforceCallingOrSelfPermission( 13292 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 13293 "deletePackage for user " + userId); 13294 } 13295 13296 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 13297 try { 13298 observer.onPackageDeleted(packageName, 13299 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 13300 } catch (RemoteException re) { 13301 } 13302 return; 13303 } 13304 13305 for (int currentUserId : users) { 13306 if (getBlockUninstallForUser(packageName, currentUserId)) { 13307 try { 13308 observer.onPackageDeleted(packageName, 13309 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 13310 } catch (RemoteException re) { 13311 } 13312 return; 13313 } 13314 } 13315 13316 if (DEBUG_REMOVE) { 13317 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 13318 } 13319 // Queue up an async operation since the package deletion may take a little while. 13320 mHandler.post(new Runnable() { 13321 public void run() { 13322 mHandler.removeCallbacks(this); 13323 final int returnCode = deletePackageX(packageName, userId, flags); 13324 try { 13325 observer.onPackageDeleted(packageName, returnCode, null); 13326 } catch (RemoteException e) { 13327 Log.i(TAG, "Observer no longer exists."); 13328 } //end catch 13329 } //end run 13330 }); 13331 } 13332 13333 private boolean isPackageDeviceAdmin(String packageName, int userId) { 13334 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13335 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13336 try { 13337 if (dpm != null) { 13338 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 13339 /* callingUserOnly =*/ false); 13340 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 13341 : deviceOwnerComponentName.getPackageName(); 13342 // Does the package contains the device owner? 13343 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 13344 // this check is probably not needed, since DO should be registered as a device 13345 // admin on some user too. (Original bug for this: b/17657954) 13346 if (packageName.equals(deviceOwnerPackageName)) { 13347 return true; 13348 } 13349 // Does it contain a device admin for any user? 13350 int[] users; 13351 if (userId == UserHandle.USER_ALL) { 13352 users = sUserManager.getUserIds(); 13353 } else { 13354 users = new int[]{userId}; 13355 } 13356 for (int i = 0; i < users.length; ++i) { 13357 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 13358 return true; 13359 } 13360 } 13361 } 13362 } catch (RemoteException e) { 13363 } 13364 return false; 13365 } 13366 13367 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 13368 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 13369 } 13370 13371 /** 13372 * This method is an internal method that could be get invoked either 13373 * to delete an installed package or to clean up a failed installation. 13374 * After deleting an installed package, a broadcast is sent to notify any 13375 * listeners that the package has been installed. For cleaning up a failed 13376 * installation, the broadcast is not necessary since the package's 13377 * installation wouldn't have sent the initial broadcast either 13378 * The key steps in deleting a package are 13379 * deleting the package information in internal structures like mPackages, 13380 * deleting the packages base directories through installd 13381 * updating mSettings to reflect current status 13382 * persisting settings for later use 13383 * sending a broadcast if necessary 13384 */ 13385 private int deletePackageX(String packageName, int userId, int flags) { 13386 final PackageRemovedInfo info = new PackageRemovedInfo(); 13387 final boolean res; 13388 13389 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 13390 ? UserHandle.ALL : new UserHandle(userId); 13391 13392 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 13393 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 13394 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 13395 } 13396 13397 boolean removedForAllUsers = false; 13398 boolean systemUpdate = false; 13399 13400 PackageParser.Package uninstalledPkg; 13401 13402 // for the uninstall-updates case and restricted profiles, remember the per- 13403 // userhandle installed state 13404 int[] allUsers; 13405 boolean[] perUserInstalled; 13406 synchronized (mPackages) { 13407 uninstalledPkg = mPackages.get(packageName); 13408 PackageSetting ps = mSettings.mPackages.get(packageName); 13409 allUsers = sUserManager.getUserIds(); 13410 perUserInstalled = new boolean[allUsers.length]; 13411 for (int i = 0; i < allUsers.length; i++) { 13412 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 13413 } 13414 } 13415 13416 synchronized (mInstallLock) { 13417 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 13418 res = deletePackageLI(packageName, removeForUser, 13419 true, allUsers, perUserInstalled, 13420 flags | REMOVE_CHATTY, info, true); 13421 systemUpdate = info.isRemovedPackageSystemUpdate; 13422 synchronized (mPackages) { 13423 if (res) { 13424 if (!systemUpdate && mPackages.get(packageName) == null) { 13425 removedForAllUsers = true; 13426 } 13427 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg); 13428 } 13429 } 13430 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 13431 + " removedForAllUsers=" + removedForAllUsers); 13432 } 13433 13434 if (res) { 13435 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 13436 13437 // If the removed package was a system update, the old system package 13438 // was re-enabled; we need to broadcast this information 13439 if (systemUpdate) { 13440 Bundle extras = new Bundle(1); 13441 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 13442 ? info.removedAppId : info.uid); 13443 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13444 13445 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 13446 extras, 0, null, null, null); 13447 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 13448 extras, 0, null, null, null); 13449 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 13450 null, 0, packageName, null, null); 13451 } 13452 } 13453 // Force a gc here. 13454 Runtime.getRuntime().gc(); 13455 // Delete the resources here after sending the broadcast to let 13456 // other processes clean up before deleting resources. 13457 if (info.args != null) { 13458 synchronized (mInstallLock) { 13459 info.args.doPostDeleteLI(true); 13460 } 13461 } 13462 13463 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 13464 } 13465 13466 class PackageRemovedInfo { 13467 String removedPackage; 13468 int uid = -1; 13469 int removedAppId = -1; 13470 int[] removedUsers = null; 13471 boolean isRemovedPackageSystemUpdate = false; 13472 // Clean up resources deleted packages. 13473 InstallArgs args = null; 13474 13475 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 13476 Bundle extras = new Bundle(1); 13477 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 13478 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 13479 if (replacing) { 13480 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13481 } 13482 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 13483 if (removedPackage != null) { 13484 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 13485 extras, 0, null, null, removedUsers); 13486 if (fullRemove && !replacing) { 13487 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 13488 extras, 0, null, null, removedUsers); 13489 } 13490 } 13491 if (removedAppId >= 0) { 13492 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 13493 removedUsers); 13494 } 13495 } 13496 } 13497 13498 /* 13499 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 13500 * flag is not set, the data directory is removed as well. 13501 * make sure this flag is set for partially installed apps. If not its meaningless to 13502 * delete a partially installed application. 13503 */ 13504 private void removePackageDataLI(PackageSetting ps, 13505 int[] allUserHandles, boolean[] perUserInstalled, 13506 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 13507 String packageName = ps.name; 13508 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 13509 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 13510 // Retrieve object to delete permissions for shared user later on 13511 final PackageSetting deletedPs; 13512 // reader 13513 synchronized (mPackages) { 13514 deletedPs = mSettings.mPackages.get(packageName); 13515 if (outInfo != null) { 13516 outInfo.removedPackage = packageName; 13517 outInfo.removedUsers = deletedPs != null 13518 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 13519 : null; 13520 } 13521 } 13522 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13523 removeDataDirsLI(ps.volumeUuid, packageName); 13524 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 13525 } 13526 // writer 13527 synchronized (mPackages) { 13528 if (deletedPs != null) { 13529 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13530 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 13531 clearDefaultBrowserIfNeeded(packageName); 13532 if (outInfo != null) { 13533 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 13534 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 13535 } 13536 updatePermissionsLPw(deletedPs.name, null, 0); 13537 if (deletedPs.sharedUser != null) { 13538 // Remove permissions associated with package. Since runtime 13539 // permissions are per user we have to kill the removed package 13540 // or packages running under the shared user of the removed 13541 // package if revoking the permissions requested only by the removed 13542 // package is successful and this causes a change in gids. 13543 for (int userId : UserManagerService.getInstance().getUserIds()) { 13544 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 13545 userId); 13546 if (userIdToKill == UserHandle.USER_ALL 13547 || userIdToKill >= UserHandle.USER_SYSTEM) { 13548 // If gids changed for this user, kill all affected packages. 13549 mHandler.post(new Runnable() { 13550 @Override 13551 public void run() { 13552 // This has to happen with no lock held. 13553 killApplication(deletedPs.name, deletedPs.appId, 13554 KILL_APP_REASON_GIDS_CHANGED); 13555 } 13556 }); 13557 break; 13558 } 13559 } 13560 } 13561 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 13562 } 13563 // make sure to preserve per-user disabled state if this removal was just 13564 // a downgrade of a system app to the factory package 13565 if (allUserHandles != null && perUserInstalled != null) { 13566 if (DEBUG_REMOVE) { 13567 Slog.d(TAG, "Propagating install state across downgrade"); 13568 } 13569 for (int i = 0; i < allUserHandles.length; i++) { 13570 if (DEBUG_REMOVE) { 13571 Slog.d(TAG, " user " + allUserHandles[i] 13572 + " => " + perUserInstalled[i]); 13573 } 13574 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13575 } 13576 } 13577 } 13578 // can downgrade to reader 13579 if (writeSettings) { 13580 // Save settings now 13581 mSettings.writeLPr(); 13582 } 13583 } 13584 if (outInfo != null) { 13585 // A user ID was deleted here. Go through all users and remove it 13586 // from KeyStore. 13587 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 13588 } 13589 } 13590 13591 static boolean locationIsPrivileged(File path) { 13592 try { 13593 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 13594 .getCanonicalPath(); 13595 return path.getCanonicalPath().startsWith(privilegedAppDir); 13596 } catch (IOException e) { 13597 Slog.e(TAG, "Unable to access code path " + path); 13598 } 13599 return false; 13600 } 13601 13602 /* 13603 * Tries to delete system package. 13604 */ 13605 private boolean deleteSystemPackageLI(PackageSetting newPs, 13606 int[] allUserHandles, boolean[] perUserInstalled, 13607 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 13608 final boolean applyUserRestrictions 13609 = (allUserHandles != null) && (perUserInstalled != null); 13610 PackageSetting disabledPs = null; 13611 // Confirm if the system package has been updated 13612 // An updated system app can be deleted. This will also have to restore 13613 // the system pkg from system partition 13614 // reader 13615 synchronized (mPackages) { 13616 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13617 } 13618 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13619 + " disabledPs=" + disabledPs); 13620 if (disabledPs == null) { 13621 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13622 return false; 13623 } else if (DEBUG_REMOVE) { 13624 Slog.d(TAG, "Deleting system pkg from data partition"); 13625 } 13626 if (DEBUG_REMOVE) { 13627 if (applyUserRestrictions) { 13628 Slog.d(TAG, "Remembering install states:"); 13629 for (int i = 0; i < allUserHandles.length; i++) { 13630 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13631 } 13632 } 13633 } 13634 // Delete the updated package 13635 outInfo.isRemovedPackageSystemUpdate = true; 13636 if (disabledPs.versionCode < newPs.versionCode) { 13637 // Delete data for downgrades 13638 flags &= ~PackageManager.DELETE_KEEP_DATA; 13639 } else { 13640 // Preserve data by setting flag 13641 flags |= PackageManager.DELETE_KEEP_DATA; 13642 } 13643 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13644 allUserHandles, perUserInstalled, outInfo, writeSettings); 13645 if (!ret) { 13646 return false; 13647 } 13648 // writer 13649 synchronized (mPackages) { 13650 // Reinstate the old system package 13651 mSettings.enableSystemPackageLPw(newPs.name); 13652 // Remove any native libraries from the upgraded package. 13653 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13654 } 13655 // Install the system package 13656 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13657 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13658 if (locationIsPrivileged(disabledPs.codePath)) { 13659 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13660 } 13661 13662 final PackageParser.Package newPkg; 13663 try { 13664 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 13665 } catch (PackageManagerException e) { 13666 Slog.w(TAG, "Failed to restore system package " + newPs.name + ": " + e.getMessage()); 13667 return false; 13668 } 13669 13670 prepareAppDataAfterInstall(newPkg); 13671 13672 // writer 13673 synchronized (mPackages) { 13674 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13675 13676 // Propagate the permissions state as we do not want to drop on the floor 13677 // runtime permissions. The update permissions method below will take 13678 // care of removing obsolete permissions and grant install permissions. 13679 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13680 updatePermissionsLPw(newPkg.packageName, newPkg, 13681 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13682 13683 if (applyUserRestrictions) { 13684 if (DEBUG_REMOVE) { 13685 Slog.d(TAG, "Propagating install state across reinstall"); 13686 } 13687 for (int i = 0; i < allUserHandles.length; i++) { 13688 if (DEBUG_REMOVE) { 13689 Slog.d(TAG, " user " + allUserHandles[i] 13690 + " => " + perUserInstalled[i]); 13691 } 13692 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13693 13694 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13695 } 13696 // Regardless of writeSettings we need to ensure that this restriction 13697 // state propagation is persisted 13698 mSettings.writeAllUsersPackageRestrictionsLPr(); 13699 } 13700 // can downgrade to reader here 13701 if (writeSettings) { 13702 mSettings.writeLPr(); 13703 } 13704 } 13705 return true; 13706 } 13707 13708 private boolean deleteInstalledPackageLI(PackageSetting ps, 13709 boolean deleteCodeAndResources, int flags, 13710 int[] allUserHandles, boolean[] perUserInstalled, 13711 PackageRemovedInfo outInfo, boolean writeSettings) { 13712 if (outInfo != null) { 13713 outInfo.uid = ps.appId; 13714 } 13715 13716 // Delete package data from internal structures and also remove data if flag is set 13717 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13718 13719 // Delete application code and resources 13720 if (deleteCodeAndResources && (outInfo != null)) { 13721 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13722 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13723 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13724 } 13725 return true; 13726 } 13727 13728 @Override 13729 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13730 int userId) { 13731 mContext.enforceCallingOrSelfPermission( 13732 android.Manifest.permission.DELETE_PACKAGES, null); 13733 synchronized (mPackages) { 13734 PackageSetting ps = mSettings.mPackages.get(packageName); 13735 if (ps == null) { 13736 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13737 return false; 13738 } 13739 if (!ps.getInstalled(userId)) { 13740 // Can't block uninstall for an app that is not installed or enabled. 13741 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13742 return false; 13743 } 13744 ps.setBlockUninstall(blockUninstall, userId); 13745 mSettings.writePackageRestrictionsLPr(userId); 13746 } 13747 return true; 13748 } 13749 13750 @Override 13751 public boolean getBlockUninstallForUser(String packageName, int userId) { 13752 synchronized (mPackages) { 13753 PackageSetting ps = mSettings.mPackages.get(packageName); 13754 if (ps == null) { 13755 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13756 return false; 13757 } 13758 return ps.getBlockUninstall(userId); 13759 } 13760 } 13761 13762 @Override 13763 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 13764 int callingUid = Binder.getCallingUid(); 13765 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 13766 throw new SecurityException( 13767 "setRequiredForSystemUser can only be run by the system or root"); 13768 } 13769 synchronized (mPackages) { 13770 PackageSetting ps = mSettings.mPackages.get(packageName); 13771 if (ps == null) { 13772 Log.w(TAG, "Package doesn't exist: " + packageName); 13773 return false; 13774 } 13775 if (systemUserApp) { 13776 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 13777 } else { 13778 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 13779 } 13780 mSettings.writeLPr(); 13781 } 13782 return true; 13783 } 13784 13785 /* 13786 * This method handles package deletion in general 13787 */ 13788 private boolean deletePackageLI(String packageName, UserHandle user, 13789 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13790 int flags, PackageRemovedInfo outInfo, 13791 boolean writeSettings) { 13792 if (packageName == null) { 13793 Slog.w(TAG, "Attempt to delete null packageName."); 13794 return false; 13795 } 13796 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13797 PackageSetting ps; 13798 boolean dataOnly = false; 13799 int removeUser = -1; 13800 int appId = -1; 13801 synchronized (mPackages) { 13802 ps = mSettings.mPackages.get(packageName); 13803 if (ps == null) { 13804 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13805 return false; 13806 } 13807 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13808 && user.getIdentifier() != UserHandle.USER_ALL) { 13809 // The caller is asking that the package only be deleted for a single 13810 // user. To do this, we just mark its uninstalled state and delete 13811 // its data. If this is a system app, we only allow this to happen if 13812 // they have set the special DELETE_SYSTEM_APP which requests different 13813 // semantics than normal for uninstalling system apps. 13814 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13815 final int userId = user.getIdentifier(); 13816 ps.setUserState(userId, 13817 COMPONENT_ENABLED_STATE_DEFAULT, 13818 false, //installed 13819 true, //stopped 13820 true, //notLaunched 13821 false, //hidden 13822 false, //suspended 13823 null, null, null, 13824 false, // blockUninstall 13825 ps.readUserState(userId).domainVerificationStatus, 0); 13826 if (!isSystemApp(ps)) { 13827 // Do not uninstall the APK if an app should be cached 13828 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 13829 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 13830 // Other user still have this package installed, so all 13831 // we need to do is clear this user's data and save that 13832 // it is uninstalled. 13833 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13834 removeUser = user.getIdentifier(); 13835 appId = ps.appId; 13836 scheduleWritePackageRestrictionsLocked(removeUser); 13837 } else { 13838 // We need to set it back to 'installed' so the uninstall 13839 // broadcasts will be sent correctly. 13840 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13841 ps.setInstalled(true, user.getIdentifier()); 13842 } 13843 } else { 13844 // This is a system app, so we assume that the 13845 // other users still have this package installed, so all 13846 // we need to do is clear this user's data and save that 13847 // it is uninstalled. 13848 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13849 removeUser = user.getIdentifier(); 13850 appId = ps.appId; 13851 scheduleWritePackageRestrictionsLocked(removeUser); 13852 } 13853 } 13854 } 13855 13856 if (removeUser >= 0) { 13857 // From above, we determined that we are deleting this only 13858 // for a single user. Continue the work here. 13859 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13860 if (outInfo != null) { 13861 outInfo.removedPackage = packageName; 13862 outInfo.removedAppId = appId; 13863 outInfo.removedUsers = new int[] {removeUser}; 13864 } 13865 // TODO: triage flags as part of 26466827 13866 final int installerFlags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 13867 try { 13868 mInstaller.destroyAppData(ps.volumeUuid, packageName, removeUser, installerFlags); 13869 } catch (InstallerException e) { 13870 Slog.w(TAG, "Failed to delete app data", e); 13871 } 13872 removeKeystoreDataIfNeeded(removeUser, appId); 13873 schedulePackageCleaning(packageName, removeUser, false); 13874 synchronized (mPackages) { 13875 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13876 scheduleWritePackageRestrictionsLocked(removeUser); 13877 } 13878 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13879 } 13880 return true; 13881 } 13882 13883 if (dataOnly) { 13884 // Delete application data first 13885 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13886 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13887 return true; 13888 } 13889 13890 boolean ret = false; 13891 if (isSystemApp(ps)) { 13892 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 13893 // When an updated system application is deleted we delete the existing resources as well and 13894 // fall back to existing code in system partition 13895 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13896 flags, outInfo, writeSettings); 13897 } else { 13898 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 13899 // Kill application pre-emptively especially for apps on sd. 13900 killApplication(packageName, ps.appId, "uninstall pkg"); 13901 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13902 allUserHandles, perUserInstalled, 13903 outInfo, writeSettings); 13904 } 13905 13906 return ret; 13907 } 13908 13909 private final static class ClearStorageConnection implements ServiceConnection { 13910 IMediaContainerService mContainerService; 13911 13912 @Override 13913 public void onServiceConnected(ComponentName name, IBinder service) { 13914 synchronized (this) { 13915 mContainerService = IMediaContainerService.Stub.asInterface(service); 13916 notifyAll(); 13917 } 13918 } 13919 13920 @Override 13921 public void onServiceDisconnected(ComponentName name) { 13922 } 13923 } 13924 13925 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13926 final boolean mounted; 13927 if (Environment.isExternalStorageEmulated()) { 13928 mounted = true; 13929 } else { 13930 final String status = Environment.getExternalStorageState(); 13931 13932 mounted = status.equals(Environment.MEDIA_MOUNTED) 13933 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13934 } 13935 13936 if (!mounted) { 13937 return; 13938 } 13939 13940 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13941 int[] users; 13942 if (userId == UserHandle.USER_ALL) { 13943 users = sUserManager.getUserIds(); 13944 } else { 13945 users = new int[] { userId }; 13946 } 13947 final ClearStorageConnection conn = new ClearStorageConnection(); 13948 if (mContext.bindServiceAsUser( 13949 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 13950 try { 13951 for (int curUser : users) { 13952 long timeout = SystemClock.uptimeMillis() + 5000; 13953 synchronized (conn) { 13954 long now = SystemClock.uptimeMillis(); 13955 while (conn.mContainerService == null && now < timeout) { 13956 try { 13957 conn.wait(timeout - now); 13958 } catch (InterruptedException e) { 13959 } 13960 } 13961 } 13962 if (conn.mContainerService == null) { 13963 return; 13964 } 13965 13966 final UserEnvironment userEnv = new UserEnvironment(curUser); 13967 clearDirectory(conn.mContainerService, 13968 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13969 if (allData) { 13970 clearDirectory(conn.mContainerService, 13971 userEnv.buildExternalStorageAppDataDirs(packageName)); 13972 clearDirectory(conn.mContainerService, 13973 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13974 } 13975 } 13976 } finally { 13977 mContext.unbindService(conn); 13978 } 13979 } 13980 } 13981 13982 @Override 13983 public void clearApplicationUserData(final String packageName, 13984 final IPackageDataObserver observer, final int userId) { 13985 mContext.enforceCallingOrSelfPermission( 13986 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13987 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13988 // Queue up an async operation since the package deletion may take a little while. 13989 mHandler.post(new Runnable() { 13990 public void run() { 13991 mHandler.removeCallbacks(this); 13992 final boolean succeeded; 13993 synchronized (mInstallLock) { 13994 succeeded = clearApplicationUserDataLI(packageName, userId); 13995 } 13996 clearExternalStorageDataSync(packageName, userId, true); 13997 if (succeeded) { 13998 // invoke DeviceStorageMonitor's update method to clear any notifications 13999 DeviceStorageMonitorInternal 14000 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 14001 if (dsm != null) { 14002 dsm.checkMemory(); 14003 } 14004 } 14005 if(observer != null) { 14006 try { 14007 observer.onRemoveCompleted(packageName, succeeded); 14008 } catch (RemoteException e) { 14009 Log.i(TAG, "Observer no longer exists."); 14010 } 14011 } //end if observer 14012 } //end run 14013 }); 14014 } 14015 14016 private boolean clearApplicationUserDataLI(String packageName, int userId) { 14017 if (packageName == null) { 14018 Slog.w(TAG, "Attempt to delete null packageName."); 14019 return false; 14020 } 14021 14022 // Try finding details about the requested package 14023 PackageParser.Package pkg; 14024 synchronized (mPackages) { 14025 pkg = mPackages.get(packageName); 14026 if (pkg == null) { 14027 final PackageSetting ps = mSettings.mPackages.get(packageName); 14028 if (ps != null) { 14029 pkg = ps.pkg; 14030 } 14031 } 14032 14033 if (pkg == null) { 14034 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 14035 return false; 14036 } 14037 14038 PackageSetting ps = (PackageSetting) pkg.mExtras; 14039 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 14040 } 14041 14042 // Always delete data directories for package, even if we found no other 14043 // record of app. This helps users recover from UID mismatches without 14044 // resorting to a full data wipe. 14045 // TODO: triage flags as part of 26466827 14046 final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 14047 try { 14048 mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags); 14049 } catch (InstallerException e) { 14050 Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e); 14051 return false; 14052 } 14053 14054 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 14055 removeKeystoreDataIfNeeded(userId, appId); 14056 14057 // Create a native library symlink only if we have native libraries 14058 // and if the native libraries are 32 bit libraries. We do not provide 14059 // this symlink for 64 bit libraries. 14060 if (pkg.applicationInfo.primaryCpuAbi != null && 14061 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 14062 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 14063 try { 14064 mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 14065 nativeLibPath, userId); 14066 } catch (InstallerException e) { 14067 Slog.w(TAG, "Failed linking native library dir", e); 14068 return false; 14069 } 14070 } 14071 14072 return true; 14073 } 14074 14075 /** 14076 * Reverts user permission state changes (permissions and flags) in 14077 * all packages for a given user. 14078 * 14079 * @param userId The device user for which to do a reset. 14080 */ 14081 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 14082 final int packageCount = mPackages.size(); 14083 for (int i = 0; i < packageCount; i++) { 14084 PackageParser.Package pkg = mPackages.valueAt(i); 14085 PackageSetting ps = (PackageSetting) pkg.mExtras; 14086 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 14087 } 14088 } 14089 14090 /** 14091 * Reverts user permission state changes (permissions and flags). 14092 * 14093 * @param ps The package for which to reset. 14094 * @param userId The device user for which to do a reset. 14095 */ 14096 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 14097 final PackageSetting ps, final int userId) { 14098 if (ps.pkg == null) { 14099 return; 14100 } 14101 14102 // These are flags that can change base on user actions. 14103 final int userSettableMask = FLAG_PERMISSION_USER_SET 14104 | FLAG_PERMISSION_USER_FIXED 14105 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 14106 | FLAG_PERMISSION_REVIEW_REQUIRED; 14107 14108 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 14109 | FLAG_PERMISSION_POLICY_FIXED; 14110 14111 boolean writeInstallPermissions = false; 14112 boolean writeRuntimePermissions = false; 14113 14114 final int permissionCount = ps.pkg.requestedPermissions.size(); 14115 for (int i = 0; i < permissionCount; i++) { 14116 String permission = ps.pkg.requestedPermissions.get(i); 14117 14118 BasePermission bp = mSettings.mPermissions.get(permission); 14119 if (bp == null) { 14120 continue; 14121 } 14122 14123 // If shared user we just reset the state to which only this app contributed. 14124 if (ps.sharedUser != null) { 14125 boolean used = false; 14126 final int packageCount = ps.sharedUser.packages.size(); 14127 for (int j = 0; j < packageCount; j++) { 14128 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 14129 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 14130 && pkg.pkg.requestedPermissions.contains(permission)) { 14131 used = true; 14132 break; 14133 } 14134 } 14135 if (used) { 14136 continue; 14137 } 14138 } 14139 14140 PermissionsState permissionsState = ps.getPermissionsState(); 14141 14142 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 14143 14144 // Always clear the user settable flags. 14145 final boolean hasInstallState = permissionsState.getInstallPermissionState( 14146 bp.name) != null; 14147 // If permission review is enabled and this is a legacy app, mark the 14148 // permission as requiring a review as this is the initial state. 14149 int flags = 0; 14150 if (Build.PERMISSIONS_REVIEW_REQUIRED 14151 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 14152 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 14153 } 14154 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 14155 if (hasInstallState) { 14156 writeInstallPermissions = true; 14157 } else { 14158 writeRuntimePermissions = true; 14159 } 14160 } 14161 14162 // Below is only runtime permission handling. 14163 if (!bp.isRuntime()) { 14164 continue; 14165 } 14166 14167 // Never clobber system or policy. 14168 if ((oldFlags & policyOrSystemFlags) != 0) { 14169 continue; 14170 } 14171 14172 // If this permission was granted by default, make sure it is. 14173 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 14174 if (permissionsState.grantRuntimePermission(bp, userId) 14175 != PERMISSION_OPERATION_FAILURE) { 14176 writeRuntimePermissions = true; 14177 } 14178 // If permission review is enabled the permissions for a legacy apps 14179 // are represented as constantly granted runtime ones, so don't revoke. 14180 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 14181 // Otherwise, reset the permission. 14182 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 14183 switch (revokeResult) { 14184 case PERMISSION_OPERATION_SUCCESS: { 14185 writeRuntimePermissions = true; 14186 } break; 14187 14188 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 14189 writeRuntimePermissions = true; 14190 final int appId = ps.appId; 14191 mHandler.post(new Runnable() { 14192 @Override 14193 public void run() { 14194 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 14195 } 14196 }); 14197 } break; 14198 } 14199 } 14200 } 14201 14202 // Synchronously write as we are taking permissions away. 14203 if (writeRuntimePermissions) { 14204 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 14205 } 14206 14207 // Synchronously write as we are taking permissions away. 14208 if (writeInstallPermissions) { 14209 mSettings.writeLPr(); 14210 } 14211 } 14212 14213 /** 14214 * Remove entries from the keystore daemon. Will only remove it if the 14215 * {@code appId} is valid. 14216 */ 14217 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 14218 if (appId < 0) { 14219 return; 14220 } 14221 14222 final KeyStore keyStore = KeyStore.getInstance(); 14223 if (keyStore != null) { 14224 if (userId == UserHandle.USER_ALL) { 14225 for (final int individual : sUserManager.getUserIds()) { 14226 keyStore.clearUid(UserHandle.getUid(individual, appId)); 14227 } 14228 } else { 14229 keyStore.clearUid(UserHandle.getUid(userId, appId)); 14230 } 14231 } else { 14232 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 14233 } 14234 } 14235 14236 @Override 14237 public void deleteApplicationCacheFiles(final String packageName, 14238 final IPackageDataObserver observer) { 14239 mContext.enforceCallingOrSelfPermission( 14240 android.Manifest.permission.DELETE_CACHE_FILES, null); 14241 // Queue up an async operation since the package deletion may take a little while. 14242 final int userId = UserHandle.getCallingUserId(); 14243 mHandler.post(new Runnable() { 14244 public void run() { 14245 mHandler.removeCallbacks(this); 14246 final boolean succeded; 14247 synchronized (mInstallLock) { 14248 succeded = deleteApplicationCacheFilesLI(packageName, userId); 14249 } 14250 clearExternalStorageDataSync(packageName, userId, false); 14251 if (observer != null) { 14252 try { 14253 observer.onRemoveCompleted(packageName, succeded); 14254 } catch (RemoteException e) { 14255 Log.i(TAG, "Observer no longer exists."); 14256 } 14257 } //end if observer 14258 } //end run 14259 }); 14260 } 14261 14262 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 14263 if (packageName == null) { 14264 Slog.w(TAG, "Attempt to delete null packageName."); 14265 return false; 14266 } 14267 PackageParser.Package p; 14268 synchronized (mPackages) { 14269 p = mPackages.get(packageName); 14270 } 14271 if (p == null) { 14272 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14273 return false; 14274 } 14275 final ApplicationInfo applicationInfo = p.applicationInfo; 14276 if (applicationInfo == null) { 14277 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14278 return false; 14279 } 14280 // TODO: triage flags as part of 26466827 14281 final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 14282 try { 14283 mInstaller.clearAppData(p.volumeUuid, packageName, userId, 14284 flags | Installer.FLAG_CLEAR_CACHE_ONLY); 14285 } catch (InstallerException e) { 14286 Slog.w(TAG, "Couldn't remove cache files for package " 14287 + packageName + " u" + userId, e); 14288 return false; 14289 } 14290 return true; 14291 } 14292 14293 @Override 14294 public void getPackageSizeInfo(final String packageName, int userHandle, 14295 final IPackageStatsObserver observer) { 14296 mContext.enforceCallingOrSelfPermission( 14297 android.Manifest.permission.GET_PACKAGE_SIZE, null); 14298 if (packageName == null) { 14299 throw new IllegalArgumentException("Attempt to get size of null packageName"); 14300 } 14301 14302 PackageStats stats = new PackageStats(packageName, userHandle); 14303 14304 /* 14305 * Queue up an async operation since the package measurement may take a 14306 * little while. 14307 */ 14308 Message msg = mHandler.obtainMessage(INIT_COPY); 14309 msg.obj = new MeasureParams(stats, observer); 14310 mHandler.sendMessage(msg); 14311 } 14312 14313 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 14314 PackageStats pStats) { 14315 if (packageName == null) { 14316 Slog.w(TAG, "Attempt to get size of null packageName."); 14317 return false; 14318 } 14319 PackageParser.Package p; 14320 boolean dataOnly = false; 14321 String libDirRoot = null; 14322 String asecPath = null; 14323 PackageSetting ps = null; 14324 synchronized (mPackages) { 14325 p = mPackages.get(packageName); 14326 ps = mSettings.mPackages.get(packageName); 14327 if(p == null) { 14328 dataOnly = true; 14329 if((ps == null) || (ps.pkg == null)) { 14330 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14331 return false; 14332 } 14333 p = ps.pkg; 14334 } 14335 if (ps != null) { 14336 libDirRoot = ps.legacyNativeLibraryPathString; 14337 } 14338 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 14339 final long token = Binder.clearCallingIdentity(); 14340 try { 14341 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 14342 if (secureContainerId != null) { 14343 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 14344 } 14345 } finally { 14346 Binder.restoreCallingIdentity(token); 14347 } 14348 } 14349 } 14350 String publicSrcDir = null; 14351 if(!dataOnly) { 14352 final ApplicationInfo applicationInfo = p.applicationInfo; 14353 if (applicationInfo == null) { 14354 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14355 return false; 14356 } 14357 if (p.isForwardLocked()) { 14358 publicSrcDir = applicationInfo.getBaseResourcePath(); 14359 } 14360 } 14361 // TODO: extend to measure size of split APKs 14362 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 14363 // not just the first level. 14364 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 14365 // just the primary. 14366 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 14367 14368 String apkPath; 14369 File packageDir = new File(p.codePath); 14370 14371 if (packageDir.isDirectory() && p.canHaveOatDir()) { 14372 apkPath = packageDir.getAbsolutePath(); 14373 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 14374 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 14375 libDirRoot = null; 14376 } 14377 } else { 14378 apkPath = p.baseCodePath; 14379 } 14380 14381 // TODO: triage flags as part of 26466827 14382 final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 14383 try { 14384 mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath, 14385 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 14386 } catch (InstallerException e) { 14387 return false; 14388 } 14389 14390 // Fix-up for forward-locked applications in ASEC containers. 14391 if (!isExternal(p)) { 14392 pStats.codeSize += pStats.externalCodeSize; 14393 pStats.externalCodeSize = 0L; 14394 } 14395 14396 return true; 14397 } 14398 14399 14400 @Override 14401 public void addPackageToPreferred(String packageName) { 14402 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 14403 } 14404 14405 @Override 14406 public void removePackageFromPreferred(String packageName) { 14407 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 14408 } 14409 14410 @Override 14411 public List<PackageInfo> getPreferredPackages(int flags) { 14412 return new ArrayList<PackageInfo>(); 14413 } 14414 14415 private int getUidTargetSdkVersionLockedLPr(int uid) { 14416 Object obj = mSettings.getUserIdLPr(uid); 14417 if (obj instanceof SharedUserSetting) { 14418 final SharedUserSetting sus = (SharedUserSetting) obj; 14419 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 14420 final Iterator<PackageSetting> it = sus.packages.iterator(); 14421 while (it.hasNext()) { 14422 final PackageSetting ps = it.next(); 14423 if (ps.pkg != null) { 14424 int v = ps.pkg.applicationInfo.targetSdkVersion; 14425 if (v < vers) vers = v; 14426 } 14427 } 14428 return vers; 14429 } else if (obj instanceof PackageSetting) { 14430 final PackageSetting ps = (PackageSetting) obj; 14431 if (ps.pkg != null) { 14432 return ps.pkg.applicationInfo.targetSdkVersion; 14433 } 14434 } 14435 return Build.VERSION_CODES.CUR_DEVELOPMENT; 14436 } 14437 14438 @Override 14439 public void addPreferredActivity(IntentFilter filter, int match, 14440 ComponentName[] set, ComponentName activity, int userId) { 14441 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14442 "Adding preferred"); 14443 } 14444 14445 private void addPreferredActivityInternal(IntentFilter filter, int match, 14446 ComponentName[] set, ComponentName activity, boolean always, int userId, 14447 String opname) { 14448 // writer 14449 int callingUid = Binder.getCallingUid(); 14450 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 14451 if (filter.countActions() == 0) { 14452 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14453 return; 14454 } 14455 synchronized (mPackages) { 14456 if (mContext.checkCallingOrSelfPermission( 14457 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14458 != PackageManager.PERMISSION_GRANTED) { 14459 if (getUidTargetSdkVersionLockedLPr(callingUid) 14460 < Build.VERSION_CODES.FROYO) { 14461 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 14462 + callingUid); 14463 return; 14464 } 14465 mContext.enforceCallingOrSelfPermission( 14466 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14467 } 14468 14469 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 14470 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 14471 + userId + ":"); 14472 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14473 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 14474 scheduleWritePackageRestrictionsLocked(userId); 14475 } 14476 } 14477 14478 @Override 14479 public void replacePreferredActivity(IntentFilter filter, int match, 14480 ComponentName[] set, ComponentName activity, int userId) { 14481 if (filter.countActions() != 1) { 14482 throw new IllegalArgumentException( 14483 "replacePreferredActivity expects filter to have only 1 action."); 14484 } 14485 if (filter.countDataAuthorities() != 0 14486 || filter.countDataPaths() != 0 14487 || filter.countDataSchemes() > 1 14488 || filter.countDataTypes() != 0) { 14489 throw new IllegalArgumentException( 14490 "replacePreferredActivity expects filter to have no data authorities, " + 14491 "paths, or types; and at most one scheme."); 14492 } 14493 14494 final int callingUid = Binder.getCallingUid(); 14495 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 14496 synchronized (mPackages) { 14497 if (mContext.checkCallingOrSelfPermission( 14498 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14499 != PackageManager.PERMISSION_GRANTED) { 14500 if (getUidTargetSdkVersionLockedLPr(callingUid) 14501 < Build.VERSION_CODES.FROYO) { 14502 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 14503 + Binder.getCallingUid()); 14504 return; 14505 } 14506 mContext.enforceCallingOrSelfPermission( 14507 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14508 } 14509 14510 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14511 if (pir != null) { 14512 // Get all of the existing entries that exactly match this filter. 14513 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 14514 if (existing != null && existing.size() == 1) { 14515 PreferredActivity cur = existing.get(0); 14516 if (DEBUG_PREFERRED) { 14517 Slog.i(TAG, "Checking replace of preferred:"); 14518 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14519 if (!cur.mPref.mAlways) { 14520 Slog.i(TAG, " -- CUR; not mAlways!"); 14521 } else { 14522 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 14523 Slog.i(TAG, " -- CUR: mSet=" 14524 + Arrays.toString(cur.mPref.mSetComponents)); 14525 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 14526 Slog.i(TAG, " -- NEW: mMatch=" 14527 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 14528 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 14529 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 14530 } 14531 } 14532 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 14533 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 14534 && cur.mPref.sameSet(set)) { 14535 // Setting the preferred activity to what it happens to be already 14536 if (DEBUG_PREFERRED) { 14537 Slog.i(TAG, "Replacing with same preferred activity " 14538 + cur.mPref.mShortComponent + " for user " 14539 + userId + ":"); 14540 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14541 } 14542 return; 14543 } 14544 } 14545 14546 if (existing != null) { 14547 if (DEBUG_PREFERRED) { 14548 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 14549 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14550 } 14551 for (int i = 0; i < existing.size(); i++) { 14552 PreferredActivity pa = existing.get(i); 14553 if (DEBUG_PREFERRED) { 14554 Slog.i(TAG, "Removing existing preferred activity " 14555 + pa.mPref.mComponent + ":"); 14556 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 14557 } 14558 pir.removeFilter(pa); 14559 } 14560 } 14561 } 14562 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14563 "Replacing preferred"); 14564 } 14565 } 14566 14567 @Override 14568 public void clearPackagePreferredActivities(String packageName) { 14569 final int uid = Binder.getCallingUid(); 14570 // writer 14571 synchronized (mPackages) { 14572 PackageParser.Package pkg = mPackages.get(packageName); 14573 if (pkg == null || pkg.applicationInfo.uid != uid) { 14574 if (mContext.checkCallingOrSelfPermission( 14575 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14576 != PackageManager.PERMISSION_GRANTED) { 14577 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 14578 < Build.VERSION_CODES.FROYO) { 14579 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 14580 + Binder.getCallingUid()); 14581 return; 14582 } 14583 mContext.enforceCallingOrSelfPermission( 14584 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14585 } 14586 } 14587 14588 int user = UserHandle.getCallingUserId(); 14589 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 14590 scheduleWritePackageRestrictionsLocked(user); 14591 } 14592 } 14593 } 14594 14595 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14596 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 14597 ArrayList<PreferredActivity> removed = null; 14598 boolean changed = false; 14599 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14600 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 14601 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14602 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 14603 continue; 14604 } 14605 Iterator<PreferredActivity> it = pir.filterIterator(); 14606 while (it.hasNext()) { 14607 PreferredActivity pa = it.next(); 14608 // Mark entry for removal only if it matches the package name 14609 // and the entry is of type "always". 14610 if (packageName == null || 14611 (pa.mPref.mComponent.getPackageName().equals(packageName) 14612 && pa.mPref.mAlways)) { 14613 if (removed == null) { 14614 removed = new ArrayList<PreferredActivity>(); 14615 } 14616 removed.add(pa); 14617 } 14618 } 14619 if (removed != null) { 14620 for (int j=0; j<removed.size(); j++) { 14621 PreferredActivity pa = removed.get(j); 14622 pir.removeFilter(pa); 14623 } 14624 changed = true; 14625 } 14626 } 14627 return changed; 14628 } 14629 14630 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14631 private void clearIntentFilterVerificationsLPw(int userId) { 14632 final int packageCount = mPackages.size(); 14633 for (int i = 0; i < packageCount; i++) { 14634 PackageParser.Package pkg = mPackages.valueAt(i); 14635 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 14636 } 14637 } 14638 14639 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14640 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 14641 if (userId == UserHandle.USER_ALL) { 14642 if (mSettings.removeIntentFilterVerificationLPw(packageName, 14643 sUserManager.getUserIds())) { 14644 for (int oneUserId : sUserManager.getUserIds()) { 14645 scheduleWritePackageRestrictionsLocked(oneUserId); 14646 } 14647 } 14648 } else { 14649 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 14650 scheduleWritePackageRestrictionsLocked(userId); 14651 } 14652 } 14653 } 14654 14655 void clearDefaultBrowserIfNeeded(String packageName) { 14656 for (int oneUserId : sUserManager.getUserIds()) { 14657 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 14658 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 14659 if (packageName.equals(defaultBrowserPackageName)) { 14660 setDefaultBrowserPackageName(null, oneUserId); 14661 } 14662 } 14663 } 14664 14665 @Override 14666 public void resetApplicationPreferences(int userId) { 14667 mContext.enforceCallingOrSelfPermission( 14668 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14669 // writer 14670 synchronized (mPackages) { 14671 final long identity = Binder.clearCallingIdentity(); 14672 try { 14673 clearPackagePreferredActivitiesLPw(null, userId); 14674 mSettings.applyDefaultPreferredAppsLPw(this, userId); 14675 // TODO: We have to reset the default SMS and Phone. This requires 14676 // significant refactoring to keep all default apps in the package 14677 // manager (cleaner but more work) or have the services provide 14678 // callbacks to the package manager to request a default app reset. 14679 applyFactoryDefaultBrowserLPw(userId); 14680 clearIntentFilterVerificationsLPw(userId); 14681 primeDomainVerificationsLPw(userId); 14682 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 14683 scheduleWritePackageRestrictionsLocked(userId); 14684 } finally { 14685 Binder.restoreCallingIdentity(identity); 14686 } 14687 } 14688 } 14689 14690 @Override 14691 public int getPreferredActivities(List<IntentFilter> outFilters, 14692 List<ComponentName> outActivities, String packageName) { 14693 14694 int num = 0; 14695 final int userId = UserHandle.getCallingUserId(); 14696 // reader 14697 synchronized (mPackages) { 14698 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14699 if (pir != null) { 14700 final Iterator<PreferredActivity> it = pir.filterIterator(); 14701 while (it.hasNext()) { 14702 final PreferredActivity pa = it.next(); 14703 if (packageName == null 14704 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14705 && pa.mPref.mAlways)) { 14706 if (outFilters != null) { 14707 outFilters.add(new IntentFilter(pa)); 14708 } 14709 if (outActivities != null) { 14710 outActivities.add(pa.mPref.mComponent); 14711 } 14712 } 14713 } 14714 } 14715 } 14716 14717 return num; 14718 } 14719 14720 @Override 14721 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14722 int userId) { 14723 int callingUid = Binder.getCallingUid(); 14724 if (callingUid != Process.SYSTEM_UID) { 14725 throw new SecurityException( 14726 "addPersistentPreferredActivity can only be run by the system"); 14727 } 14728 if (filter.countActions() == 0) { 14729 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14730 return; 14731 } 14732 synchronized (mPackages) { 14733 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14734 ":"); 14735 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14736 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14737 new PersistentPreferredActivity(filter, activity)); 14738 scheduleWritePackageRestrictionsLocked(userId); 14739 } 14740 } 14741 14742 @Override 14743 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14744 int callingUid = Binder.getCallingUid(); 14745 if (callingUid != Process.SYSTEM_UID) { 14746 throw new SecurityException( 14747 "clearPackagePersistentPreferredActivities can only be run by the system"); 14748 } 14749 ArrayList<PersistentPreferredActivity> removed = null; 14750 boolean changed = false; 14751 synchronized (mPackages) { 14752 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14753 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14754 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14755 .valueAt(i); 14756 if (userId != thisUserId) { 14757 continue; 14758 } 14759 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14760 while (it.hasNext()) { 14761 PersistentPreferredActivity ppa = it.next(); 14762 // Mark entry for removal only if it matches the package name. 14763 if (ppa.mComponent.getPackageName().equals(packageName)) { 14764 if (removed == null) { 14765 removed = new ArrayList<PersistentPreferredActivity>(); 14766 } 14767 removed.add(ppa); 14768 } 14769 } 14770 if (removed != null) { 14771 for (int j=0; j<removed.size(); j++) { 14772 PersistentPreferredActivity ppa = removed.get(j); 14773 ppir.removeFilter(ppa); 14774 } 14775 changed = true; 14776 } 14777 } 14778 14779 if (changed) { 14780 scheduleWritePackageRestrictionsLocked(userId); 14781 } 14782 } 14783 } 14784 14785 /** 14786 * Common machinery for picking apart a restored XML blob and passing 14787 * it to a caller-supplied functor to be applied to the running system. 14788 */ 14789 private void restoreFromXml(XmlPullParser parser, int userId, 14790 String expectedStartTag, BlobXmlRestorer functor) 14791 throws IOException, XmlPullParserException { 14792 int type; 14793 while ((type = parser.next()) != XmlPullParser.START_TAG 14794 && type != XmlPullParser.END_DOCUMENT) { 14795 } 14796 if (type != XmlPullParser.START_TAG) { 14797 // oops didn't find a start tag?! 14798 if (DEBUG_BACKUP) { 14799 Slog.e(TAG, "Didn't find start tag during restore"); 14800 } 14801 return; 14802 } 14803Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 14804 // this is supposed to be TAG_PREFERRED_BACKUP 14805 if (!expectedStartTag.equals(parser.getName())) { 14806 if (DEBUG_BACKUP) { 14807 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14808 } 14809 return; 14810 } 14811 14812 // skip interfering stuff, then we're aligned with the backing implementation 14813 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14814Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 14815 functor.apply(parser, userId); 14816 } 14817 14818 private interface BlobXmlRestorer { 14819 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14820 } 14821 14822 /** 14823 * Non-Binder method, support for the backup/restore mechanism: write the 14824 * full set of preferred activities in its canonical XML format. Returns the 14825 * XML output as a byte array, or null if there is none. 14826 */ 14827 @Override 14828 public byte[] getPreferredActivityBackup(int userId) { 14829 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14830 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14831 } 14832 14833 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14834 try { 14835 final XmlSerializer serializer = new FastXmlSerializer(); 14836 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14837 serializer.startDocument(null, true); 14838 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14839 14840 synchronized (mPackages) { 14841 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14842 } 14843 14844 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14845 serializer.endDocument(); 14846 serializer.flush(); 14847 } catch (Exception e) { 14848 if (DEBUG_BACKUP) { 14849 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14850 } 14851 return null; 14852 } 14853 14854 return dataStream.toByteArray(); 14855 } 14856 14857 @Override 14858 public void restorePreferredActivities(byte[] backup, int userId) { 14859 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14860 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14861 } 14862 14863 try { 14864 final XmlPullParser parser = Xml.newPullParser(); 14865 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14866 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14867 new BlobXmlRestorer() { 14868 @Override 14869 public void apply(XmlPullParser parser, int userId) 14870 throws XmlPullParserException, IOException { 14871 synchronized (mPackages) { 14872 mSettings.readPreferredActivitiesLPw(parser, userId); 14873 } 14874 } 14875 } ); 14876 } catch (Exception e) { 14877 if (DEBUG_BACKUP) { 14878 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14879 } 14880 } 14881 } 14882 14883 /** 14884 * Non-Binder method, support for the backup/restore mechanism: write the 14885 * default browser (etc) settings in its canonical XML format. Returns the default 14886 * browser XML representation as a byte array, or null if there is none. 14887 */ 14888 @Override 14889 public byte[] getDefaultAppsBackup(int userId) { 14890 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14891 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14892 } 14893 14894 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14895 try { 14896 final XmlSerializer serializer = new FastXmlSerializer(); 14897 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14898 serializer.startDocument(null, true); 14899 serializer.startTag(null, TAG_DEFAULT_APPS); 14900 14901 synchronized (mPackages) { 14902 mSettings.writeDefaultAppsLPr(serializer, userId); 14903 } 14904 14905 serializer.endTag(null, TAG_DEFAULT_APPS); 14906 serializer.endDocument(); 14907 serializer.flush(); 14908 } catch (Exception e) { 14909 if (DEBUG_BACKUP) { 14910 Slog.e(TAG, "Unable to write default apps for backup", e); 14911 } 14912 return null; 14913 } 14914 14915 return dataStream.toByteArray(); 14916 } 14917 14918 @Override 14919 public void restoreDefaultApps(byte[] backup, int userId) { 14920 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14921 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14922 } 14923 14924 try { 14925 final XmlPullParser parser = Xml.newPullParser(); 14926 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14927 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14928 new BlobXmlRestorer() { 14929 @Override 14930 public void apply(XmlPullParser parser, int userId) 14931 throws XmlPullParserException, IOException { 14932 synchronized (mPackages) { 14933 mSettings.readDefaultAppsLPw(parser, userId); 14934 } 14935 } 14936 } ); 14937 } catch (Exception e) { 14938 if (DEBUG_BACKUP) { 14939 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14940 } 14941 } 14942 } 14943 14944 @Override 14945 public byte[] getIntentFilterVerificationBackup(int userId) { 14946 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14947 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14948 } 14949 14950 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14951 try { 14952 final XmlSerializer serializer = new FastXmlSerializer(); 14953 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14954 serializer.startDocument(null, true); 14955 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14956 14957 synchronized (mPackages) { 14958 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14959 } 14960 14961 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14962 serializer.endDocument(); 14963 serializer.flush(); 14964 } catch (Exception e) { 14965 if (DEBUG_BACKUP) { 14966 Slog.e(TAG, "Unable to write default apps for backup", e); 14967 } 14968 return null; 14969 } 14970 14971 return dataStream.toByteArray(); 14972 } 14973 14974 @Override 14975 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14976 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14977 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14978 } 14979 14980 try { 14981 final XmlPullParser parser = Xml.newPullParser(); 14982 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14983 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14984 new BlobXmlRestorer() { 14985 @Override 14986 public void apply(XmlPullParser parser, int userId) 14987 throws XmlPullParserException, IOException { 14988 synchronized (mPackages) { 14989 mSettings.readAllDomainVerificationsLPr(parser, userId); 14990 mSettings.writeLPr(); 14991 } 14992 } 14993 } ); 14994 } catch (Exception e) { 14995 if (DEBUG_BACKUP) { 14996 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14997 } 14998 } 14999 } 15000 15001 @Override 15002 public byte[] getPermissionGrantBackup(int userId) { 15003 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15004 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 15005 } 15006 15007 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 15008 try { 15009 final XmlSerializer serializer = new FastXmlSerializer(); 15010 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 15011 serializer.startDocument(null, true); 15012 serializer.startTag(null, TAG_PERMISSION_BACKUP); 15013 15014 synchronized (mPackages) { 15015 serializeRuntimePermissionGrantsLPr(serializer, userId); 15016 } 15017 15018 serializer.endTag(null, TAG_PERMISSION_BACKUP); 15019 serializer.endDocument(); 15020 serializer.flush(); 15021 } catch (Exception e) { 15022 if (DEBUG_BACKUP) { 15023 Slog.e(TAG, "Unable to write default apps for backup", e); 15024 } 15025 return null; 15026 } 15027 15028 return dataStream.toByteArray(); 15029 } 15030 15031 @Override 15032 public void restorePermissionGrants(byte[] backup, int userId) { 15033 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15034 throw new SecurityException("Only the system may call restorePermissionGrants()"); 15035 } 15036 15037 try { 15038 final XmlPullParser parser = Xml.newPullParser(); 15039 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 15040 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 15041 new BlobXmlRestorer() { 15042 @Override 15043 public void apply(XmlPullParser parser, int userId) 15044 throws XmlPullParserException, IOException { 15045 synchronized (mPackages) { 15046 processRestoredPermissionGrantsLPr(parser, userId); 15047 } 15048 } 15049 } ); 15050 } catch (Exception e) { 15051 if (DEBUG_BACKUP) { 15052 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 15053 } 15054 } 15055 } 15056 15057 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 15058 throws IOException { 15059 serializer.startTag(null, TAG_ALL_GRANTS); 15060 15061 final int N = mSettings.mPackages.size(); 15062 for (int i = 0; i < N; i++) { 15063 final PackageSetting ps = mSettings.mPackages.valueAt(i); 15064 boolean pkgGrantsKnown = false; 15065 15066 PermissionsState packagePerms = ps.getPermissionsState(); 15067 15068 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 15069 final int grantFlags = state.getFlags(); 15070 // only look at grants that are not system/policy fixed 15071 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 15072 final boolean isGranted = state.isGranted(); 15073 // And only back up the user-twiddled state bits 15074 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 15075 final String packageName = mSettings.mPackages.keyAt(i); 15076 if (!pkgGrantsKnown) { 15077 serializer.startTag(null, TAG_GRANT); 15078 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 15079 pkgGrantsKnown = true; 15080 } 15081 15082 final boolean userSet = 15083 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 15084 final boolean userFixed = 15085 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 15086 final boolean revoke = 15087 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 15088 15089 serializer.startTag(null, TAG_PERMISSION); 15090 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 15091 if (isGranted) { 15092 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 15093 } 15094 if (userSet) { 15095 serializer.attribute(null, ATTR_USER_SET, "true"); 15096 } 15097 if (userFixed) { 15098 serializer.attribute(null, ATTR_USER_FIXED, "true"); 15099 } 15100 if (revoke) { 15101 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 15102 } 15103 serializer.endTag(null, TAG_PERMISSION); 15104 } 15105 } 15106 } 15107 15108 if (pkgGrantsKnown) { 15109 serializer.endTag(null, TAG_GRANT); 15110 } 15111 } 15112 15113 serializer.endTag(null, TAG_ALL_GRANTS); 15114 } 15115 15116 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 15117 throws XmlPullParserException, IOException { 15118 String pkgName = null; 15119 int outerDepth = parser.getDepth(); 15120 int type; 15121 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 15122 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 15123 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 15124 continue; 15125 } 15126 15127 final String tagName = parser.getName(); 15128 if (tagName.equals(TAG_GRANT)) { 15129 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 15130 if (DEBUG_BACKUP) { 15131 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 15132 } 15133 } else if (tagName.equals(TAG_PERMISSION)) { 15134 15135 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 15136 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 15137 15138 int newFlagSet = 0; 15139 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 15140 newFlagSet |= FLAG_PERMISSION_USER_SET; 15141 } 15142 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 15143 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 15144 } 15145 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 15146 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 15147 } 15148 if (DEBUG_BACKUP) { 15149 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 15150 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 15151 } 15152 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15153 if (ps != null) { 15154 // Already installed so we apply the grant immediately 15155 if (DEBUG_BACKUP) { 15156 Slog.v(TAG, " + already installed; applying"); 15157 } 15158 PermissionsState perms = ps.getPermissionsState(); 15159 BasePermission bp = mSettings.mPermissions.get(permName); 15160 if (bp != null) { 15161 if (isGranted) { 15162 perms.grantRuntimePermission(bp, userId); 15163 } 15164 if (newFlagSet != 0) { 15165 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 15166 } 15167 } 15168 } else { 15169 // Need to wait for post-restore install to apply the grant 15170 if (DEBUG_BACKUP) { 15171 Slog.v(TAG, " - not yet installed; saving for later"); 15172 } 15173 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 15174 isGranted, newFlagSet, userId); 15175 } 15176 } else { 15177 PackageManagerService.reportSettingsProblem(Log.WARN, 15178 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 15179 XmlUtils.skipCurrentTag(parser); 15180 } 15181 } 15182 15183 scheduleWriteSettingsLocked(); 15184 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15185 } 15186 15187 @Override 15188 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 15189 int sourceUserId, int targetUserId, int flags) { 15190 mContext.enforceCallingOrSelfPermission( 15191 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 15192 int callingUid = Binder.getCallingUid(); 15193 enforceOwnerRights(ownerPackage, callingUid); 15194 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 15195 if (intentFilter.countActions() == 0) { 15196 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 15197 return; 15198 } 15199 synchronized (mPackages) { 15200 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 15201 ownerPackage, targetUserId, flags); 15202 CrossProfileIntentResolver resolver = 15203 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 15204 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 15205 // We have all those whose filter is equal. Now checking if the rest is equal as well. 15206 if (existing != null) { 15207 int size = existing.size(); 15208 for (int i = 0; i < size; i++) { 15209 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 15210 return; 15211 } 15212 } 15213 } 15214 resolver.addFilter(newFilter); 15215 scheduleWritePackageRestrictionsLocked(sourceUserId); 15216 } 15217 } 15218 15219 @Override 15220 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 15221 mContext.enforceCallingOrSelfPermission( 15222 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 15223 int callingUid = Binder.getCallingUid(); 15224 enforceOwnerRights(ownerPackage, callingUid); 15225 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 15226 synchronized (mPackages) { 15227 CrossProfileIntentResolver resolver = 15228 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 15229 ArraySet<CrossProfileIntentFilter> set = 15230 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 15231 for (CrossProfileIntentFilter filter : set) { 15232 if (filter.getOwnerPackage().equals(ownerPackage)) { 15233 resolver.removeFilter(filter); 15234 } 15235 } 15236 scheduleWritePackageRestrictionsLocked(sourceUserId); 15237 } 15238 } 15239 15240 // Enforcing that callingUid is owning pkg on userId 15241 private void enforceOwnerRights(String pkg, int callingUid) { 15242 // The system owns everything. 15243 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 15244 return; 15245 } 15246 int callingUserId = UserHandle.getUserId(callingUid); 15247 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 15248 if (pi == null) { 15249 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 15250 + callingUserId); 15251 } 15252 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 15253 throw new SecurityException("Calling uid " + callingUid 15254 + " does not own package " + pkg); 15255 } 15256 } 15257 15258 @Override 15259 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 15260 Intent intent = new Intent(Intent.ACTION_MAIN); 15261 intent.addCategory(Intent.CATEGORY_HOME); 15262 15263 final int callingUserId = UserHandle.getCallingUserId(); 15264 List<ResolveInfo> list = queryIntentActivities(intent, null, 15265 PackageManager.GET_META_DATA, callingUserId); 15266 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 15267 true, false, false, callingUserId); 15268 15269 allHomeCandidates.clear(); 15270 if (list != null) { 15271 for (ResolveInfo ri : list) { 15272 allHomeCandidates.add(ri); 15273 } 15274 } 15275 return (preferred == null || preferred.activityInfo == null) 15276 ? null 15277 : new ComponentName(preferred.activityInfo.packageName, 15278 preferred.activityInfo.name); 15279 } 15280 15281 @Override 15282 public void setApplicationEnabledSetting(String appPackageName, 15283 int newState, int flags, int userId, String callingPackage) { 15284 if (!sUserManager.exists(userId)) return; 15285 if (callingPackage == null) { 15286 callingPackage = Integer.toString(Binder.getCallingUid()); 15287 } 15288 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 15289 } 15290 15291 @Override 15292 public void setComponentEnabledSetting(ComponentName componentName, 15293 int newState, int flags, int userId) { 15294 if (!sUserManager.exists(userId)) return; 15295 setEnabledSetting(componentName.getPackageName(), 15296 componentName.getClassName(), newState, flags, userId, null); 15297 } 15298 15299 private void setEnabledSetting(final String packageName, String className, int newState, 15300 final int flags, int userId, String callingPackage) { 15301 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 15302 || newState == COMPONENT_ENABLED_STATE_ENABLED 15303 || newState == COMPONENT_ENABLED_STATE_DISABLED 15304 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 15305 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 15306 throw new IllegalArgumentException("Invalid new component state: " 15307 + newState); 15308 } 15309 PackageSetting pkgSetting; 15310 final int uid = Binder.getCallingUid(); 15311 final int permission = mContext.checkCallingOrSelfPermission( 15312 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 15313 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 15314 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 15315 boolean sendNow = false; 15316 boolean isApp = (className == null); 15317 String componentName = isApp ? packageName : className; 15318 int packageUid = -1; 15319 ArrayList<String> components; 15320 15321 // writer 15322 synchronized (mPackages) { 15323 pkgSetting = mSettings.mPackages.get(packageName); 15324 if (pkgSetting == null) { 15325 if (className == null) { 15326 throw new IllegalArgumentException("Unknown package: " + packageName); 15327 } 15328 throw new IllegalArgumentException( 15329 "Unknown component: " + packageName + "/" + className); 15330 } 15331 // Allow root and verify that userId is not being specified by a different user 15332 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 15333 throw new SecurityException( 15334 "Permission Denial: attempt to change component state from pid=" 15335 + Binder.getCallingPid() 15336 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 15337 } 15338 if (className == null) { 15339 // We're dealing with an application/package level state change 15340 if (pkgSetting.getEnabled(userId) == newState) { 15341 // Nothing to do 15342 return; 15343 } 15344 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 15345 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 15346 // Don't care about who enables an app. 15347 callingPackage = null; 15348 } 15349 pkgSetting.setEnabled(newState, userId, callingPackage); 15350 // pkgSetting.pkg.mSetEnabled = newState; 15351 } else { 15352 // We're dealing with a component level state change 15353 // First, verify that this is a valid class name. 15354 PackageParser.Package pkg = pkgSetting.pkg; 15355 if (pkg == null || !pkg.hasComponentClassName(className)) { 15356 if (pkg != null && 15357 pkg.applicationInfo.targetSdkVersion >= 15358 Build.VERSION_CODES.JELLY_BEAN) { 15359 throw new IllegalArgumentException("Component class " + className 15360 + " does not exist in " + packageName); 15361 } else { 15362 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 15363 + className + " does not exist in " + packageName); 15364 } 15365 } 15366 switch (newState) { 15367 case COMPONENT_ENABLED_STATE_ENABLED: 15368 if (!pkgSetting.enableComponentLPw(className, userId)) { 15369 return; 15370 } 15371 break; 15372 case COMPONENT_ENABLED_STATE_DISABLED: 15373 if (!pkgSetting.disableComponentLPw(className, userId)) { 15374 return; 15375 } 15376 break; 15377 case COMPONENT_ENABLED_STATE_DEFAULT: 15378 if (!pkgSetting.restoreComponentLPw(className, userId)) { 15379 return; 15380 } 15381 break; 15382 default: 15383 Slog.e(TAG, "Invalid new component state: " + newState); 15384 return; 15385 } 15386 } 15387 scheduleWritePackageRestrictionsLocked(userId); 15388 components = mPendingBroadcasts.get(userId, packageName); 15389 final boolean newPackage = components == null; 15390 if (newPackage) { 15391 components = new ArrayList<String>(); 15392 } 15393 if (!components.contains(componentName)) { 15394 components.add(componentName); 15395 } 15396 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 15397 sendNow = true; 15398 // Purge entry from pending broadcast list if another one exists already 15399 // since we are sending one right away. 15400 mPendingBroadcasts.remove(userId, packageName); 15401 } else { 15402 if (newPackage) { 15403 mPendingBroadcasts.put(userId, packageName, components); 15404 } 15405 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 15406 // Schedule a message 15407 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 15408 } 15409 } 15410 } 15411 15412 long callingId = Binder.clearCallingIdentity(); 15413 try { 15414 if (sendNow) { 15415 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 15416 sendPackageChangedBroadcast(packageName, 15417 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 15418 } 15419 } finally { 15420 Binder.restoreCallingIdentity(callingId); 15421 } 15422 } 15423 15424 private void sendPackageChangedBroadcast(String packageName, 15425 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 15426 if (DEBUG_INSTALL) 15427 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 15428 + componentNames); 15429 Bundle extras = new Bundle(4); 15430 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 15431 String nameList[] = new String[componentNames.size()]; 15432 componentNames.toArray(nameList); 15433 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 15434 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 15435 extras.putInt(Intent.EXTRA_UID, packageUid); 15436 // If this is not reporting a change of the overall package, then only send it 15437 // to registered receivers. We don't want to launch a swath of apps for every 15438 // little component state change. 15439 final int flags = !componentNames.contains(packageName) 15440 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 15441 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 15442 new int[] {UserHandle.getUserId(packageUid)}); 15443 } 15444 15445 @Override 15446 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 15447 if (!sUserManager.exists(userId)) return; 15448 final int uid = Binder.getCallingUid(); 15449 final int permission = mContext.checkCallingOrSelfPermission( 15450 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 15451 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 15452 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 15453 // writer 15454 synchronized (mPackages) { 15455 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 15456 allowedByPermission, uid, userId)) { 15457 scheduleWritePackageRestrictionsLocked(userId); 15458 } 15459 } 15460 } 15461 15462 @Override 15463 public String getInstallerPackageName(String packageName) { 15464 // reader 15465 synchronized (mPackages) { 15466 return mSettings.getInstallerPackageNameLPr(packageName); 15467 } 15468 } 15469 15470 @Override 15471 public int getApplicationEnabledSetting(String packageName, int userId) { 15472 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 15473 int uid = Binder.getCallingUid(); 15474 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 15475 // reader 15476 synchronized (mPackages) { 15477 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 15478 } 15479 } 15480 15481 @Override 15482 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 15483 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 15484 int uid = Binder.getCallingUid(); 15485 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 15486 // reader 15487 synchronized (mPackages) { 15488 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 15489 } 15490 } 15491 15492 @Override 15493 public void enterSafeMode() { 15494 enforceSystemOrRoot("Only the system can request entering safe mode"); 15495 15496 if (!mSystemReady) { 15497 mSafeMode = true; 15498 } 15499 } 15500 15501 @Override 15502 public void systemReady() { 15503 mSystemReady = true; 15504 15505 // Read the compatibilty setting when the system is ready. 15506 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 15507 mContext.getContentResolver(), 15508 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 15509 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 15510 if (DEBUG_SETTINGS) { 15511 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 15512 } 15513 15514 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 15515 15516 synchronized (mPackages) { 15517 // Verify that all of the preferred activity components actually 15518 // exist. It is possible for applications to be updated and at 15519 // that point remove a previously declared activity component that 15520 // had been set as a preferred activity. We try to clean this up 15521 // the next time we encounter that preferred activity, but it is 15522 // possible for the user flow to never be able to return to that 15523 // situation so here we do a sanity check to make sure we haven't 15524 // left any junk around. 15525 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 15526 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15527 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15528 removed.clear(); 15529 for (PreferredActivity pa : pir.filterSet()) { 15530 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 15531 removed.add(pa); 15532 } 15533 } 15534 if (removed.size() > 0) { 15535 for (int r=0; r<removed.size(); r++) { 15536 PreferredActivity pa = removed.get(r); 15537 Slog.w(TAG, "Removing dangling preferred activity: " 15538 + pa.mPref.mComponent); 15539 pir.removeFilter(pa); 15540 } 15541 mSettings.writePackageRestrictionsLPr( 15542 mSettings.mPreferredActivities.keyAt(i)); 15543 } 15544 } 15545 15546 for (int userId : UserManagerService.getInstance().getUserIds()) { 15547 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 15548 grantPermissionsUserIds = ArrayUtils.appendInt( 15549 grantPermissionsUserIds, userId); 15550 } 15551 } 15552 } 15553 sUserManager.systemReady(); 15554 15555 // If we upgraded grant all default permissions before kicking off. 15556 for (int userId : grantPermissionsUserIds) { 15557 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 15558 } 15559 15560 // Kick off any messages waiting for system ready 15561 if (mPostSystemReadyMessages != null) { 15562 for (Message msg : mPostSystemReadyMessages) { 15563 msg.sendToTarget(); 15564 } 15565 mPostSystemReadyMessages = null; 15566 } 15567 15568 // Watch for external volumes that come and go over time 15569 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15570 storage.registerListener(mStorageListener); 15571 15572 mInstallerService.systemReady(); 15573 mPackageDexOptimizer.systemReady(); 15574 15575 MountServiceInternal mountServiceInternal = LocalServices.getService( 15576 MountServiceInternal.class); 15577 mountServiceInternal.addExternalStoragePolicy( 15578 new MountServiceInternal.ExternalStorageMountPolicy() { 15579 @Override 15580 public int getMountMode(int uid, String packageName) { 15581 if (Process.isIsolated(uid)) { 15582 return Zygote.MOUNT_EXTERNAL_NONE; 15583 } 15584 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 15585 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15586 } 15587 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15588 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15589 } 15590 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15591 return Zygote.MOUNT_EXTERNAL_READ; 15592 } 15593 return Zygote.MOUNT_EXTERNAL_WRITE; 15594 } 15595 15596 @Override 15597 public boolean hasExternalStorage(int uid, String packageName) { 15598 return true; 15599 } 15600 }); 15601 } 15602 15603 @Override 15604 public boolean isSafeMode() { 15605 return mSafeMode; 15606 } 15607 15608 @Override 15609 public boolean hasSystemUidErrors() { 15610 return mHasSystemUidErrors; 15611 } 15612 15613 static String arrayToString(int[] array) { 15614 StringBuffer buf = new StringBuffer(128); 15615 buf.append('['); 15616 if (array != null) { 15617 for (int i=0; i<array.length; i++) { 15618 if (i > 0) buf.append(", "); 15619 buf.append(array[i]); 15620 } 15621 } 15622 buf.append(']'); 15623 return buf.toString(); 15624 } 15625 15626 static class DumpState { 15627 public static final int DUMP_LIBS = 1 << 0; 15628 public static final int DUMP_FEATURES = 1 << 1; 15629 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 15630 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 15631 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 15632 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 15633 public static final int DUMP_PERMISSIONS = 1 << 6; 15634 public static final int DUMP_PACKAGES = 1 << 7; 15635 public static final int DUMP_SHARED_USERS = 1 << 8; 15636 public static final int DUMP_MESSAGES = 1 << 9; 15637 public static final int DUMP_PROVIDERS = 1 << 10; 15638 public static final int DUMP_VERIFIERS = 1 << 11; 15639 public static final int DUMP_PREFERRED = 1 << 12; 15640 public static final int DUMP_PREFERRED_XML = 1 << 13; 15641 public static final int DUMP_KEYSETS = 1 << 14; 15642 public static final int DUMP_VERSION = 1 << 15; 15643 public static final int DUMP_INSTALLS = 1 << 16; 15644 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 15645 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 15646 15647 public static final int OPTION_SHOW_FILTERS = 1 << 0; 15648 15649 private int mTypes; 15650 15651 private int mOptions; 15652 15653 private boolean mTitlePrinted; 15654 15655 private SharedUserSetting mSharedUser; 15656 15657 public boolean isDumping(int type) { 15658 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 15659 return true; 15660 } 15661 15662 return (mTypes & type) != 0; 15663 } 15664 15665 public void setDump(int type) { 15666 mTypes |= type; 15667 } 15668 15669 public boolean isOptionEnabled(int option) { 15670 return (mOptions & option) != 0; 15671 } 15672 15673 public void setOptionEnabled(int option) { 15674 mOptions |= option; 15675 } 15676 15677 public boolean onTitlePrinted() { 15678 final boolean printed = mTitlePrinted; 15679 mTitlePrinted = true; 15680 return printed; 15681 } 15682 15683 public boolean getTitlePrinted() { 15684 return mTitlePrinted; 15685 } 15686 15687 public void setTitlePrinted(boolean enabled) { 15688 mTitlePrinted = enabled; 15689 } 15690 15691 public SharedUserSetting getSharedUser() { 15692 return mSharedUser; 15693 } 15694 15695 public void setSharedUser(SharedUserSetting user) { 15696 mSharedUser = user; 15697 } 15698 } 15699 15700 @Override 15701 public void onShellCommand(FileDescriptor in, FileDescriptor out, 15702 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 15703 (new PackageManagerShellCommand(this)).exec( 15704 this, in, out, err, args, resultReceiver); 15705 } 15706 15707 @Override 15708 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 15709 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 15710 != PackageManager.PERMISSION_GRANTED) { 15711 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 15712 + Binder.getCallingPid() 15713 + ", uid=" + Binder.getCallingUid() 15714 + " without permission " 15715 + android.Manifest.permission.DUMP); 15716 return; 15717 } 15718 15719 DumpState dumpState = new DumpState(); 15720 boolean fullPreferred = false; 15721 boolean checkin = false; 15722 15723 String packageName = null; 15724 ArraySet<String> permissionNames = null; 15725 15726 int opti = 0; 15727 while (opti < args.length) { 15728 String opt = args[opti]; 15729 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 15730 break; 15731 } 15732 opti++; 15733 15734 if ("-a".equals(opt)) { 15735 // Right now we only know how to print all. 15736 } else if ("-h".equals(opt)) { 15737 pw.println("Package manager dump options:"); 15738 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 15739 pw.println(" --checkin: dump for a checkin"); 15740 pw.println(" -f: print details of intent filters"); 15741 pw.println(" -h: print this help"); 15742 pw.println(" cmd may be one of:"); 15743 pw.println(" l[ibraries]: list known shared libraries"); 15744 pw.println(" f[eatures]: list device features"); 15745 pw.println(" k[eysets]: print known keysets"); 15746 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 15747 pw.println(" perm[issions]: dump permissions"); 15748 pw.println(" permission [name ...]: dump declaration and use of given permission"); 15749 pw.println(" pref[erred]: print preferred package settings"); 15750 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 15751 pw.println(" prov[iders]: dump content providers"); 15752 pw.println(" p[ackages]: dump installed packages"); 15753 pw.println(" s[hared-users]: dump shared user IDs"); 15754 pw.println(" m[essages]: print collected runtime messages"); 15755 pw.println(" v[erifiers]: print package verifier info"); 15756 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 15757 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 15758 pw.println(" version: print database version info"); 15759 pw.println(" write: write current settings now"); 15760 pw.println(" installs: details about install sessions"); 15761 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 15762 pw.println(" <package.name>: info about given package"); 15763 return; 15764 } else if ("--checkin".equals(opt)) { 15765 checkin = true; 15766 } else if ("-f".equals(opt)) { 15767 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15768 } else { 15769 pw.println("Unknown argument: " + opt + "; use -h for help"); 15770 } 15771 } 15772 15773 // Is the caller requesting to dump a particular piece of data? 15774 if (opti < args.length) { 15775 String cmd = args[opti]; 15776 opti++; 15777 // Is this a package name? 15778 if ("android".equals(cmd) || cmd.contains(".")) { 15779 packageName = cmd; 15780 // When dumping a single package, we always dump all of its 15781 // filter information since the amount of data will be reasonable. 15782 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15783 } else if ("check-permission".equals(cmd)) { 15784 if (opti >= args.length) { 15785 pw.println("Error: check-permission missing permission argument"); 15786 return; 15787 } 15788 String perm = args[opti]; 15789 opti++; 15790 if (opti >= args.length) { 15791 pw.println("Error: check-permission missing package argument"); 15792 return; 15793 } 15794 String pkg = args[opti]; 15795 opti++; 15796 int user = UserHandle.getUserId(Binder.getCallingUid()); 15797 if (opti < args.length) { 15798 try { 15799 user = Integer.parseInt(args[opti]); 15800 } catch (NumberFormatException e) { 15801 pw.println("Error: check-permission user argument is not a number: " 15802 + args[opti]); 15803 return; 15804 } 15805 } 15806 pw.println(checkPermission(perm, pkg, user)); 15807 return; 15808 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 15809 dumpState.setDump(DumpState.DUMP_LIBS); 15810 } else if ("f".equals(cmd) || "features".equals(cmd)) { 15811 dumpState.setDump(DumpState.DUMP_FEATURES); 15812 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 15813 if (opti >= args.length) { 15814 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 15815 | DumpState.DUMP_SERVICE_RESOLVERS 15816 | DumpState.DUMP_RECEIVER_RESOLVERS 15817 | DumpState.DUMP_CONTENT_RESOLVERS); 15818 } else { 15819 while (opti < args.length) { 15820 String name = args[opti]; 15821 if ("a".equals(name) || "activity".equals(name)) { 15822 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 15823 } else if ("s".equals(name) || "service".equals(name)) { 15824 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 15825 } else if ("r".equals(name) || "receiver".equals(name)) { 15826 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 15827 } else if ("c".equals(name) || "content".equals(name)) { 15828 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 15829 } else { 15830 pw.println("Error: unknown resolver table type: " + name); 15831 return; 15832 } 15833 opti++; 15834 } 15835 } 15836 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 15837 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 15838 } else if ("permission".equals(cmd)) { 15839 if (opti >= args.length) { 15840 pw.println("Error: permission requires permission name"); 15841 return; 15842 } 15843 permissionNames = new ArraySet<>(); 15844 while (opti < args.length) { 15845 permissionNames.add(args[opti]); 15846 opti++; 15847 } 15848 dumpState.setDump(DumpState.DUMP_PERMISSIONS 15849 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 15850 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 15851 dumpState.setDump(DumpState.DUMP_PREFERRED); 15852 } else if ("preferred-xml".equals(cmd)) { 15853 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 15854 if (opti < args.length && "--full".equals(args[opti])) { 15855 fullPreferred = true; 15856 opti++; 15857 } 15858 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 15859 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 15860 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 15861 dumpState.setDump(DumpState.DUMP_PACKAGES); 15862 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 15863 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 15864 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 15865 dumpState.setDump(DumpState.DUMP_PROVIDERS); 15866 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 15867 dumpState.setDump(DumpState.DUMP_MESSAGES); 15868 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 15869 dumpState.setDump(DumpState.DUMP_VERIFIERS); 15870 } else if ("i".equals(cmd) || "ifv".equals(cmd) 15871 || "intent-filter-verifiers".equals(cmd)) { 15872 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 15873 } else if ("version".equals(cmd)) { 15874 dumpState.setDump(DumpState.DUMP_VERSION); 15875 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 15876 dumpState.setDump(DumpState.DUMP_KEYSETS); 15877 } else if ("installs".equals(cmd)) { 15878 dumpState.setDump(DumpState.DUMP_INSTALLS); 15879 } else if ("write".equals(cmd)) { 15880 synchronized (mPackages) { 15881 mSettings.writeLPr(); 15882 pw.println("Settings written."); 15883 return; 15884 } 15885 } 15886 } 15887 15888 if (checkin) { 15889 pw.println("vers,1"); 15890 } 15891 15892 // reader 15893 synchronized (mPackages) { 15894 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 15895 if (!checkin) { 15896 if (dumpState.onTitlePrinted()) 15897 pw.println(); 15898 pw.println("Database versions:"); 15899 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 15900 } 15901 } 15902 15903 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 15904 if (!checkin) { 15905 if (dumpState.onTitlePrinted()) 15906 pw.println(); 15907 pw.println("Verifiers:"); 15908 pw.print(" Required: "); 15909 pw.print(mRequiredVerifierPackage); 15910 pw.print(" (uid="); 15911 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 15912 UserHandle.USER_SYSTEM)); 15913 pw.println(")"); 15914 } else if (mRequiredVerifierPackage != null) { 15915 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 15916 pw.print(","); 15917 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 15918 UserHandle.USER_SYSTEM)); 15919 } 15920 } 15921 15922 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 15923 packageName == null) { 15924 if (mIntentFilterVerifierComponent != null) { 15925 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 15926 if (!checkin) { 15927 if (dumpState.onTitlePrinted()) 15928 pw.println(); 15929 pw.println("Intent Filter Verifier:"); 15930 pw.print(" Using: "); 15931 pw.print(verifierPackageName); 15932 pw.print(" (uid="); 15933 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 15934 UserHandle.USER_SYSTEM)); 15935 pw.println(")"); 15936 } else if (verifierPackageName != null) { 15937 pw.print("ifv,"); pw.print(verifierPackageName); 15938 pw.print(","); 15939 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 15940 UserHandle.USER_SYSTEM)); 15941 } 15942 } else { 15943 pw.println(); 15944 pw.println("No Intent Filter Verifier available!"); 15945 } 15946 } 15947 15948 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 15949 boolean printedHeader = false; 15950 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 15951 while (it.hasNext()) { 15952 String name = it.next(); 15953 SharedLibraryEntry ent = mSharedLibraries.get(name); 15954 if (!checkin) { 15955 if (!printedHeader) { 15956 if (dumpState.onTitlePrinted()) 15957 pw.println(); 15958 pw.println("Libraries:"); 15959 printedHeader = true; 15960 } 15961 pw.print(" "); 15962 } else { 15963 pw.print("lib,"); 15964 } 15965 pw.print(name); 15966 if (!checkin) { 15967 pw.print(" -> "); 15968 } 15969 if (ent.path != null) { 15970 if (!checkin) { 15971 pw.print("(jar) "); 15972 pw.print(ent.path); 15973 } else { 15974 pw.print(",jar,"); 15975 pw.print(ent.path); 15976 } 15977 } else { 15978 if (!checkin) { 15979 pw.print("(apk) "); 15980 pw.print(ent.apk); 15981 } else { 15982 pw.print(",apk,"); 15983 pw.print(ent.apk); 15984 } 15985 } 15986 pw.println(); 15987 } 15988 } 15989 15990 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 15991 if (dumpState.onTitlePrinted()) 15992 pw.println(); 15993 if (!checkin) { 15994 pw.println("Features:"); 15995 } 15996 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 15997 while (it.hasNext()) { 15998 String name = it.next(); 15999 if (!checkin) { 16000 pw.print(" "); 16001 } else { 16002 pw.print("feat,"); 16003 } 16004 pw.println(name); 16005 } 16006 } 16007 16008 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 16009 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 16010 : "Activity Resolver Table:", " ", packageName, 16011 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16012 dumpState.setTitlePrinted(true); 16013 } 16014 } 16015 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 16016 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 16017 : "Receiver Resolver Table:", " ", packageName, 16018 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16019 dumpState.setTitlePrinted(true); 16020 } 16021 } 16022 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 16023 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 16024 : "Service Resolver Table:", " ", packageName, 16025 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16026 dumpState.setTitlePrinted(true); 16027 } 16028 } 16029 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 16030 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 16031 : "Provider Resolver Table:", " ", packageName, 16032 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16033 dumpState.setTitlePrinted(true); 16034 } 16035 } 16036 16037 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 16038 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16039 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16040 int user = mSettings.mPreferredActivities.keyAt(i); 16041 if (pir.dump(pw, 16042 dumpState.getTitlePrinted() 16043 ? "\nPreferred Activities User " + user + ":" 16044 : "Preferred Activities User " + user + ":", " ", 16045 packageName, true, false)) { 16046 dumpState.setTitlePrinted(true); 16047 } 16048 } 16049 } 16050 16051 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 16052 pw.flush(); 16053 FileOutputStream fout = new FileOutputStream(fd); 16054 BufferedOutputStream str = new BufferedOutputStream(fout); 16055 XmlSerializer serializer = new FastXmlSerializer(); 16056 try { 16057 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 16058 serializer.startDocument(null, true); 16059 serializer.setFeature( 16060 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 16061 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 16062 serializer.endDocument(); 16063 serializer.flush(); 16064 } catch (IllegalArgumentException e) { 16065 pw.println("Failed writing: " + e); 16066 } catch (IllegalStateException e) { 16067 pw.println("Failed writing: " + e); 16068 } catch (IOException e) { 16069 pw.println("Failed writing: " + e); 16070 } 16071 } 16072 16073 if (!checkin 16074 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 16075 && packageName == null) { 16076 pw.println(); 16077 int count = mSettings.mPackages.size(); 16078 if (count == 0) { 16079 pw.println("No applications!"); 16080 pw.println(); 16081 } else { 16082 final String prefix = " "; 16083 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 16084 if (allPackageSettings.size() == 0) { 16085 pw.println("No domain preferred apps!"); 16086 pw.println(); 16087 } else { 16088 pw.println("App verification status:"); 16089 pw.println(); 16090 count = 0; 16091 for (PackageSetting ps : allPackageSettings) { 16092 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 16093 if (ivi == null || ivi.getPackageName() == null) continue; 16094 pw.println(prefix + "Package: " + ivi.getPackageName()); 16095 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 16096 pw.println(prefix + "Status: " + ivi.getStatusString()); 16097 pw.println(); 16098 count++; 16099 } 16100 if (count == 0) { 16101 pw.println(prefix + "No app verification established."); 16102 pw.println(); 16103 } 16104 for (int userId : sUserManager.getUserIds()) { 16105 pw.println("App linkages for user " + userId + ":"); 16106 pw.println(); 16107 count = 0; 16108 for (PackageSetting ps : allPackageSettings) { 16109 final long status = ps.getDomainVerificationStatusForUser(userId); 16110 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 16111 continue; 16112 } 16113 pw.println(prefix + "Package: " + ps.name); 16114 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 16115 String statusStr = IntentFilterVerificationInfo. 16116 getStatusStringFromValue(status); 16117 pw.println(prefix + "Status: " + statusStr); 16118 pw.println(); 16119 count++; 16120 } 16121 if (count == 0) { 16122 pw.println(prefix + "No configured app linkages."); 16123 pw.println(); 16124 } 16125 } 16126 } 16127 } 16128 } 16129 16130 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 16131 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 16132 if (packageName == null && permissionNames == null) { 16133 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 16134 if (iperm == 0) { 16135 if (dumpState.onTitlePrinted()) 16136 pw.println(); 16137 pw.println("AppOp Permissions:"); 16138 } 16139 pw.print(" AppOp Permission "); 16140 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 16141 pw.println(":"); 16142 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 16143 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 16144 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 16145 } 16146 } 16147 } 16148 } 16149 16150 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 16151 boolean printedSomething = false; 16152 for (PackageParser.Provider p : mProviders.mProviders.values()) { 16153 if (packageName != null && !packageName.equals(p.info.packageName)) { 16154 continue; 16155 } 16156 if (!printedSomething) { 16157 if (dumpState.onTitlePrinted()) 16158 pw.println(); 16159 pw.println("Registered ContentProviders:"); 16160 printedSomething = true; 16161 } 16162 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 16163 pw.print(" "); pw.println(p.toString()); 16164 } 16165 printedSomething = false; 16166 for (Map.Entry<String, PackageParser.Provider> entry : 16167 mProvidersByAuthority.entrySet()) { 16168 PackageParser.Provider p = entry.getValue(); 16169 if (packageName != null && !packageName.equals(p.info.packageName)) { 16170 continue; 16171 } 16172 if (!printedSomething) { 16173 if (dumpState.onTitlePrinted()) 16174 pw.println(); 16175 pw.println("ContentProvider Authorities:"); 16176 printedSomething = true; 16177 } 16178 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 16179 pw.print(" "); pw.println(p.toString()); 16180 if (p.info != null && p.info.applicationInfo != null) { 16181 final String appInfo = p.info.applicationInfo.toString(); 16182 pw.print(" applicationInfo="); pw.println(appInfo); 16183 } 16184 } 16185 } 16186 16187 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 16188 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 16189 } 16190 16191 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 16192 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 16193 } 16194 16195 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 16196 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 16197 } 16198 16199 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 16200 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 16201 } 16202 16203 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 16204 // XXX should handle packageName != null by dumping only install data that 16205 // the given package is involved with. 16206 if (dumpState.onTitlePrinted()) pw.println(); 16207 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 16208 } 16209 16210 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 16211 if (dumpState.onTitlePrinted()) pw.println(); 16212 mSettings.dumpReadMessagesLPr(pw, dumpState); 16213 16214 pw.println(); 16215 pw.println("Package warning messages:"); 16216 BufferedReader in = null; 16217 String line = null; 16218 try { 16219 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 16220 while ((line = in.readLine()) != null) { 16221 if (line.contains("ignored: updated version")) continue; 16222 pw.println(line); 16223 } 16224 } catch (IOException ignored) { 16225 } finally { 16226 IoUtils.closeQuietly(in); 16227 } 16228 } 16229 16230 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 16231 BufferedReader in = null; 16232 String line = null; 16233 try { 16234 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 16235 while ((line = in.readLine()) != null) { 16236 if (line.contains("ignored: updated version")) continue; 16237 pw.print("msg,"); 16238 pw.println(line); 16239 } 16240 } catch (IOException ignored) { 16241 } finally { 16242 IoUtils.closeQuietly(in); 16243 } 16244 } 16245 } 16246 } 16247 16248 private String dumpDomainString(String packageName) { 16249 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 16250 List<IntentFilter> filters = getAllIntentFilters(packageName); 16251 16252 ArraySet<String> result = new ArraySet<>(); 16253 if (iviList.size() > 0) { 16254 for (IntentFilterVerificationInfo ivi : iviList) { 16255 for (String host : ivi.getDomains()) { 16256 result.add(host); 16257 } 16258 } 16259 } 16260 if (filters != null && filters.size() > 0) { 16261 for (IntentFilter filter : filters) { 16262 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 16263 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 16264 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 16265 result.addAll(filter.getHostsList()); 16266 } 16267 } 16268 } 16269 16270 StringBuilder sb = new StringBuilder(result.size() * 16); 16271 for (String domain : result) { 16272 if (sb.length() > 0) sb.append(" "); 16273 sb.append(domain); 16274 } 16275 return sb.toString(); 16276 } 16277 16278 // ------- apps on sdcard specific code ------- 16279 static final boolean DEBUG_SD_INSTALL = false; 16280 16281 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 16282 16283 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 16284 16285 private boolean mMediaMounted = false; 16286 16287 static String getEncryptKey() { 16288 try { 16289 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 16290 SD_ENCRYPTION_KEYSTORE_NAME); 16291 if (sdEncKey == null) { 16292 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 16293 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 16294 if (sdEncKey == null) { 16295 Slog.e(TAG, "Failed to create encryption keys"); 16296 return null; 16297 } 16298 } 16299 return sdEncKey; 16300 } catch (NoSuchAlgorithmException nsae) { 16301 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 16302 return null; 16303 } catch (IOException ioe) { 16304 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 16305 return null; 16306 } 16307 } 16308 16309 /* 16310 * Update media status on PackageManager. 16311 */ 16312 @Override 16313 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 16314 int callingUid = Binder.getCallingUid(); 16315 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 16316 throw new SecurityException("Media status can only be updated by the system"); 16317 } 16318 // reader; this apparently protects mMediaMounted, but should probably 16319 // be a different lock in that case. 16320 synchronized (mPackages) { 16321 Log.i(TAG, "Updating external media status from " 16322 + (mMediaMounted ? "mounted" : "unmounted") + " to " 16323 + (mediaStatus ? "mounted" : "unmounted")); 16324 if (DEBUG_SD_INSTALL) 16325 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 16326 + ", mMediaMounted=" + mMediaMounted); 16327 if (mediaStatus == mMediaMounted) { 16328 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 16329 : 0, -1); 16330 mHandler.sendMessage(msg); 16331 return; 16332 } 16333 mMediaMounted = mediaStatus; 16334 } 16335 // Queue up an async operation since the package installation may take a 16336 // little while. 16337 mHandler.post(new Runnable() { 16338 public void run() { 16339 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 16340 } 16341 }); 16342 } 16343 16344 /** 16345 * Called by MountService when the initial ASECs to scan are available. 16346 * Should block until all the ASEC containers are finished being scanned. 16347 */ 16348 public void scanAvailableAsecs() { 16349 updateExternalMediaStatusInner(true, false, false); 16350 } 16351 16352 /* 16353 * Collect information of applications on external media, map them against 16354 * existing containers and update information based on current mount status. 16355 * Please note that we always have to report status if reportStatus has been 16356 * set to true especially when unloading packages. 16357 */ 16358 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 16359 boolean externalStorage) { 16360 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 16361 int[] uidArr = EmptyArray.INT; 16362 16363 final String[] list = PackageHelper.getSecureContainerList(); 16364 if (ArrayUtils.isEmpty(list)) { 16365 Log.i(TAG, "No secure containers found"); 16366 } else { 16367 // Process list of secure containers and categorize them 16368 // as active or stale based on their package internal state. 16369 16370 // reader 16371 synchronized (mPackages) { 16372 for (String cid : list) { 16373 // Leave stages untouched for now; installer service owns them 16374 if (PackageInstallerService.isStageName(cid)) continue; 16375 16376 if (DEBUG_SD_INSTALL) 16377 Log.i(TAG, "Processing container " + cid); 16378 String pkgName = getAsecPackageName(cid); 16379 if (pkgName == null) { 16380 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 16381 continue; 16382 } 16383 if (DEBUG_SD_INSTALL) 16384 Log.i(TAG, "Looking for pkg : " + pkgName); 16385 16386 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16387 if (ps == null) { 16388 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 16389 continue; 16390 } 16391 16392 /* 16393 * Skip packages that are not external if we're unmounting 16394 * external storage. 16395 */ 16396 if (externalStorage && !isMounted && !isExternal(ps)) { 16397 continue; 16398 } 16399 16400 final AsecInstallArgs args = new AsecInstallArgs(cid, 16401 getAppDexInstructionSets(ps), ps.isForwardLocked()); 16402 // The package status is changed only if the code path 16403 // matches between settings and the container id. 16404 if (ps.codePathString != null 16405 && ps.codePathString.startsWith(args.getCodePath())) { 16406 if (DEBUG_SD_INSTALL) { 16407 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 16408 + " at code path: " + ps.codePathString); 16409 } 16410 16411 // We do have a valid package installed on sdcard 16412 processCids.put(args, ps.codePathString); 16413 final int uid = ps.appId; 16414 if (uid != -1) { 16415 uidArr = ArrayUtils.appendInt(uidArr, uid); 16416 } 16417 } else { 16418 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 16419 + ps.codePathString); 16420 } 16421 } 16422 } 16423 16424 Arrays.sort(uidArr); 16425 } 16426 16427 // Process packages with valid entries. 16428 if (isMounted) { 16429 if (DEBUG_SD_INSTALL) 16430 Log.i(TAG, "Loading packages"); 16431 loadMediaPackages(processCids, uidArr, externalStorage); 16432 startCleaningPackages(); 16433 mInstallerService.onSecureContainersAvailable(); 16434 } else { 16435 if (DEBUG_SD_INSTALL) 16436 Log.i(TAG, "Unloading packages"); 16437 unloadMediaPackages(processCids, uidArr, reportStatus); 16438 } 16439 } 16440 16441 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16442 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 16443 final int size = infos.size(); 16444 final String[] packageNames = new String[size]; 16445 final int[] packageUids = new int[size]; 16446 for (int i = 0; i < size; i++) { 16447 final ApplicationInfo info = infos.get(i); 16448 packageNames[i] = info.packageName; 16449 packageUids[i] = info.uid; 16450 } 16451 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 16452 finishedReceiver); 16453 } 16454 16455 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16456 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 16457 sendResourcesChangedBroadcast(mediaStatus, replacing, 16458 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 16459 } 16460 16461 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16462 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 16463 int size = pkgList.length; 16464 if (size > 0) { 16465 // Send broadcasts here 16466 Bundle extras = new Bundle(); 16467 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 16468 if (uidArr != null) { 16469 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 16470 } 16471 if (replacing) { 16472 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 16473 } 16474 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 16475 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 16476 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 16477 } 16478 } 16479 16480 /* 16481 * Look at potentially valid container ids from processCids If package 16482 * information doesn't match the one on record or package scanning fails, 16483 * the cid is added to list of removeCids. We currently don't delete stale 16484 * containers. 16485 */ 16486 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 16487 boolean externalStorage) { 16488 ArrayList<String> pkgList = new ArrayList<String>(); 16489 Set<AsecInstallArgs> keys = processCids.keySet(); 16490 16491 for (AsecInstallArgs args : keys) { 16492 String codePath = processCids.get(args); 16493 if (DEBUG_SD_INSTALL) 16494 Log.i(TAG, "Loading container : " + args.cid); 16495 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 16496 try { 16497 // Make sure there are no container errors first. 16498 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 16499 Slog.e(TAG, "Failed to mount cid : " + args.cid 16500 + " when installing from sdcard"); 16501 continue; 16502 } 16503 // Check code path here. 16504 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 16505 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 16506 + " does not match one in settings " + codePath); 16507 continue; 16508 } 16509 // Parse package 16510 int parseFlags = mDefParseFlags; 16511 if (args.isExternalAsec()) { 16512 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 16513 } 16514 if (args.isFwdLocked()) { 16515 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 16516 } 16517 16518 synchronized (mInstallLock) { 16519 PackageParser.Package pkg = null; 16520 try { 16521 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 16522 } catch (PackageManagerException e) { 16523 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 16524 } 16525 // Scan the package 16526 if (pkg != null) { 16527 /* 16528 * TODO why is the lock being held? doPostInstall is 16529 * called in other places without the lock. This needs 16530 * to be straightened out. 16531 */ 16532 // writer 16533 synchronized (mPackages) { 16534 retCode = PackageManager.INSTALL_SUCCEEDED; 16535 pkgList.add(pkg.packageName); 16536 // Post process args 16537 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 16538 pkg.applicationInfo.uid); 16539 } 16540 } else { 16541 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 16542 } 16543 } 16544 16545 } finally { 16546 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 16547 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 16548 } 16549 } 16550 } 16551 // writer 16552 synchronized (mPackages) { 16553 // If the platform SDK has changed since the last time we booted, 16554 // we need to re-grant app permission to catch any new ones that 16555 // appear. This is really a hack, and means that apps can in some 16556 // cases get permissions that the user didn't initially explicitly 16557 // allow... it would be nice to have some better way to handle 16558 // this situation. 16559 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 16560 : mSettings.getInternalVersion(); 16561 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 16562 : StorageManager.UUID_PRIVATE_INTERNAL; 16563 16564 int updateFlags = UPDATE_PERMISSIONS_ALL; 16565 if (ver.sdkVersion != mSdkVersion) { 16566 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16567 + mSdkVersion + "; regranting permissions for external"); 16568 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16569 } 16570 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 16571 16572 // Yay, everything is now upgraded 16573 ver.forceCurrent(); 16574 16575 // can downgrade to reader 16576 // Persist settings 16577 mSettings.writeLPr(); 16578 } 16579 // Send a broadcast to let everyone know we are done processing 16580 if (pkgList.size() > 0) { 16581 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 16582 } 16583 } 16584 16585 /* 16586 * Utility method to unload a list of specified containers 16587 */ 16588 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 16589 // Just unmount all valid containers. 16590 for (AsecInstallArgs arg : cidArgs) { 16591 synchronized (mInstallLock) { 16592 arg.doPostDeleteLI(false); 16593 } 16594 } 16595 } 16596 16597 /* 16598 * Unload packages mounted on external media. This involves deleting package 16599 * data from internal structures, sending broadcasts about diabled packages, 16600 * gc'ing to free up references, unmounting all secure containers 16601 * corresponding to packages on external media, and posting a 16602 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 16603 * that we always have to post this message if status has been requested no 16604 * matter what. 16605 */ 16606 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 16607 final boolean reportStatus) { 16608 if (DEBUG_SD_INSTALL) 16609 Log.i(TAG, "unloading media packages"); 16610 ArrayList<String> pkgList = new ArrayList<String>(); 16611 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 16612 final Set<AsecInstallArgs> keys = processCids.keySet(); 16613 for (AsecInstallArgs args : keys) { 16614 String pkgName = args.getPackageName(); 16615 if (DEBUG_SD_INSTALL) 16616 Log.i(TAG, "Trying to unload pkg : " + pkgName); 16617 // Delete package internally 16618 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16619 synchronized (mInstallLock) { 16620 boolean res = deletePackageLI(pkgName, null, false, null, null, 16621 PackageManager.DELETE_KEEP_DATA, outInfo, false); 16622 if (res) { 16623 pkgList.add(pkgName); 16624 } else { 16625 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 16626 failedList.add(args); 16627 } 16628 } 16629 } 16630 16631 // reader 16632 synchronized (mPackages) { 16633 // We didn't update the settings after removing each package; 16634 // write them now for all packages. 16635 mSettings.writeLPr(); 16636 } 16637 16638 // We have to absolutely send UPDATED_MEDIA_STATUS only 16639 // after confirming that all the receivers processed the ordered 16640 // broadcast when packages get disabled, force a gc to clean things up. 16641 // and unload all the containers. 16642 if (pkgList.size() > 0) { 16643 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 16644 new IIntentReceiver.Stub() { 16645 public void performReceive(Intent intent, int resultCode, String data, 16646 Bundle extras, boolean ordered, boolean sticky, 16647 int sendingUser) throws RemoteException { 16648 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 16649 reportStatus ? 1 : 0, 1, keys); 16650 mHandler.sendMessage(msg); 16651 } 16652 }); 16653 } else { 16654 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 16655 keys); 16656 mHandler.sendMessage(msg); 16657 } 16658 } 16659 16660 private void loadPrivatePackages(final VolumeInfo vol) { 16661 mHandler.post(new Runnable() { 16662 @Override 16663 public void run() { 16664 loadPrivatePackagesInner(vol); 16665 } 16666 }); 16667 } 16668 16669 private void loadPrivatePackagesInner(VolumeInfo vol) { 16670 final String volumeUuid = vol.fsUuid; 16671 if (TextUtils.isEmpty(volumeUuid)) { 16672 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 16673 return; 16674 } 16675 16676 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 16677 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 16678 16679 final VersionInfo ver; 16680 final List<PackageSetting> packages; 16681 synchronized (mPackages) { 16682 ver = mSettings.findOrCreateVersion(volumeUuid); 16683 packages = mSettings.getVolumePackagesLPr(volumeUuid); 16684 } 16685 16686 // TODO: introduce a new concept similar to "frozen" to prevent these 16687 // apps from being launched until after data has been fully reconciled 16688 for (PackageSetting ps : packages) { 16689 synchronized (mInstallLock) { 16690 final PackageParser.Package pkg; 16691 try { 16692 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 16693 loaded.add(pkg.applicationInfo); 16694 16695 } catch (PackageManagerException e) { 16696 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 16697 } 16698 16699 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 16700 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 16701 } 16702 } 16703 } 16704 16705 // Reconcile app data for all started/unlocked users 16706 final UserManager um = mContext.getSystemService(UserManager.class); 16707 for (UserInfo user : um.getUsers()) { 16708 if (um.isUserUnlocked(user.id)) { 16709 reconcileAppsData(volumeUuid, user.id, 16710 Installer.FLAG_DE_STORAGE | Installer.FLAG_CE_STORAGE); 16711 } else if (um.isUserRunning(user.id)) { 16712 reconcileAppsData(volumeUuid, user.id, Installer.FLAG_DE_STORAGE); 16713 } else { 16714 continue; 16715 } 16716 } 16717 16718 synchronized (mPackages) { 16719 int updateFlags = UPDATE_PERMISSIONS_ALL; 16720 if (ver.sdkVersion != mSdkVersion) { 16721 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16722 + mSdkVersion + "; regranting permissions for " + volumeUuid); 16723 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16724 } 16725 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 16726 16727 // Yay, everything is now upgraded 16728 ver.forceCurrent(); 16729 16730 mSettings.writeLPr(); 16731 } 16732 16733 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 16734 sendResourcesChangedBroadcast(true, false, loaded, null); 16735 } 16736 16737 private void unloadPrivatePackages(final VolumeInfo vol) { 16738 mHandler.post(new Runnable() { 16739 @Override 16740 public void run() { 16741 unloadPrivatePackagesInner(vol); 16742 } 16743 }); 16744 } 16745 16746 private void unloadPrivatePackagesInner(VolumeInfo vol) { 16747 final String volumeUuid = vol.fsUuid; 16748 if (TextUtils.isEmpty(volumeUuid)) { 16749 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 16750 return; 16751 } 16752 16753 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 16754 synchronized (mInstallLock) { 16755 synchronized (mPackages) { 16756 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 16757 for (PackageSetting ps : packages) { 16758 if (ps.pkg == null) continue; 16759 16760 final ApplicationInfo info = ps.pkg.applicationInfo; 16761 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16762 if (deletePackageLI(ps.name, null, false, null, null, 16763 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 16764 unloaded.add(info); 16765 } else { 16766 Slog.w(TAG, "Failed to unload " + ps.codePath); 16767 } 16768 } 16769 16770 mSettings.writeLPr(); 16771 } 16772 } 16773 16774 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 16775 sendResourcesChangedBroadcast(false, false, unloaded, null); 16776 } 16777 16778 /** 16779 * Examine all users present on given mounted volume, and destroy data 16780 * belonging to users that are no longer valid, or whose user ID has been 16781 * recycled. 16782 */ 16783 private void reconcileUsers(String volumeUuid) { 16784 final File[] files = FileUtils 16785 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 16786 for (File file : files) { 16787 if (!file.isDirectory()) continue; 16788 16789 final int userId; 16790 final UserInfo info; 16791 try { 16792 userId = Integer.parseInt(file.getName()); 16793 info = sUserManager.getUserInfo(userId); 16794 } catch (NumberFormatException e) { 16795 Slog.w(TAG, "Invalid user directory " + file); 16796 continue; 16797 } 16798 16799 boolean destroyUser = false; 16800 if (info == null) { 16801 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16802 + " because no matching user was found"); 16803 destroyUser = true; 16804 } else { 16805 try { 16806 UserManagerService.enforceSerialNumber(file, info.serialNumber); 16807 } catch (IOException e) { 16808 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16809 + " because we failed to enforce serial number: " + e); 16810 destroyUser = true; 16811 } 16812 } 16813 16814 if (destroyUser) { 16815 synchronized (mInstallLock) { 16816 try { 16817 mInstaller.removeUserDataDirs(volumeUuid, userId); 16818 } catch (InstallerException e) { 16819 Slog.w(TAG, "Failed to clean up user dirs", e); 16820 } 16821 } 16822 } 16823 } 16824 16825 final StorageManager sm = mContext.getSystemService(StorageManager.class); 16826 final UserManager um = mContext.getSystemService(UserManager.class); 16827 for (UserInfo user : um.getUsers()) { 16828 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 16829 if (userDir.exists()) continue; 16830 16831 try { 16832 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, user.isEphemeral()); 16833 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 16834 } catch (IOException e) { 16835 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 16836 } 16837 } 16838 } 16839 16840 private void assertPackageKnown(String volumeUuid, String packageName) 16841 throws PackageManagerException { 16842 synchronized (mPackages) { 16843 final PackageSetting ps = mSettings.mPackages.get(packageName); 16844 if (ps == null) { 16845 throw new PackageManagerException("Package " + packageName + " is unknown"); 16846 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 16847 throw new PackageManagerException( 16848 "Package " + packageName + " found on unknown volume " + volumeUuid 16849 + "; expected volume " + ps.volumeUuid); 16850 } 16851 } 16852 } 16853 16854 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 16855 throws PackageManagerException { 16856 synchronized (mPackages) { 16857 final PackageSetting ps = mSettings.mPackages.get(packageName); 16858 if (ps == null) { 16859 throw new PackageManagerException("Package " + packageName + " is unknown"); 16860 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 16861 throw new PackageManagerException( 16862 "Package " + packageName + " found on unknown volume " + volumeUuid 16863 + "; expected volume " + ps.volumeUuid); 16864 } else if (!ps.getInstalled(userId)) { 16865 throw new PackageManagerException( 16866 "Package " + packageName + " not installed for user " + userId); 16867 } 16868 } 16869 } 16870 16871 /** 16872 * Examine all apps present on given mounted volume, and destroy apps that 16873 * aren't expected, either due to uninstallation or reinstallation on 16874 * another volume. 16875 */ 16876 private void reconcileApps(String volumeUuid) { 16877 final File[] files = FileUtils 16878 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 16879 for (File file : files) { 16880 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 16881 && !PackageInstallerService.isStageName(file.getName()); 16882 if (!isPackage) { 16883 // Ignore entries which are not packages 16884 continue; 16885 } 16886 16887 try { 16888 final PackageLite pkg = PackageParser.parsePackageLite(file, 16889 PackageParser.PARSE_MUST_BE_APK); 16890 assertPackageKnown(volumeUuid, pkg.packageName); 16891 16892 } catch (PackageParserException | PackageManagerException e) { 16893 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 16894 synchronized (mInstallLock) { 16895 removeCodePathLI(file); 16896 } 16897 } 16898 } 16899 } 16900 16901 /** 16902 * Reconcile all app data for the given user. 16903 * <p> 16904 * Verifies that directories exist and that ownership and labeling is 16905 * correct for all installed apps on all mounted volumes. 16906 */ 16907 void reconcileAppsData(int userId, @StorageFlags int flags) { 16908 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16909 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16910 final String volumeUuid = vol.getFsUuid(); 16911 reconcileAppsData(volumeUuid, userId, flags); 16912 } 16913 } 16914 16915 /** 16916 * Reconcile all app data on given mounted volume. 16917 * <p> 16918 * Destroys app data that isn't expected, either due to uninstallation or 16919 * reinstallation on another volume. 16920 * <p> 16921 * Verifies that directories exist and that ownership and labeling is 16922 * correct for all installed apps. 16923 */ 16924 private void reconcileAppsData(String volumeUuid, int userId, @StorageFlags int flags) { 16925 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 16926 + Integer.toHexString(flags)); 16927 16928 final File ceDir = Environment.getDataUserCredentialEncryptedDirectory(volumeUuid, userId); 16929 final File deDir = Environment.getDataUserDeviceEncryptedDirectory(volumeUuid, userId); 16930 16931 boolean restoreconNeeded = false; 16932 16933 // First look for stale data that doesn't belong, and check if things 16934 // have changed since we did our last restorecon 16935 if ((flags & Installer.FLAG_CE_STORAGE) != 0) { 16936 if (!isUserKeyUnlocked(userId)) { 16937 throw new RuntimeException( 16938 "Yikes, someone asked us to reconcile CE storage while " + userId 16939 + " was still locked; this would have caused massive data loss!"); 16940 } 16941 16942 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 16943 16944 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 16945 for (File file : files) { 16946 final String packageName = file.getName(); 16947 try { 16948 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 16949 } catch (PackageManagerException e) { 16950 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 16951 synchronized (mInstallLock) { 16952 destroyAppDataLI(volumeUuid, packageName, userId, 16953 Installer.FLAG_CE_STORAGE); 16954 } 16955 } 16956 } 16957 } 16958 if ((flags & Installer.FLAG_DE_STORAGE) != 0) { 16959 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 16960 16961 final File[] files = FileUtils.listFilesOrEmpty(deDir); 16962 for (File file : files) { 16963 final String packageName = file.getName(); 16964 try { 16965 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 16966 } catch (PackageManagerException e) { 16967 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 16968 synchronized (mInstallLock) { 16969 destroyAppDataLI(volumeUuid, packageName, userId, 16970 Installer.FLAG_DE_STORAGE); 16971 } 16972 } 16973 } 16974 } 16975 16976 // Ensure that data directories are ready to roll for all packages 16977 // installed for this volume and user 16978 final List<PackageSetting> packages; 16979 synchronized (mPackages) { 16980 packages = mSettings.getVolumePackagesLPr(volumeUuid); 16981 } 16982 int preparedCount = 0; 16983 for (PackageSetting ps : packages) { 16984 final String packageName = ps.name; 16985 if (ps.pkg == null) { 16986 Slog.w(TAG, "Odd, missing scanned package " + packageName); 16987 // TODO: might be due to legacy ASEC apps; we should circle back 16988 // and reconcile again once they're scanned 16989 continue; 16990 } 16991 16992 if (ps.getInstalled(userId)) { 16993 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 16994 preparedCount++; 16995 } 16996 } 16997 16998 if (restoreconNeeded) { 16999 if ((flags & Installer.FLAG_CE_STORAGE) != 0) { 17000 SELinuxMMAC.setRestoreconDone(ceDir); 17001 } 17002 if ((flags & Installer.FLAG_DE_STORAGE) != 0) { 17003 SELinuxMMAC.setRestoreconDone(deDir); 17004 } 17005 } 17006 17007 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 17008 + " packages; restoreconNeeded was " + restoreconNeeded); 17009 } 17010 17011 /** 17012 * Prepare app data for the given app just after it was installed or 17013 * upgraded. This method carefully only touches users that it's installed 17014 * for, and it forces a restorecon to handle any seinfo changes. 17015 * <p> 17016 * Verifies that directories exist and that ownership and labeling is 17017 * correct for all installed apps. If there is an ownership mismatch, it 17018 * will try recovering system apps by wiping data; third-party app data is 17019 * left intact. 17020 */ 17021 private void prepareAppDataAfterInstall(PackageParser.Package pkg) { 17022 final PackageSetting ps; 17023 synchronized (mPackages) { 17024 ps = mSettings.mPackages.get(pkg.packageName); 17025 } 17026 17027 final UserManager um = mContext.getSystemService(UserManager.class); 17028 for (UserInfo user : um.getUsers()) { 17029 final int flags; 17030 if (um.isUserUnlocked(user.id)) { 17031 flags = Installer.FLAG_DE_STORAGE | Installer.FLAG_CE_STORAGE; 17032 } else if (um.isUserRunning(user.id)) { 17033 flags = Installer.FLAG_DE_STORAGE; 17034 } else { 17035 continue; 17036 } 17037 17038 if (ps.getInstalled(user.id)) { 17039 // Whenever an app changes, force a restorecon of its data 17040 // TODO: when user data is locked, mark that we're still dirty 17041 prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true); 17042 } 17043 } 17044 } 17045 17046 /** 17047 * Prepare app data for the given app. 17048 * <p> 17049 * Verifies that directories exist and that ownership and labeling is 17050 * correct for all installed apps. If there is an ownership mismatch, this 17051 * will try recovering system apps by wiping data; third-party app data is 17052 * left intact. 17053 */ 17054 private void prepareAppData(String volumeUuid, int userId, @StorageFlags int flags, 17055 PackageParser.Package pkg, boolean restoreconNeeded) { 17056 if (DEBUG_APP_DATA) { 17057 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 17058 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 17059 } 17060 17061 final String packageName = pkg.packageName; 17062 final ApplicationInfo app = pkg.applicationInfo; 17063 final int appId = UserHandle.getAppId(app.uid); 17064 17065 Preconditions.checkNotNull(app.seinfo); 17066 17067 synchronized (mInstallLock) { 17068 try { 17069 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 17070 appId, app.seinfo, app.targetSdkVersion); 17071 } catch (InstallerException e) { 17072 if (app.isSystemApp()) { 17073 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 17074 + ", but trying to recover: " + e); 17075 destroyAppDataLI(volumeUuid, packageName, userId, flags); 17076 try { 17077 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 17078 appId, app.seinfo, app.targetSdkVersion); 17079 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 17080 } catch (InstallerException e2) { 17081 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 17082 } 17083 } else { 17084 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 17085 } 17086 } 17087 17088 if (restoreconNeeded) { 17089 restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo); 17090 } 17091 17092 if ((flags & Installer.FLAG_CE_STORAGE) != 0) { 17093 // Create a native library symlink only if we have native libraries 17094 // and if the native libraries are 32 bit libraries. We do not provide 17095 // this symlink for 64 bit libraries. 17096 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 17097 final String nativeLibPath = app.nativeLibraryDir; 17098 try { 17099 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 17100 nativeLibPath, userId); 17101 } catch (InstallerException e) { 17102 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 17103 } 17104 } 17105 } 17106 } 17107 } 17108 17109 private void unfreezePackage(String packageName) { 17110 synchronized (mPackages) { 17111 final PackageSetting ps = mSettings.mPackages.get(packageName); 17112 if (ps != null) { 17113 ps.frozen = false; 17114 } 17115 } 17116 } 17117 17118 @Override 17119 public int movePackage(final String packageName, final String volumeUuid) { 17120 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 17121 17122 final int moveId = mNextMoveId.getAndIncrement(); 17123 mHandler.post(new Runnable() { 17124 @Override 17125 public void run() { 17126 try { 17127 movePackageInternal(packageName, volumeUuid, moveId); 17128 } catch (PackageManagerException e) { 17129 Slog.w(TAG, "Failed to move " + packageName, e); 17130 mMoveCallbacks.notifyStatusChanged(moveId, 17131 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 17132 } 17133 } 17134 }); 17135 return moveId; 17136 } 17137 17138 private void movePackageInternal(final String packageName, final String volumeUuid, 17139 final int moveId) throws PackageManagerException { 17140 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 17141 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17142 final PackageManager pm = mContext.getPackageManager(); 17143 17144 final boolean currentAsec; 17145 final String currentVolumeUuid; 17146 final File codeFile; 17147 final String installerPackageName; 17148 final String packageAbiOverride; 17149 final int appId; 17150 final String seinfo; 17151 final String label; 17152 final int targetSdkVersion; 17153 17154 // reader 17155 synchronized (mPackages) { 17156 final PackageParser.Package pkg = mPackages.get(packageName); 17157 final PackageSetting ps = mSettings.mPackages.get(packageName); 17158 if (pkg == null || ps == null) { 17159 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 17160 } 17161 17162 if (pkg.applicationInfo.isSystemApp()) { 17163 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 17164 "Cannot move system application"); 17165 } 17166 17167 if (pkg.applicationInfo.isExternalAsec()) { 17168 currentAsec = true; 17169 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 17170 } else if (pkg.applicationInfo.isForwardLocked()) { 17171 currentAsec = true; 17172 currentVolumeUuid = "forward_locked"; 17173 } else { 17174 currentAsec = false; 17175 currentVolumeUuid = ps.volumeUuid; 17176 17177 final File probe = new File(pkg.codePath); 17178 final File probeOat = new File(probe, "oat"); 17179 if (!probe.isDirectory() || !probeOat.isDirectory()) { 17180 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17181 "Move only supported for modern cluster style installs"); 17182 } 17183 } 17184 17185 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 17186 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17187 "Package already moved to " + volumeUuid); 17188 } 17189 17190 if (ps.frozen) { 17191 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 17192 "Failed to move already frozen package"); 17193 } 17194 ps.frozen = true; 17195 17196 codeFile = new File(pkg.codePath); 17197 installerPackageName = ps.installerPackageName; 17198 packageAbiOverride = ps.cpuAbiOverrideString; 17199 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 17200 seinfo = pkg.applicationInfo.seinfo; 17201 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 17202 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 17203 } 17204 17205 // Now that we're guarded by frozen state, kill app during move 17206 final long token = Binder.clearCallingIdentity(); 17207 try { 17208 killApplication(packageName, appId, "move pkg"); 17209 } finally { 17210 Binder.restoreCallingIdentity(token); 17211 } 17212 17213 final Bundle extras = new Bundle(); 17214 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 17215 extras.putString(Intent.EXTRA_TITLE, label); 17216 mMoveCallbacks.notifyCreated(moveId, extras); 17217 17218 int installFlags; 17219 final boolean moveCompleteApp; 17220 final File measurePath; 17221 17222 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 17223 installFlags = INSTALL_INTERNAL; 17224 moveCompleteApp = !currentAsec; 17225 measurePath = Environment.getDataAppDirectory(volumeUuid); 17226 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 17227 installFlags = INSTALL_EXTERNAL; 17228 moveCompleteApp = false; 17229 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 17230 } else { 17231 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 17232 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 17233 || !volume.isMountedWritable()) { 17234 unfreezePackage(packageName); 17235 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17236 "Move location not mounted private volume"); 17237 } 17238 17239 Preconditions.checkState(!currentAsec); 17240 17241 installFlags = INSTALL_INTERNAL; 17242 moveCompleteApp = true; 17243 measurePath = Environment.getDataAppDirectory(volumeUuid); 17244 } 17245 17246 final PackageStats stats = new PackageStats(null, -1); 17247 synchronized (mInstaller) { 17248 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 17249 unfreezePackage(packageName); 17250 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17251 "Failed to measure package size"); 17252 } 17253 } 17254 17255 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 17256 + stats.dataSize); 17257 17258 final long startFreeBytes = measurePath.getFreeSpace(); 17259 final long sizeBytes; 17260 if (moveCompleteApp) { 17261 sizeBytes = stats.codeSize + stats.dataSize; 17262 } else { 17263 sizeBytes = stats.codeSize; 17264 } 17265 17266 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 17267 unfreezePackage(packageName); 17268 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17269 "Not enough free space to move"); 17270 } 17271 17272 mMoveCallbacks.notifyStatusChanged(moveId, 10); 17273 17274 final CountDownLatch installedLatch = new CountDownLatch(1); 17275 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 17276 @Override 17277 public void onUserActionRequired(Intent intent) throws RemoteException { 17278 throw new IllegalStateException(); 17279 } 17280 17281 @Override 17282 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 17283 Bundle extras) throws RemoteException { 17284 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 17285 + PackageManager.installStatusToString(returnCode, msg)); 17286 17287 installedLatch.countDown(); 17288 17289 // Regardless of success or failure of the move operation, 17290 // always unfreeze the package 17291 unfreezePackage(packageName); 17292 17293 final int status = PackageManager.installStatusToPublicStatus(returnCode); 17294 switch (status) { 17295 case PackageInstaller.STATUS_SUCCESS: 17296 mMoveCallbacks.notifyStatusChanged(moveId, 17297 PackageManager.MOVE_SUCCEEDED); 17298 break; 17299 case PackageInstaller.STATUS_FAILURE_STORAGE: 17300 mMoveCallbacks.notifyStatusChanged(moveId, 17301 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 17302 break; 17303 default: 17304 mMoveCallbacks.notifyStatusChanged(moveId, 17305 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 17306 break; 17307 } 17308 } 17309 }; 17310 17311 final MoveInfo move; 17312 if (moveCompleteApp) { 17313 // Kick off a thread to report progress estimates 17314 new Thread() { 17315 @Override 17316 public void run() { 17317 while (true) { 17318 try { 17319 if (installedLatch.await(1, TimeUnit.SECONDS)) { 17320 break; 17321 } 17322 } catch (InterruptedException ignored) { 17323 } 17324 17325 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 17326 final int progress = 10 + (int) MathUtils.constrain( 17327 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 17328 mMoveCallbacks.notifyStatusChanged(moveId, progress); 17329 } 17330 } 17331 }.start(); 17332 17333 final String dataAppName = codeFile.getName(); 17334 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 17335 dataAppName, appId, seinfo, targetSdkVersion); 17336 } else { 17337 move = null; 17338 } 17339 17340 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 17341 17342 final Message msg = mHandler.obtainMessage(INIT_COPY); 17343 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 17344 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 17345 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 17346 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 17347 msg.obj = params; 17348 17349 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 17350 System.identityHashCode(msg.obj)); 17351 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 17352 System.identityHashCode(msg.obj)); 17353 17354 mHandler.sendMessage(msg); 17355 } 17356 17357 @Override 17358 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 17359 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 17360 17361 final int realMoveId = mNextMoveId.getAndIncrement(); 17362 final Bundle extras = new Bundle(); 17363 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 17364 mMoveCallbacks.notifyCreated(realMoveId, extras); 17365 17366 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 17367 @Override 17368 public void onCreated(int moveId, Bundle extras) { 17369 // Ignored 17370 } 17371 17372 @Override 17373 public void onStatusChanged(int moveId, int status, long estMillis) { 17374 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 17375 } 17376 }; 17377 17378 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17379 storage.setPrimaryStorageUuid(volumeUuid, callback); 17380 return realMoveId; 17381 } 17382 17383 @Override 17384 public int getMoveStatus(int moveId) { 17385 mContext.enforceCallingOrSelfPermission( 17386 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 17387 return mMoveCallbacks.mLastStatus.get(moveId); 17388 } 17389 17390 @Override 17391 public void registerMoveCallback(IPackageMoveObserver callback) { 17392 mContext.enforceCallingOrSelfPermission( 17393 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 17394 mMoveCallbacks.register(callback); 17395 } 17396 17397 @Override 17398 public void unregisterMoveCallback(IPackageMoveObserver callback) { 17399 mContext.enforceCallingOrSelfPermission( 17400 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 17401 mMoveCallbacks.unregister(callback); 17402 } 17403 17404 @Override 17405 public boolean setInstallLocation(int loc) { 17406 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 17407 null); 17408 if (getInstallLocation() == loc) { 17409 return true; 17410 } 17411 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 17412 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 17413 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 17414 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 17415 return true; 17416 } 17417 return false; 17418 } 17419 17420 @Override 17421 public int getInstallLocation() { 17422 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 17423 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 17424 PackageHelper.APP_INSTALL_AUTO); 17425 } 17426 17427 /** Called by UserManagerService */ 17428 void cleanUpUser(UserManagerService userManager, int userHandle) { 17429 synchronized (mPackages) { 17430 mDirtyUsers.remove(userHandle); 17431 mUserNeedsBadging.delete(userHandle); 17432 mSettings.removeUserLPw(userHandle); 17433 mPendingBroadcasts.remove(userHandle); 17434 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 17435 } 17436 synchronized (mInstallLock) { 17437 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17438 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 17439 final String volumeUuid = vol.getFsUuid(); 17440 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 17441 try { 17442 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 17443 } catch (InstallerException e) { 17444 Slog.w(TAG, "Failed to remove user data", e); 17445 } 17446 } 17447 synchronized (mPackages) { 17448 removeUnusedPackagesLILPw(userManager, userHandle); 17449 } 17450 } 17451 } 17452 17453 /** 17454 * We're removing userHandle and would like to remove any downloaded packages 17455 * that are no longer in use by any other user. 17456 * @param userHandle the user being removed 17457 */ 17458 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 17459 final boolean DEBUG_CLEAN_APKS = false; 17460 int [] users = userManager.getUserIds(); 17461 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 17462 while (psit.hasNext()) { 17463 PackageSetting ps = psit.next(); 17464 if (ps.pkg == null) { 17465 continue; 17466 } 17467 final String packageName = ps.pkg.packageName; 17468 // Skip over if system app 17469 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 17470 continue; 17471 } 17472 if (DEBUG_CLEAN_APKS) { 17473 Slog.i(TAG, "Checking package " + packageName); 17474 } 17475 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 17476 if (keep) { 17477 if (DEBUG_CLEAN_APKS) { 17478 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 17479 } 17480 } else { 17481 for (int i = 0; i < users.length; i++) { 17482 if (users[i] != userHandle && ps.getInstalled(users[i])) { 17483 keep = true; 17484 if (DEBUG_CLEAN_APKS) { 17485 Slog.i(TAG, " Keeping package " + packageName + " for user " 17486 + users[i]); 17487 } 17488 break; 17489 } 17490 } 17491 } 17492 if (!keep) { 17493 if (DEBUG_CLEAN_APKS) { 17494 Slog.i(TAG, " Removing package " + packageName); 17495 } 17496 mHandler.post(new Runnable() { 17497 public void run() { 17498 deletePackageX(packageName, userHandle, 0); 17499 } //end run 17500 }); 17501 } 17502 } 17503 } 17504 17505 /** Called by UserManagerService */ 17506 void createNewUser(int userHandle) { 17507 synchronized (mInstallLock) { 17508 try { 17509 mInstaller.createUserConfig(userHandle); 17510 } catch (InstallerException e) { 17511 Slog.w(TAG, "Failed to create user config", e); 17512 } 17513 mSettings.createNewUserLI(this, mInstaller, userHandle); 17514 } 17515 synchronized (mPackages) { 17516 applyFactoryDefaultBrowserLPw(userHandle); 17517 primeDomainVerificationsLPw(userHandle); 17518 } 17519 } 17520 17521 void newUserCreated(final int userHandle) { 17522 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 17523 // If permission review for legacy apps is required, we represent 17524 // dagerous permissions for such apps as always granted runtime 17525 // permissions to keep per user flag state whether review is needed. 17526 // Hence, if a new user is added we have to propagate dangerous 17527 // permission grants for these legacy apps. 17528 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 17529 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 17530 | UPDATE_PERMISSIONS_REPLACE_ALL); 17531 } 17532 } 17533 17534 @Override 17535 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 17536 mContext.enforceCallingOrSelfPermission( 17537 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 17538 "Only package verification agents can read the verifier device identity"); 17539 17540 synchronized (mPackages) { 17541 return mSettings.getVerifierDeviceIdentityLPw(); 17542 } 17543 } 17544 17545 @Override 17546 public void setPermissionEnforced(String permission, boolean enforced) { 17547 // TODO: Now that we no longer change GID for storage, this should to away. 17548 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 17549 "setPermissionEnforced"); 17550 if (READ_EXTERNAL_STORAGE.equals(permission)) { 17551 synchronized (mPackages) { 17552 if (mSettings.mReadExternalStorageEnforced == null 17553 || mSettings.mReadExternalStorageEnforced != enforced) { 17554 mSettings.mReadExternalStorageEnforced = enforced; 17555 mSettings.writeLPr(); 17556 } 17557 } 17558 // kill any non-foreground processes so we restart them and 17559 // grant/revoke the GID. 17560 final IActivityManager am = ActivityManagerNative.getDefault(); 17561 if (am != null) { 17562 final long token = Binder.clearCallingIdentity(); 17563 try { 17564 am.killProcessesBelowForeground("setPermissionEnforcement"); 17565 } catch (RemoteException e) { 17566 } finally { 17567 Binder.restoreCallingIdentity(token); 17568 } 17569 } 17570 } else { 17571 throw new IllegalArgumentException("No selective enforcement for " + permission); 17572 } 17573 } 17574 17575 @Override 17576 @Deprecated 17577 public boolean isPermissionEnforced(String permission) { 17578 return true; 17579 } 17580 17581 @Override 17582 public boolean isStorageLow() { 17583 final long token = Binder.clearCallingIdentity(); 17584 try { 17585 final DeviceStorageMonitorInternal 17586 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 17587 if (dsm != null) { 17588 return dsm.isMemoryLow(); 17589 } else { 17590 return false; 17591 } 17592 } finally { 17593 Binder.restoreCallingIdentity(token); 17594 } 17595 } 17596 17597 @Override 17598 public IPackageInstaller getPackageInstaller() { 17599 return mInstallerService; 17600 } 17601 17602 private boolean userNeedsBadging(int userId) { 17603 int index = mUserNeedsBadging.indexOfKey(userId); 17604 if (index < 0) { 17605 final UserInfo userInfo; 17606 final long token = Binder.clearCallingIdentity(); 17607 try { 17608 userInfo = sUserManager.getUserInfo(userId); 17609 } finally { 17610 Binder.restoreCallingIdentity(token); 17611 } 17612 final boolean b; 17613 if (userInfo != null && userInfo.isManagedProfile()) { 17614 b = true; 17615 } else { 17616 b = false; 17617 } 17618 mUserNeedsBadging.put(userId, b); 17619 return b; 17620 } 17621 return mUserNeedsBadging.valueAt(index); 17622 } 17623 17624 @Override 17625 public KeySet getKeySetByAlias(String packageName, String alias) { 17626 if (packageName == null || alias == null) { 17627 return null; 17628 } 17629 synchronized(mPackages) { 17630 final PackageParser.Package pkg = mPackages.get(packageName); 17631 if (pkg == null) { 17632 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17633 throw new IllegalArgumentException("Unknown package: " + packageName); 17634 } 17635 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17636 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 17637 } 17638 } 17639 17640 @Override 17641 public KeySet getSigningKeySet(String packageName) { 17642 if (packageName == null) { 17643 return null; 17644 } 17645 synchronized(mPackages) { 17646 final PackageParser.Package pkg = mPackages.get(packageName); 17647 if (pkg == null) { 17648 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17649 throw new IllegalArgumentException("Unknown package: " + packageName); 17650 } 17651 if (pkg.applicationInfo.uid != Binder.getCallingUid() 17652 && Process.SYSTEM_UID != Binder.getCallingUid()) { 17653 throw new SecurityException("May not access signing KeySet of other apps."); 17654 } 17655 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17656 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 17657 } 17658 } 17659 17660 @Override 17661 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 17662 if (packageName == null || ks == null) { 17663 return false; 17664 } 17665 synchronized(mPackages) { 17666 final PackageParser.Package pkg = mPackages.get(packageName); 17667 if (pkg == null) { 17668 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17669 throw new IllegalArgumentException("Unknown package: " + packageName); 17670 } 17671 IBinder ksh = ks.getToken(); 17672 if (ksh instanceof KeySetHandle) { 17673 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17674 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 17675 } 17676 return false; 17677 } 17678 } 17679 17680 @Override 17681 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 17682 if (packageName == null || ks == null) { 17683 return false; 17684 } 17685 synchronized(mPackages) { 17686 final PackageParser.Package pkg = mPackages.get(packageName); 17687 if (pkg == null) { 17688 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17689 throw new IllegalArgumentException("Unknown package: " + packageName); 17690 } 17691 IBinder ksh = ks.getToken(); 17692 if (ksh instanceof KeySetHandle) { 17693 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17694 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 17695 } 17696 return false; 17697 } 17698 } 17699 17700 private void deletePackageIfUnusedLPr(final String packageName) { 17701 PackageSetting ps = mSettings.mPackages.get(packageName); 17702 if (ps == null) { 17703 return; 17704 } 17705 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 17706 // TODO Implement atomic delete if package is unused 17707 // It is currently possible that the package will be deleted even if it is installed 17708 // after this method returns. 17709 mHandler.post(new Runnable() { 17710 public void run() { 17711 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 17712 } 17713 }); 17714 } 17715 } 17716 17717 /** 17718 * Check and throw if the given before/after packages would be considered a 17719 * downgrade. 17720 */ 17721 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 17722 throws PackageManagerException { 17723 if (after.versionCode < before.mVersionCode) { 17724 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17725 "Update version code " + after.versionCode + " is older than current " 17726 + before.mVersionCode); 17727 } else if (after.versionCode == before.mVersionCode) { 17728 if (after.baseRevisionCode < before.baseRevisionCode) { 17729 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17730 "Update base revision code " + after.baseRevisionCode 17731 + " is older than current " + before.baseRevisionCode); 17732 } 17733 17734 if (!ArrayUtils.isEmpty(after.splitNames)) { 17735 for (int i = 0; i < after.splitNames.length; i++) { 17736 final String splitName = after.splitNames[i]; 17737 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 17738 if (j != -1) { 17739 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 17740 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17741 "Update split " + splitName + " revision code " 17742 + after.splitRevisionCodes[i] + " is older than current " 17743 + before.splitRevisionCodes[j]); 17744 } 17745 } 17746 } 17747 } 17748 } 17749 } 17750 17751 private static class MoveCallbacks extends Handler { 17752 private static final int MSG_CREATED = 1; 17753 private static final int MSG_STATUS_CHANGED = 2; 17754 17755 private final RemoteCallbackList<IPackageMoveObserver> 17756 mCallbacks = new RemoteCallbackList<>(); 17757 17758 private final SparseIntArray mLastStatus = new SparseIntArray(); 17759 17760 public MoveCallbacks(Looper looper) { 17761 super(looper); 17762 } 17763 17764 public void register(IPackageMoveObserver callback) { 17765 mCallbacks.register(callback); 17766 } 17767 17768 public void unregister(IPackageMoveObserver callback) { 17769 mCallbacks.unregister(callback); 17770 } 17771 17772 @Override 17773 public void handleMessage(Message msg) { 17774 final SomeArgs args = (SomeArgs) msg.obj; 17775 final int n = mCallbacks.beginBroadcast(); 17776 for (int i = 0; i < n; i++) { 17777 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 17778 try { 17779 invokeCallback(callback, msg.what, args); 17780 } catch (RemoteException ignored) { 17781 } 17782 } 17783 mCallbacks.finishBroadcast(); 17784 args.recycle(); 17785 } 17786 17787 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 17788 throws RemoteException { 17789 switch (what) { 17790 case MSG_CREATED: { 17791 callback.onCreated(args.argi1, (Bundle) args.arg2); 17792 break; 17793 } 17794 case MSG_STATUS_CHANGED: { 17795 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 17796 break; 17797 } 17798 } 17799 } 17800 17801 private void notifyCreated(int moveId, Bundle extras) { 17802 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 17803 17804 final SomeArgs args = SomeArgs.obtain(); 17805 args.argi1 = moveId; 17806 args.arg2 = extras; 17807 obtainMessage(MSG_CREATED, args).sendToTarget(); 17808 } 17809 17810 private void notifyStatusChanged(int moveId, int status) { 17811 notifyStatusChanged(moveId, status, -1); 17812 } 17813 17814 private void notifyStatusChanged(int moveId, int status, long estMillis) { 17815 Slog.v(TAG, "Move " + moveId + " status " + status); 17816 17817 final SomeArgs args = SomeArgs.obtain(); 17818 args.argi1 = moveId; 17819 args.argi2 = status; 17820 args.arg3 = estMillis; 17821 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 17822 17823 synchronized (mLastStatus) { 17824 mLastStatus.put(moveId, status); 17825 } 17826 } 17827 } 17828 17829 private final static class OnPermissionChangeListeners extends Handler { 17830 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 17831 17832 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 17833 new RemoteCallbackList<>(); 17834 17835 public OnPermissionChangeListeners(Looper looper) { 17836 super(looper); 17837 } 17838 17839 @Override 17840 public void handleMessage(Message msg) { 17841 switch (msg.what) { 17842 case MSG_ON_PERMISSIONS_CHANGED: { 17843 final int uid = msg.arg1; 17844 handleOnPermissionsChanged(uid); 17845 } break; 17846 } 17847 } 17848 17849 public void addListenerLocked(IOnPermissionsChangeListener listener) { 17850 mPermissionListeners.register(listener); 17851 17852 } 17853 17854 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 17855 mPermissionListeners.unregister(listener); 17856 } 17857 17858 public void onPermissionsChanged(int uid) { 17859 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 17860 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 17861 } 17862 } 17863 17864 private void handleOnPermissionsChanged(int uid) { 17865 final int count = mPermissionListeners.beginBroadcast(); 17866 try { 17867 for (int i = 0; i < count; i++) { 17868 IOnPermissionsChangeListener callback = mPermissionListeners 17869 .getBroadcastItem(i); 17870 try { 17871 callback.onPermissionsChanged(uid); 17872 } catch (RemoteException e) { 17873 Log.e(TAG, "Permission listener is dead", e); 17874 } 17875 } 17876 } finally { 17877 mPermissionListeners.finishBroadcast(); 17878 } 17879 } 17880 } 17881 17882 private class PackageManagerInternalImpl extends PackageManagerInternal { 17883 @Override 17884 public void setLocationPackagesProvider(PackagesProvider provider) { 17885 synchronized (mPackages) { 17886 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 17887 } 17888 } 17889 17890 @Override 17891 public void setImePackagesProvider(PackagesProvider provider) { 17892 synchronized (mPackages) { 17893 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 17894 } 17895 } 17896 17897 @Override 17898 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 17899 synchronized (mPackages) { 17900 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 17901 } 17902 } 17903 17904 @Override 17905 public void setSmsAppPackagesProvider(PackagesProvider provider) { 17906 synchronized (mPackages) { 17907 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 17908 } 17909 } 17910 17911 @Override 17912 public void setDialerAppPackagesProvider(PackagesProvider provider) { 17913 synchronized (mPackages) { 17914 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 17915 } 17916 } 17917 17918 @Override 17919 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 17920 synchronized (mPackages) { 17921 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 17922 } 17923 } 17924 17925 @Override 17926 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 17927 synchronized (mPackages) { 17928 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 17929 } 17930 } 17931 17932 @Override 17933 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 17934 synchronized (mPackages) { 17935 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 17936 packageName, userId); 17937 } 17938 } 17939 17940 @Override 17941 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 17942 synchronized (mPackages) { 17943 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 17944 packageName, userId); 17945 } 17946 } 17947 17948 @Override 17949 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 17950 synchronized (mPackages) { 17951 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 17952 packageName, userId); 17953 } 17954 } 17955 17956 @Override 17957 public void setKeepUninstalledPackages(final List<String> packageList) { 17958 Preconditions.checkNotNull(packageList); 17959 List<String> removedFromList = null; 17960 synchronized (mPackages) { 17961 if (mKeepUninstalledPackages != null) { 17962 final int packagesCount = mKeepUninstalledPackages.size(); 17963 for (int i = 0; i < packagesCount; i++) { 17964 String oldPackage = mKeepUninstalledPackages.get(i); 17965 if (packageList != null && packageList.contains(oldPackage)) { 17966 continue; 17967 } 17968 if (removedFromList == null) { 17969 removedFromList = new ArrayList<>(); 17970 } 17971 removedFromList.add(oldPackage); 17972 } 17973 } 17974 mKeepUninstalledPackages = new ArrayList<>(packageList); 17975 if (removedFromList != null) { 17976 final int removedCount = removedFromList.size(); 17977 for (int i = 0; i < removedCount; i++) { 17978 deletePackageIfUnusedLPr(removedFromList.get(i)); 17979 } 17980 } 17981 } 17982 } 17983 17984 @Override 17985 public boolean isPermissionsReviewRequired(String packageName, int userId) { 17986 synchronized (mPackages) { 17987 // If we do not support permission review, done. 17988 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 17989 return false; 17990 } 17991 17992 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 17993 if (packageSetting == null) { 17994 return false; 17995 } 17996 17997 // Permission review applies only to apps not supporting the new permission model. 17998 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 17999 return false; 18000 } 18001 18002 // Legacy apps have the permission and get user consent on launch. 18003 PermissionsState permissionsState = packageSetting.getPermissionsState(); 18004 return permissionsState.isPermissionReviewRequired(userId); 18005 } 18006 } 18007 } 18008 18009 @Override 18010 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 18011 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 18012 synchronized (mPackages) { 18013 final long identity = Binder.clearCallingIdentity(); 18014 try { 18015 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 18016 packageNames, userId); 18017 } finally { 18018 Binder.restoreCallingIdentity(identity); 18019 } 18020 } 18021 } 18022 18023 private static void enforceSystemOrPhoneCaller(String tag) { 18024 int callingUid = Binder.getCallingUid(); 18025 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 18026 throw new SecurityException( 18027 "Cannot call " + tag + " from UID " + callingUid); 18028 } 18029 } 18030} 18031