PackageManagerService.java revision 3bcf800c50238ac2df19c9fc0375c303905524b0
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; 79import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 80import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 81import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 82import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 83import static com.android.internal.util.ArrayUtils.appendInt; 84import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 85import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 86import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 87import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 88import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 89import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 90import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 91import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 92import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 93 94import android.Manifest; 95import android.annotation.NonNull; 96import android.annotation.Nullable; 97import android.app.ActivityManager; 98import android.app.ActivityManagerNative; 99import android.app.AppGlobals; 100import android.app.IActivityManager; 101import android.app.admin.IDevicePolicyManager; 102import android.app.backup.IBackupManager; 103import android.content.BroadcastReceiver; 104import android.content.ComponentName; 105import android.content.Context; 106import android.content.IIntentReceiver; 107import android.content.Intent; 108import android.content.IntentFilter; 109import android.content.IntentSender; 110import android.content.IntentSender.SendIntentException; 111import android.content.ServiceConnection; 112import android.content.pm.ActivityInfo; 113import android.content.pm.ApplicationInfo; 114import android.content.pm.AppsQueryHelper; 115import android.content.pm.ComponentInfo; 116import android.content.pm.EphemeralApplicationInfo; 117import android.content.pm.EphemeralResolveInfo; 118import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 119import android.content.pm.FeatureInfo; 120import android.content.pm.IOnPermissionsChangeListener; 121import android.content.pm.IPackageDataObserver; 122import android.content.pm.IPackageDeleteObserver; 123import android.content.pm.IPackageDeleteObserver2; 124import android.content.pm.IPackageInstallObserver2; 125import android.content.pm.IPackageInstaller; 126import android.content.pm.IPackageManager; 127import android.content.pm.IPackageMoveObserver; 128import android.content.pm.IPackageStatsObserver; 129import android.content.pm.InstrumentationInfo; 130import android.content.pm.IntentFilterVerificationInfo; 131import android.content.pm.KeySet; 132import android.content.pm.PackageCleanItem; 133import android.content.pm.PackageInfo; 134import android.content.pm.PackageInfoLite; 135import android.content.pm.PackageInstaller; 136import android.content.pm.PackageManager; 137import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 138import android.content.pm.PackageManagerInternal; 139import android.content.pm.PackageParser; 140import android.content.pm.PackageParser.ActivityIntentInfo; 141import android.content.pm.PackageParser.PackageLite; 142import android.content.pm.PackageParser.PackageParserException; 143import android.content.pm.PackageStats; 144import android.content.pm.PackageUserState; 145import android.content.pm.ParceledListSlice; 146import android.content.pm.PermissionGroupInfo; 147import android.content.pm.PermissionInfo; 148import android.content.pm.ProviderInfo; 149import android.content.pm.ResolveInfo; 150import android.content.pm.ServiceInfo; 151import android.content.pm.Signature; 152import android.content.pm.UserInfo; 153import android.content.pm.VerificationParams; 154import android.content.pm.VerifierDeviceIdentity; 155import android.content.pm.VerifierInfo; 156import android.content.res.Resources; 157import android.graphics.Bitmap; 158import android.hardware.display.DisplayManager; 159import android.net.Uri; 160import android.os.Binder; 161import android.os.Build; 162import android.os.Bundle; 163import android.os.Debug; 164import android.os.Environment; 165import android.os.Environment.UserEnvironment; 166import android.os.FileUtils; 167import android.os.Handler; 168import android.os.IBinder; 169import android.os.Looper; 170import android.os.Message; 171import android.os.Parcel; 172import android.os.ParcelFileDescriptor; 173import android.os.Process; 174import android.os.RemoteCallbackList; 175import android.os.RemoteException; 176import android.os.ResultReceiver; 177import android.os.SELinux; 178import android.os.ServiceManager; 179import android.os.SystemClock; 180import android.os.SystemProperties; 181import android.os.Trace; 182import android.os.UserHandle; 183import android.os.UserManager; 184import android.os.storage.IMountService; 185import android.os.storage.MountServiceInternal; 186import android.os.storage.StorageEventListener; 187import android.os.storage.StorageManager; 188import android.os.storage.VolumeInfo; 189import android.os.storage.VolumeRecord; 190import android.security.KeyStore; 191import android.security.SystemKeyStore; 192import android.system.ErrnoException; 193import android.system.Os; 194import android.text.TextUtils; 195import android.text.format.DateUtils; 196import android.util.ArrayMap; 197import android.util.ArraySet; 198import android.util.AtomicFile; 199import android.util.DisplayMetrics; 200import android.util.EventLog; 201import android.util.ExceptionUtils; 202import android.util.Log; 203import android.util.LogPrinter; 204import android.util.MathUtils; 205import android.util.PrintStreamPrinter; 206import android.util.Slog; 207import android.util.SparseArray; 208import android.util.SparseBooleanArray; 209import android.util.SparseIntArray; 210import android.util.Xml; 211import android.view.Display; 212 213import com.android.internal.R; 214import com.android.internal.annotations.GuardedBy; 215import com.android.internal.app.IMediaContainerService; 216import com.android.internal.app.ResolverActivity; 217import com.android.internal.content.NativeLibraryHelper; 218import com.android.internal.content.PackageHelper; 219import com.android.internal.os.IParcelFileDescriptorFactory; 220import com.android.internal.os.InstallerConnection.InstallerException; 221import com.android.internal.os.SomeArgs; 222import com.android.internal.os.Zygote; 223import com.android.internal.util.ArrayUtils; 224import com.android.internal.util.FastPrintWriter; 225import com.android.internal.util.FastXmlSerializer; 226import com.android.internal.util.IndentingPrintWriter; 227import com.android.internal.util.Preconditions; 228import com.android.internal.util.XmlUtils; 229import com.android.server.EventLogTags; 230import com.android.server.FgThread; 231import com.android.server.IntentResolver; 232import com.android.server.LocalServices; 233import com.android.server.ServiceThread; 234import com.android.server.SystemConfig; 235import com.android.server.Watchdog; 236import com.android.server.pm.Installer.StorageFlags; 237import com.android.server.pm.PermissionsState.PermissionState; 238import com.android.server.pm.Settings.DatabaseVersion; 239import com.android.server.pm.Settings.VersionInfo; 240import com.android.server.storage.DeviceStorageMonitorInternal; 241 242import dalvik.system.DexFile; 243import dalvik.system.VMRuntime; 244 245import libcore.io.IoUtils; 246import libcore.util.EmptyArray; 247 248import org.xmlpull.v1.XmlPullParser; 249import org.xmlpull.v1.XmlPullParserException; 250import org.xmlpull.v1.XmlSerializer; 251 252import java.io.BufferedInputStream; 253import java.io.BufferedOutputStream; 254import java.io.BufferedReader; 255import java.io.ByteArrayInputStream; 256import java.io.ByteArrayOutputStream; 257import java.io.File; 258import java.io.FileDescriptor; 259import java.io.FileNotFoundException; 260import java.io.FileOutputStream; 261import java.io.FileReader; 262import java.io.FilenameFilter; 263import java.io.IOException; 264import java.io.InputStream; 265import java.io.PrintWriter; 266import java.nio.charset.StandardCharsets; 267import java.security.MessageDigest; 268import java.security.NoSuchAlgorithmException; 269import java.security.PublicKey; 270import java.security.cert.CertificateEncodingException; 271import java.security.cert.CertificateException; 272import java.text.SimpleDateFormat; 273import java.util.ArrayList; 274import java.util.Arrays; 275import java.util.Collection; 276import java.util.Collections; 277import java.util.Comparator; 278import java.util.Date; 279import java.util.Iterator; 280import java.util.List; 281import java.util.Map; 282import java.util.Objects; 283import java.util.Set; 284import java.util.concurrent.CountDownLatch; 285import java.util.concurrent.TimeUnit; 286import java.util.concurrent.atomic.AtomicBoolean; 287import java.util.concurrent.atomic.AtomicInteger; 288import java.util.concurrent.atomic.AtomicLong; 289 290/** 291 * Keep track of all those .apks everywhere. 292 * 293 * This is very central to the platform's security; please run the unit 294 * tests whenever making modifications here: 295 * 296runtest -c android.content.pm.PackageManagerTests frameworks-core 297 * 298 * {@hide} 299 */ 300public class PackageManagerService extends IPackageManager.Stub { 301 static final String TAG = "PackageManager"; 302 static final boolean DEBUG_SETTINGS = false; 303 static final boolean DEBUG_PREFERRED = false; 304 static final boolean DEBUG_UPGRADE = false; 305 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 306 private static final boolean DEBUG_BACKUP = false; 307 private static final boolean DEBUG_INSTALL = false; 308 private static final boolean DEBUG_REMOVE = false; 309 private static final boolean DEBUG_BROADCASTS = false; 310 private static final boolean DEBUG_SHOW_INFO = false; 311 private static final boolean DEBUG_PACKAGE_INFO = false; 312 private static final boolean DEBUG_INTENT_MATCHING = false; 313 private static final boolean DEBUG_PACKAGE_SCANNING = false; 314 private static final boolean DEBUG_VERIFY = false; 315 private static final boolean DEBUG_DEXOPT = false; 316 private static final boolean DEBUG_ABI_SELECTION = false; 317 private static final boolean DEBUG_EPHEMERAL = false; 318 private static final boolean DEBUG_TRIAGED_MISSING = false; 319 private static final boolean DEBUG_APP_DATA = false; 320 321 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 322 323 private static final boolean DISABLE_EPHEMERAL_APPS = true; 324 325 private static final int RADIO_UID = Process.PHONE_UID; 326 private static final int LOG_UID = Process.LOG_UID; 327 private static final int NFC_UID = Process.NFC_UID; 328 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 329 private static final int SHELL_UID = Process.SHELL_UID; 330 331 // Cap the size of permission trees that 3rd party apps can define 332 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 333 334 // Suffix used during package installation when copying/moving 335 // package apks to install directory. 336 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 337 338 static final int SCAN_NO_DEX = 1<<1; 339 static final int SCAN_FORCE_DEX = 1<<2; 340 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 341 static final int SCAN_NEW_INSTALL = 1<<4; 342 static final int SCAN_NO_PATHS = 1<<5; 343 static final int SCAN_UPDATE_TIME = 1<<6; 344 static final int SCAN_DEFER_DEX = 1<<7; 345 static final int SCAN_BOOTING = 1<<8; 346 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 347 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 348 static final int SCAN_REPLACING = 1<<11; 349 static final int SCAN_REQUIRE_KNOWN = 1<<12; 350 static final int SCAN_MOVE = 1<<13; 351 static final int SCAN_INITIAL = 1<<14; 352 353 static final int REMOVE_CHATTY = 1<<16; 354 355 private static final int[] EMPTY_INT_ARRAY = new int[0]; 356 357 /** 358 * Timeout (in milliseconds) after which the watchdog should declare that 359 * our handler thread is wedged. The usual default for such things is one 360 * minute but we sometimes do very lengthy I/O operations on this thread, 361 * such as installing multi-gigabyte applications, so ours needs to be longer. 362 */ 363 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 364 365 /** 366 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 367 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 368 * settings entry if available, otherwise we use the hardcoded default. If it's been 369 * more than this long since the last fstrim, we force one during the boot sequence. 370 * 371 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 372 * one gets run at the next available charging+idle time. This final mandatory 373 * no-fstrim check kicks in only of the other scheduling criteria is never met. 374 */ 375 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 376 377 /** 378 * Whether verification is enabled by default. 379 */ 380 private static final boolean DEFAULT_VERIFY_ENABLE = true; 381 382 /** 383 * The default maximum time to wait for the verification agent to return in 384 * milliseconds. 385 */ 386 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 387 388 /** 389 * The default response for package verification timeout. 390 * 391 * This can be either PackageManager.VERIFICATION_ALLOW or 392 * PackageManager.VERIFICATION_REJECT. 393 */ 394 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 395 396 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 397 398 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 399 DEFAULT_CONTAINER_PACKAGE, 400 "com.android.defcontainer.DefaultContainerService"); 401 402 private static final String KILL_APP_REASON_GIDS_CHANGED = 403 "permission grant or revoke changed gids"; 404 405 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 406 "permissions revoked"; 407 408 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 409 410 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 411 412 /** Permission grant: not grant the permission. */ 413 private static final int GRANT_DENIED = 1; 414 415 /** Permission grant: grant the permission as an install permission. */ 416 private static final int GRANT_INSTALL = 2; 417 418 /** Permission grant: grant the permission as a runtime one. */ 419 private static final int GRANT_RUNTIME = 3; 420 421 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 422 private static final int GRANT_UPGRADE = 4; 423 424 /** Canonical intent used to identify what counts as a "web browser" app */ 425 private static final Intent sBrowserIntent; 426 static { 427 sBrowserIntent = new Intent(); 428 sBrowserIntent.setAction(Intent.ACTION_VIEW); 429 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 430 sBrowserIntent.setData(Uri.parse("http:")); 431 } 432 433 final ServiceThread mHandlerThread; 434 435 final PackageHandler mHandler; 436 437 /** 438 * Messages for {@link #mHandler} that need to wait for system ready before 439 * being dispatched. 440 */ 441 private ArrayList<Message> mPostSystemReadyMessages; 442 443 final int mSdkVersion = Build.VERSION.SDK_INT; 444 445 final Context mContext; 446 final boolean mFactoryTest; 447 final boolean mOnlyCore; 448 final DisplayMetrics mMetrics; 449 final int mDefParseFlags; 450 final String[] mSeparateProcesses; 451 final boolean mIsUpgrade; 452 453 /** The location for ASEC container files on internal storage. */ 454 final String mAsecInternalPath; 455 456 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 457 // LOCK HELD. Can be called with mInstallLock held. 458 @GuardedBy("mInstallLock") 459 final Installer mInstaller; 460 461 /** Directory where installed third-party apps stored */ 462 final File mAppInstallDir; 463 final File mEphemeralInstallDir; 464 465 /** 466 * Directory to which applications installed internally have their 467 * 32 bit native libraries copied. 468 */ 469 private File mAppLib32InstallDir; 470 471 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 472 // apps. 473 final File mDrmAppPrivateInstallDir; 474 475 // ---------------------------------------------------------------- 476 477 // Lock for state used when installing and doing other long running 478 // operations. Methods that must be called with this lock held have 479 // the suffix "LI". 480 final Object mInstallLock = new Object(); 481 482 // ---------------------------------------------------------------- 483 484 // Keys are String (package name), values are Package. This also serves 485 // as the lock for the global state. Methods that must be called with 486 // this lock held have the prefix "LP". 487 @GuardedBy("mPackages") 488 final ArrayMap<String, PackageParser.Package> mPackages = 489 new ArrayMap<String, PackageParser.Package>(); 490 491 // Tracks available target package names -> overlay package paths. 492 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 493 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 494 495 /** 496 * Tracks new system packages [received in an OTA] that we expect to 497 * find updated user-installed versions. Keys are package name, values 498 * are package location. 499 */ 500 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 501 502 /** 503 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 504 */ 505 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 506 /** 507 * Whether or not system app permissions should be promoted from install to runtime. 508 */ 509 boolean mPromoteSystemApps; 510 511 final Settings mSettings; 512 boolean mRestoredSettings; 513 514 // System configuration read by SystemConfig. 515 final int[] mGlobalGids; 516 final SparseArray<ArraySet<String>> mSystemPermissions; 517 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 518 519 // If mac_permissions.xml was found for seinfo labeling. 520 boolean mFoundPolicyFile; 521 522 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 523 524 public static final class SharedLibraryEntry { 525 public final String path; 526 public final String apk; 527 528 SharedLibraryEntry(String _path, String _apk) { 529 path = _path; 530 apk = _apk; 531 } 532 } 533 534 // Currently known shared libraries. 535 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 536 new ArrayMap<String, SharedLibraryEntry>(); 537 538 // All available activities, for your resolving pleasure. 539 final ActivityIntentResolver mActivities = 540 new ActivityIntentResolver(); 541 542 // All available receivers, for your resolving pleasure. 543 final ActivityIntentResolver mReceivers = 544 new ActivityIntentResolver(); 545 546 // All available services, for your resolving pleasure. 547 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 548 549 // All available providers, for your resolving pleasure. 550 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 551 552 // Mapping from provider base names (first directory in content URI codePath) 553 // to the provider information. 554 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 555 new ArrayMap<String, PackageParser.Provider>(); 556 557 // Mapping from instrumentation class names to info about them. 558 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 559 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 560 561 // Mapping from permission names to info about them. 562 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 563 new ArrayMap<String, PackageParser.PermissionGroup>(); 564 565 // Packages whose data we have transfered into another package, thus 566 // should no longer exist. 567 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 568 569 // Broadcast actions that are only available to the system. 570 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 571 572 /** List of packages waiting for verification. */ 573 final SparseArray<PackageVerificationState> mPendingVerification 574 = new SparseArray<PackageVerificationState>(); 575 576 /** Set of packages associated with each app op permission. */ 577 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 578 579 final PackageInstallerService mInstallerService; 580 581 private final PackageDexOptimizer mPackageDexOptimizer; 582 583 private AtomicInteger mNextMoveId = new AtomicInteger(); 584 private final MoveCallbacks mMoveCallbacks; 585 586 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 587 588 // Cache of users who need badging. 589 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 590 591 /** Token for keys in mPendingVerification. */ 592 private int mPendingVerificationToken = 0; 593 594 volatile boolean mSystemReady; 595 volatile boolean mSafeMode; 596 volatile boolean mHasSystemUidErrors; 597 598 ApplicationInfo mAndroidApplication; 599 final ActivityInfo mResolveActivity = new ActivityInfo(); 600 final ResolveInfo mResolveInfo = new ResolveInfo(); 601 ComponentName mResolveComponentName; 602 PackageParser.Package mPlatformPackage; 603 ComponentName mCustomResolverComponentName; 604 605 boolean mResolverReplaced = false; 606 607 private final @Nullable ComponentName mIntentFilterVerifierComponent; 608 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 609 610 private int mIntentFilterVerificationToken = 0; 611 612 /** Component that knows whether or not an ephemeral application exists */ 613 final ComponentName mEphemeralResolverComponent; 614 /** The service connection to the ephemeral resolver */ 615 final EphemeralResolverConnection mEphemeralResolverConnection; 616 617 /** Component used to install ephemeral applications */ 618 final ComponentName mEphemeralInstallerComponent; 619 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 620 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 621 622 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 623 = new SparseArray<IntentFilterVerificationState>(); 624 625 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 626 new DefaultPermissionGrantPolicy(this); 627 628 // List of packages names to keep cached, even if they are uninstalled for all users 629 private List<String> mKeepUninstalledPackages; 630 631 private boolean mUseJitProfiles = 632 SystemProperties.getBoolean("dalvik.vm.usejitprofiles", false); 633 634 private static class IFVerificationParams { 635 PackageParser.Package pkg; 636 boolean replacing; 637 int userId; 638 int verifierUid; 639 640 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 641 int _userId, int _verifierUid) { 642 pkg = _pkg; 643 replacing = _replacing; 644 userId = _userId; 645 replacing = _replacing; 646 verifierUid = _verifierUid; 647 } 648 } 649 650 private interface IntentFilterVerifier<T extends IntentFilter> { 651 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 652 T filter, String packageName); 653 void startVerifications(int userId); 654 void receiveVerificationResponse(int verificationId); 655 } 656 657 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 658 private Context mContext; 659 private ComponentName mIntentFilterVerifierComponent; 660 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 661 662 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 663 mContext = context; 664 mIntentFilterVerifierComponent = verifierComponent; 665 } 666 667 private String getDefaultScheme() { 668 return IntentFilter.SCHEME_HTTPS; 669 } 670 671 @Override 672 public void startVerifications(int userId) { 673 // Launch verifications requests 674 int count = mCurrentIntentFilterVerifications.size(); 675 for (int n=0; n<count; n++) { 676 int verificationId = mCurrentIntentFilterVerifications.get(n); 677 final IntentFilterVerificationState ivs = 678 mIntentFilterVerificationStates.get(verificationId); 679 680 String packageName = ivs.getPackageName(); 681 682 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 683 final int filterCount = filters.size(); 684 ArraySet<String> domainsSet = new ArraySet<>(); 685 for (int m=0; m<filterCount; m++) { 686 PackageParser.ActivityIntentInfo filter = filters.get(m); 687 domainsSet.addAll(filter.getHostsList()); 688 } 689 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 690 synchronized (mPackages) { 691 if (mSettings.createIntentFilterVerificationIfNeededLPw( 692 packageName, domainsList) != null) { 693 scheduleWriteSettingsLocked(); 694 } 695 } 696 sendVerificationRequest(userId, verificationId, ivs); 697 } 698 mCurrentIntentFilterVerifications.clear(); 699 } 700 701 private void sendVerificationRequest(int userId, int verificationId, 702 IntentFilterVerificationState ivs) { 703 704 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 705 verificationIntent.putExtra( 706 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 707 verificationId); 708 verificationIntent.putExtra( 709 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 710 getDefaultScheme()); 711 verificationIntent.putExtra( 712 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 713 ivs.getHostsString()); 714 verificationIntent.putExtra( 715 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 716 ivs.getPackageName()); 717 verificationIntent.setComponent(mIntentFilterVerifierComponent); 718 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 719 720 UserHandle user = new UserHandle(userId); 721 mContext.sendBroadcastAsUser(verificationIntent, user); 722 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 723 "Sending IntentFilter verification broadcast"); 724 } 725 726 public void receiveVerificationResponse(int verificationId) { 727 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 728 729 final boolean verified = ivs.isVerified(); 730 731 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 732 final int count = filters.size(); 733 if (DEBUG_DOMAIN_VERIFICATION) { 734 Slog.i(TAG, "Received verification response " + verificationId 735 + " for " + count + " filters, verified=" + verified); 736 } 737 for (int n=0; n<count; n++) { 738 PackageParser.ActivityIntentInfo filter = filters.get(n); 739 filter.setVerified(verified); 740 741 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 742 + " verified with result:" + verified + " and hosts:" 743 + ivs.getHostsString()); 744 } 745 746 mIntentFilterVerificationStates.remove(verificationId); 747 748 final String packageName = ivs.getPackageName(); 749 IntentFilterVerificationInfo ivi = null; 750 751 synchronized (mPackages) { 752 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 753 } 754 if (ivi == null) { 755 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 756 + verificationId + " packageName:" + packageName); 757 return; 758 } 759 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 760 "Updating IntentFilterVerificationInfo for package " + packageName 761 +" verificationId:" + verificationId); 762 763 synchronized (mPackages) { 764 if (verified) { 765 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 766 } else { 767 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 768 } 769 scheduleWriteSettingsLocked(); 770 771 final int userId = ivs.getUserId(); 772 if (userId != UserHandle.USER_ALL) { 773 final int userStatus = 774 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 775 776 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 777 boolean needUpdate = false; 778 779 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 780 // already been set by the User thru the Disambiguation dialog 781 switch (userStatus) { 782 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 783 if (verified) { 784 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 785 } else { 786 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 787 } 788 needUpdate = true; 789 break; 790 791 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 792 if (verified) { 793 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 794 needUpdate = true; 795 } 796 break; 797 798 default: 799 // Nothing to do 800 } 801 802 if (needUpdate) { 803 mSettings.updateIntentFilterVerificationStatusLPw( 804 packageName, updatedStatus, userId); 805 scheduleWritePackageRestrictionsLocked(userId); 806 } 807 } 808 } 809 } 810 811 @Override 812 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 813 ActivityIntentInfo filter, String packageName) { 814 if (!hasValidDomains(filter)) { 815 return false; 816 } 817 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 818 if (ivs == null) { 819 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 820 packageName); 821 } 822 if (DEBUG_DOMAIN_VERIFICATION) { 823 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 824 } 825 ivs.addFilter(filter); 826 return true; 827 } 828 829 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 830 int userId, int verificationId, String packageName) { 831 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 832 verifierUid, userId, packageName); 833 ivs.setPendingState(); 834 synchronized (mPackages) { 835 mIntentFilterVerificationStates.append(verificationId, ivs); 836 mCurrentIntentFilterVerifications.add(verificationId); 837 } 838 return ivs; 839 } 840 } 841 842 private static boolean hasValidDomains(ActivityIntentInfo filter) { 843 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 844 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 845 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 846 } 847 848 // Set of pending broadcasts for aggregating enable/disable of components. 849 static class PendingPackageBroadcasts { 850 // for each user id, a map of <package name -> components within that package> 851 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 852 853 public PendingPackageBroadcasts() { 854 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 855 } 856 857 public ArrayList<String> get(int userId, String packageName) { 858 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 859 return packages.get(packageName); 860 } 861 862 public void put(int userId, String packageName, ArrayList<String> components) { 863 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 864 packages.put(packageName, components); 865 } 866 867 public void remove(int userId, String packageName) { 868 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 869 if (packages != null) { 870 packages.remove(packageName); 871 } 872 } 873 874 public void remove(int userId) { 875 mUidMap.remove(userId); 876 } 877 878 public int userIdCount() { 879 return mUidMap.size(); 880 } 881 882 public int userIdAt(int n) { 883 return mUidMap.keyAt(n); 884 } 885 886 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 887 return mUidMap.get(userId); 888 } 889 890 public int size() { 891 // total number of pending broadcast entries across all userIds 892 int num = 0; 893 for (int i = 0; i< mUidMap.size(); i++) { 894 num += mUidMap.valueAt(i).size(); 895 } 896 return num; 897 } 898 899 public void clear() { 900 mUidMap.clear(); 901 } 902 903 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 904 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 905 if (map == null) { 906 map = new ArrayMap<String, ArrayList<String>>(); 907 mUidMap.put(userId, map); 908 } 909 return map; 910 } 911 } 912 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 913 914 // Service Connection to remote media container service to copy 915 // package uri's from external media onto secure containers 916 // or internal storage. 917 private IMediaContainerService mContainerService = null; 918 919 static final int SEND_PENDING_BROADCAST = 1; 920 static final int MCS_BOUND = 3; 921 static final int END_COPY = 4; 922 static final int INIT_COPY = 5; 923 static final int MCS_UNBIND = 6; 924 static final int START_CLEANING_PACKAGE = 7; 925 static final int FIND_INSTALL_LOC = 8; 926 static final int POST_INSTALL = 9; 927 static final int MCS_RECONNECT = 10; 928 static final int MCS_GIVE_UP = 11; 929 static final int UPDATED_MEDIA_STATUS = 12; 930 static final int WRITE_SETTINGS = 13; 931 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 932 static final int PACKAGE_VERIFIED = 15; 933 static final int CHECK_PENDING_VERIFICATION = 16; 934 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 935 static final int INTENT_FILTER_VERIFIED = 18; 936 937 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 938 939 // Delay time in millisecs 940 static final int BROADCAST_DELAY = 10 * 1000; 941 942 static UserManagerService sUserManager; 943 944 // Stores a list of users whose package restrictions file needs to be updated 945 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 946 947 final private DefaultContainerConnection mDefContainerConn = 948 new DefaultContainerConnection(); 949 class DefaultContainerConnection implements ServiceConnection { 950 public void onServiceConnected(ComponentName name, IBinder service) { 951 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 952 IMediaContainerService imcs = 953 IMediaContainerService.Stub.asInterface(service); 954 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 955 } 956 957 public void onServiceDisconnected(ComponentName name) { 958 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 959 } 960 } 961 962 // Recordkeeping of restore-after-install operations that are currently in flight 963 // between the Package Manager and the Backup Manager 964 static class PostInstallData { 965 public InstallArgs args; 966 public PackageInstalledInfo res; 967 968 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 969 args = _a; 970 res = _r; 971 } 972 } 973 974 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 975 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 976 977 // XML tags for backup/restore of various bits of state 978 private static final String TAG_PREFERRED_BACKUP = "pa"; 979 private static final String TAG_DEFAULT_APPS = "da"; 980 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 981 982 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 983 private static final String TAG_ALL_GRANTS = "rt-grants"; 984 private static final String TAG_GRANT = "grant"; 985 private static final String ATTR_PACKAGE_NAME = "pkg"; 986 987 private static final String TAG_PERMISSION = "perm"; 988 private static final String ATTR_PERMISSION_NAME = "name"; 989 private static final String ATTR_IS_GRANTED = "g"; 990 private static final String ATTR_USER_SET = "set"; 991 private static final String ATTR_USER_FIXED = "fixed"; 992 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 993 994 // System/policy permission grants are not backed up 995 private static final int SYSTEM_RUNTIME_GRANT_MASK = 996 FLAG_PERMISSION_POLICY_FIXED 997 | FLAG_PERMISSION_SYSTEM_FIXED 998 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 999 1000 // And we back up these user-adjusted states 1001 private static final int USER_RUNTIME_GRANT_MASK = 1002 FLAG_PERMISSION_USER_SET 1003 | FLAG_PERMISSION_USER_FIXED 1004 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1005 1006 final @Nullable String mRequiredVerifierPackage; 1007 final @Nullable String mRequiredInstallerPackage; 1008 1009 private final PackageUsage mPackageUsage = new PackageUsage(); 1010 1011 private class PackageUsage { 1012 private static final int WRITE_INTERVAL 1013 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1014 1015 private final Object mFileLock = new Object(); 1016 private final AtomicLong mLastWritten = new AtomicLong(0); 1017 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1018 1019 private boolean mIsHistoricalPackageUsageAvailable = true; 1020 1021 boolean isHistoricalPackageUsageAvailable() { 1022 return mIsHistoricalPackageUsageAvailable; 1023 } 1024 1025 void write(boolean force) { 1026 if (force) { 1027 writeInternal(); 1028 return; 1029 } 1030 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1031 && !DEBUG_DEXOPT) { 1032 return; 1033 } 1034 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1035 new Thread("PackageUsage_DiskWriter") { 1036 @Override 1037 public void run() { 1038 try { 1039 writeInternal(); 1040 } finally { 1041 mBackgroundWriteRunning.set(false); 1042 } 1043 } 1044 }.start(); 1045 } 1046 } 1047 1048 private void writeInternal() { 1049 synchronized (mPackages) { 1050 synchronized (mFileLock) { 1051 AtomicFile file = getFile(); 1052 FileOutputStream f = null; 1053 try { 1054 f = file.startWrite(); 1055 BufferedOutputStream out = new BufferedOutputStream(f); 1056 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1057 StringBuilder sb = new StringBuilder(); 1058 for (PackageParser.Package pkg : mPackages.values()) { 1059 if (pkg.mLastPackageUsageTimeInMills == 0) { 1060 continue; 1061 } 1062 sb.setLength(0); 1063 sb.append(pkg.packageName); 1064 sb.append(' '); 1065 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1066 sb.append('\n'); 1067 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1068 } 1069 out.flush(); 1070 file.finishWrite(f); 1071 } catch (IOException e) { 1072 if (f != null) { 1073 file.failWrite(f); 1074 } 1075 Log.e(TAG, "Failed to write package usage times", e); 1076 } 1077 } 1078 } 1079 mLastWritten.set(SystemClock.elapsedRealtime()); 1080 } 1081 1082 void readLP() { 1083 synchronized (mFileLock) { 1084 AtomicFile file = getFile(); 1085 BufferedInputStream in = null; 1086 try { 1087 in = new BufferedInputStream(file.openRead()); 1088 StringBuffer sb = new StringBuffer(); 1089 while (true) { 1090 String packageName = readToken(in, sb, ' '); 1091 if (packageName == null) { 1092 break; 1093 } 1094 String timeInMillisString = readToken(in, sb, '\n'); 1095 if (timeInMillisString == null) { 1096 throw new IOException("Failed to find last usage time for package " 1097 + packageName); 1098 } 1099 PackageParser.Package pkg = mPackages.get(packageName); 1100 if (pkg == null) { 1101 continue; 1102 } 1103 long timeInMillis; 1104 try { 1105 timeInMillis = Long.parseLong(timeInMillisString); 1106 } catch (NumberFormatException e) { 1107 throw new IOException("Failed to parse " + timeInMillisString 1108 + " as a long.", e); 1109 } 1110 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1111 } 1112 } catch (FileNotFoundException expected) { 1113 mIsHistoricalPackageUsageAvailable = false; 1114 } catch (IOException e) { 1115 Log.w(TAG, "Failed to read package usage times", e); 1116 } finally { 1117 IoUtils.closeQuietly(in); 1118 } 1119 } 1120 mLastWritten.set(SystemClock.elapsedRealtime()); 1121 } 1122 1123 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1124 throws IOException { 1125 sb.setLength(0); 1126 while (true) { 1127 int ch = in.read(); 1128 if (ch == -1) { 1129 if (sb.length() == 0) { 1130 return null; 1131 } 1132 throw new IOException("Unexpected EOF"); 1133 } 1134 if (ch == endOfToken) { 1135 return sb.toString(); 1136 } 1137 sb.append((char)ch); 1138 } 1139 } 1140 1141 private AtomicFile getFile() { 1142 File dataDir = Environment.getDataDirectory(); 1143 File systemDir = new File(dataDir, "system"); 1144 File fname = new File(systemDir, "package-usage.list"); 1145 return new AtomicFile(fname); 1146 } 1147 } 1148 1149 class PackageHandler extends Handler { 1150 private boolean mBound = false; 1151 final ArrayList<HandlerParams> mPendingInstalls = 1152 new ArrayList<HandlerParams>(); 1153 1154 private boolean connectToService() { 1155 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1156 " DefaultContainerService"); 1157 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1158 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1159 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1160 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1161 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1162 mBound = true; 1163 return true; 1164 } 1165 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1166 return false; 1167 } 1168 1169 private void disconnectService() { 1170 mContainerService = null; 1171 mBound = false; 1172 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1173 mContext.unbindService(mDefContainerConn); 1174 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1175 } 1176 1177 PackageHandler(Looper looper) { 1178 super(looper); 1179 } 1180 1181 public void handleMessage(Message msg) { 1182 try { 1183 doHandleMessage(msg); 1184 } finally { 1185 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1186 } 1187 } 1188 1189 void doHandleMessage(Message msg) { 1190 switch (msg.what) { 1191 case INIT_COPY: { 1192 HandlerParams params = (HandlerParams) msg.obj; 1193 int idx = mPendingInstalls.size(); 1194 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1195 // If a bind was already initiated we dont really 1196 // need to do anything. The pending install 1197 // will be processed later on. 1198 if (!mBound) { 1199 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1200 System.identityHashCode(mHandler)); 1201 // If this is the only one pending we might 1202 // have to bind to the service again. 1203 if (!connectToService()) { 1204 Slog.e(TAG, "Failed to bind to media container service"); 1205 params.serviceError(); 1206 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1207 System.identityHashCode(mHandler)); 1208 if (params.traceMethod != null) { 1209 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1210 params.traceCookie); 1211 } 1212 return; 1213 } else { 1214 // Once we bind to the service, the first 1215 // pending request will be processed. 1216 mPendingInstalls.add(idx, params); 1217 } 1218 } else { 1219 mPendingInstalls.add(idx, params); 1220 // Already bound to the service. Just make 1221 // sure we trigger off processing the first request. 1222 if (idx == 0) { 1223 mHandler.sendEmptyMessage(MCS_BOUND); 1224 } 1225 } 1226 break; 1227 } 1228 case MCS_BOUND: { 1229 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1230 if (msg.obj != null) { 1231 mContainerService = (IMediaContainerService) msg.obj; 1232 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1233 System.identityHashCode(mHandler)); 1234 } 1235 if (mContainerService == null) { 1236 if (!mBound) { 1237 // Something seriously wrong since we are not bound and we are not 1238 // waiting for connection. Bail out. 1239 Slog.e(TAG, "Cannot bind to media container service"); 1240 for (HandlerParams params : mPendingInstalls) { 1241 // Indicate service bind error 1242 params.serviceError(); 1243 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1244 System.identityHashCode(params)); 1245 if (params.traceMethod != null) { 1246 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1247 params.traceMethod, params.traceCookie); 1248 } 1249 return; 1250 } 1251 mPendingInstalls.clear(); 1252 } else { 1253 Slog.w(TAG, "Waiting to connect to media container service"); 1254 } 1255 } else if (mPendingInstalls.size() > 0) { 1256 HandlerParams params = mPendingInstalls.get(0); 1257 if (params != null) { 1258 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1259 System.identityHashCode(params)); 1260 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1261 if (params.startCopy()) { 1262 // We are done... look for more work or to 1263 // go idle. 1264 if (DEBUG_SD_INSTALL) Log.i(TAG, 1265 "Checking for more work or unbind..."); 1266 // Delete pending install 1267 if (mPendingInstalls.size() > 0) { 1268 mPendingInstalls.remove(0); 1269 } 1270 if (mPendingInstalls.size() == 0) { 1271 if (mBound) { 1272 if (DEBUG_SD_INSTALL) Log.i(TAG, 1273 "Posting delayed MCS_UNBIND"); 1274 removeMessages(MCS_UNBIND); 1275 Message ubmsg = obtainMessage(MCS_UNBIND); 1276 // Unbind after a little delay, to avoid 1277 // continual thrashing. 1278 sendMessageDelayed(ubmsg, 10000); 1279 } 1280 } else { 1281 // There are more pending requests in queue. 1282 // Just post MCS_BOUND message to trigger processing 1283 // of next pending install. 1284 if (DEBUG_SD_INSTALL) Log.i(TAG, 1285 "Posting MCS_BOUND for next work"); 1286 mHandler.sendEmptyMessage(MCS_BOUND); 1287 } 1288 } 1289 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1290 } 1291 } else { 1292 // Should never happen ideally. 1293 Slog.w(TAG, "Empty queue"); 1294 } 1295 break; 1296 } 1297 case MCS_RECONNECT: { 1298 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1299 if (mPendingInstalls.size() > 0) { 1300 if (mBound) { 1301 disconnectService(); 1302 } 1303 if (!connectToService()) { 1304 Slog.e(TAG, "Failed to bind to media container service"); 1305 for (HandlerParams params : mPendingInstalls) { 1306 // Indicate service bind error 1307 params.serviceError(); 1308 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1309 System.identityHashCode(params)); 1310 } 1311 mPendingInstalls.clear(); 1312 } 1313 } 1314 break; 1315 } 1316 case MCS_UNBIND: { 1317 // If there is no actual work left, then time to unbind. 1318 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1319 1320 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1321 if (mBound) { 1322 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1323 1324 disconnectService(); 1325 } 1326 } else if (mPendingInstalls.size() > 0) { 1327 // There are more pending requests in queue. 1328 // Just post MCS_BOUND message to trigger processing 1329 // of next pending install. 1330 mHandler.sendEmptyMessage(MCS_BOUND); 1331 } 1332 1333 break; 1334 } 1335 case MCS_GIVE_UP: { 1336 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1337 HandlerParams params = mPendingInstalls.remove(0); 1338 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1339 System.identityHashCode(params)); 1340 break; 1341 } 1342 case SEND_PENDING_BROADCAST: { 1343 String packages[]; 1344 ArrayList<String> components[]; 1345 int size = 0; 1346 int uids[]; 1347 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1348 synchronized (mPackages) { 1349 if (mPendingBroadcasts == null) { 1350 return; 1351 } 1352 size = mPendingBroadcasts.size(); 1353 if (size <= 0) { 1354 // Nothing to be done. Just return 1355 return; 1356 } 1357 packages = new String[size]; 1358 components = new ArrayList[size]; 1359 uids = new int[size]; 1360 int i = 0; // filling out the above arrays 1361 1362 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1363 int packageUserId = mPendingBroadcasts.userIdAt(n); 1364 Iterator<Map.Entry<String, ArrayList<String>>> it 1365 = mPendingBroadcasts.packagesForUserId(packageUserId) 1366 .entrySet().iterator(); 1367 while (it.hasNext() && i < size) { 1368 Map.Entry<String, ArrayList<String>> ent = it.next(); 1369 packages[i] = ent.getKey(); 1370 components[i] = ent.getValue(); 1371 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1372 uids[i] = (ps != null) 1373 ? UserHandle.getUid(packageUserId, ps.appId) 1374 : -1; 1375 i++; 1376 } 1377 } 1378 size = i; 1379 mPendingBroadcasts.clear(); 1380 } 1381 // Send broadcasts 1382 for (int i = 0; i < size; i++) { 1383 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1384 } 1385 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1386 break; 1387 } 1388 case START_CLEANING_PACKAGE: { 1389 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1390 final String packageName = (String)msg.obj; 1391 final int userId = msg.arg1; 1392 final boolean andCode = msg.arg2 != 0; 1393 synchronized (mPackages) { 1394 if (userId == UserHandle.USER_ALL) { 1395 int[] users = sUserManager.getUserIds(); 1396 for (int user : users) { 1397 mSettings.addPackageToCleanLPw( 1398 new PackageCleanItem(user, packageName, andCode)); 1399 } 1400 } else { 1401 mSettings.addPackageToCleanLPw( 1402 new PackageCleanItem(userId, packageName, andCode)); 1403 } 1404 } 1405 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1406 startCleaningPackages(); 1407 } break; 1408 case POST_INSTALL: { 1409 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1410 1411 PostInstallData data = mRunningInstalls.get(msg.arg1); 1412 mRunningInstalls.delete(msg.arg1); 1413 boolean deleteOld = false; 1414 1415 if (data != null) { 1416 InstallArgs args = data.args; 1417 PackageInstalledInfo res = data.res; 1418 1419 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1420 final String packageName = res.pkg.applicationInfo.packageName; 1421 res.removedInfo.sendBroadcast(false, true, false); 1422 Bundle extras = new Bundle(1); 1423 extras.putInt(Intent.EXTRA_UID, res.uid); 1424 1425 // Now that we successfully installed the package, grant runtime 1426 // permissions if requested before broadcasting the install. 1427 if ((args.installFlags 1428 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 1429 && res.pkg.applicationInfo.targetSdkVersion 1430 >= Build.VERSION_CODES.M) { 1431 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1432 args.installGrantPermissions); 1433 } 1434 1435 synchronized (mPackages) { 1436 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1437 } 1438 1439 // Determine the set of users who are adding this 1440 // package for the first time vs. those who are seeing 1441 // an update. 1442 int[] firstUsers; 1443 int[] updateUsers = new int[0]; 1444 if (res.origUsers == null || res.origUsers.length == 0) { 1445 firstUsers = res.newUsers; 1446 } else { 1447 firstUsers = new int[0]; 1448 for (int i=0; i<res.newUsers.length; i++) { 1449 int user = res.newUsers[i]; 1450 boolean isNew = true; 1451 for (int j=0; j<res.origUsers.length; j++) { 1452 if (res.origUsers[j] == user) { 1453 isNew = false; 1454 break; 1455 } 1456 } 1457 if (isNew) { 1458 int[] newFirst = new int[firstUsers.length+1]; 1459 System.arraycopy(firstUsers, 0, newFirst, 0, 1460 firstUsers.length); 1461 newFirst[firstUsers.length] = user; 1462 firstUsers = newFirst; 1463 } else { 1464 int[] newUpdate = new int[updateUsers.length+1]; 1465 System.arraycopy(updateUsers, 0, newUpdate, 0, 1466 updateUsers.length); 1467 newUpdate[updateUsers.length] = user; 1468 updateUsers = newUpdate; 1469 } 1470 } 1471 } 1472 // don't broadcast for ephemeral installs/updates 1473 final boolean isEphemeral = isEphemeral(res.pkg); 1474 if (!isEphemeral) { 1475 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1476 extras, 0 /*flags*/, null /*targetPackage*/, 1477 null /*finishedReceiver*/, firstUsers); 1478 } 1479 final boolean update = res.removedInfo.removedPackage != null; 1480 if (update) { 1481 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1482 } 1483 if (!isEphemeral) { 1484 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1485 extras, 0 /*flags*/, null /*targetPackage*/, 1486 null /*finishedReceiver*/, updateUsers); 1487 } 1488 if (update) { 1489 if (!isEphemeral) { 1490 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1491 packageName, extras, 0 /*flags*/, 1492 null /*targetPackage*/, null /*finishedReceiver*/, 1493 updateUsers); 1494 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1495 null /*package*/, null /*extras*/, 0 /*flags*/, 1496 packageName /*targetPackage*/, 1497 null /*finishedReceiver*/, updateUsers); 1498 } 1499 1500 // treat asec-hosted packages like removable media on upgrade 1501 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1502 if (DEBUG_INSTALL) { 1503 Slog.i(TAG, "upgrading pkg " + res.pkg 1504 + " is ASEC-hosted -> AVAILABLE"); 1505 } 1506 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1507 ArrayList<String> pkgList = new ArrayList<String>(1); 1508 pkgList.add(packageName); 1509 sendResourcesChangedBroadcast(true, true, 1510 pkgList,uidArray, null); 1511 } 1512 } 1513 if (res.removedInfo.args != null) { 1514 // Remove the replaced package's older resources safely now 1515 deleteOld = true; 1516 } 1517 1518 1519 // Work that needs to happen on first install within each user 1520 if (firstUsers.length > 0) { 1521 for (int userId : firstUsers) { 1522 synchronized (mPackages) { 1523 // If this app is a browser and it's newly-installed for 1524 // some users, clear any default-browser state in those 1525 // users. The app's nature doesn't depend on the user, 1526 // so we can just check its browser nature in any user 1527 // and generalize. 1528 if (packageIsBrowser(packageName, firstUsers[0])) { 1529 mSettings.setDefaultBrowserPackageNameLPw( 1530 null, userId); 1531 } 1532 1533 // We may also need to apply pending (restored) runtime 1534 // permission grants within these users. 1535 mSettings.applyPendingPermissionGrantsLPw( 1536 packageName, userId); 1537 } 1538 } 1539 } 1540 // Log current value of "unknown sources" setting 1541 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1542 getUnknownSourcesSettings()); 1543 } 1544 // Force a gc to clear up things 1545 Runtime.getRuntime().gc(); 1546 // We delete after a gc for applications on sdcard. 1547 if (deleteOld) { 1548 synchronized (mInstallLock) { 1549 res.removedInfo.args.doPostDeleteLI(true); 1550 } 1551 } 1552 if (args.observer != null) { 1553 try { 1554 Bundle extras = extrasForInstallResult(res); 1555 args.observer.onPackageInstalled(res.name, res.returnCode, 1556 res.returnMsg, extras); 1557 } catch (RemoteException e) { 1558 Slog.i(TAG, "Observer no longer exists."); 1559 } 1560 } 1561 if (args.traceMethod != null) { 1562 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1563 args.traceCookie); 1564 } 1565 return; 1566 } else { 1567 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1568 } 1569 1570 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1571 } break; 1572 case UPDATED_MEDIA_STATUS: { 1573 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1574 boolean reportStatus = msg.arg1 == 1; 1575 boolean doGc = msg.arg2 == 1; 1576 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1577 if (doGc) { 1578 // Force a gc to clear up stale containers. 1579 Runtime.getRuntime().gc(); 1580 } 1581 if (msg.obj != null) { 1582 @SuppressWarnings("unchecked") 1583 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1584 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1585 // Unload containers 1586 unloadAllContainers(args); 1587 } 1588 if (reportStatus) { 1589 try { 1590 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1591 PackageHelper.getMountService().finishMediaUpdate(); 1592 } catch (RemoteException e) { 1593 Log.e(TAG, "MountService not running?"); 1594 } 1595 } 1596 } break; 1597 case WRITE_SETTINGS: { 1598 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1599 synchronized (mPackages) { 1600 removeMessages(WRITE_SETTINGS); 1601 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1602 mSettings.writeLPr(); 1603 mDirtyUsers.clear(); 1604 } 1605 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1606 } break; 1607 case WRITE_PACKAGE_RESTRICTIONS: { 1608 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1609 synchronized (mPackages) { 1610 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1611 for (int userId : mDirtyUsers) { 1612 mSettings.writePackageRestrictionsLPr(userId); 1613 } 1614 mDirtyUsers.clear(); 1615 } 1616 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1617 } break; 1618 case CHECK_PENDING_VERIFICATION: { 1619 final int verificationId = msg.arg1; 1620 final PackageVerificationState state = mPendingVerification.get(verificationId); 1621 1622 if ((state != null) && !state.timeoutExtended()) { 1623 final InstallArgs args = state.getInstallArgs(); 1624 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1625 1626 Slog.i(TAG, "Verification timed out for " + originUri); 1627 mPendingVerification.remove(verificationId); 1628 1629 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1630 1631 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1632 Slog.i(TAG, "Continuing with installation of " + originUri); 1633 state.setVerifierResponse(Binder.getCallingUid(), 1634 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1635 broadcastPackageVerified(verificationId, originUri, 1636 PackageManager.VERIFICATION_ALLOW, 1637 state.getInstallArgs().getUser()); 1638 try { 1639 ret = args.copyApk(mContainerService, true); 1640 } catch (RemoteException e) { 1641 Slog.e(TAG, "Could not contact the ContainerService"); 1642 } 1643 } else { 1644 broadcastPackageVerified(verificationId, originUri, 1645 PackageManager.VERIFICATION_REJECT, 1646 state.getInstallArgs().getUser()); 1647 } 1648 1649 Trace.asyncTraceEnd( 1650 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1651 1652 processPendingInstall(args, ret); 1653 mHandler.sendEmptyMessage(MCS_UNBIND); 1654 } 1655 break; 1656 } 1657 case PACKAGE_VERIFIED: { 1658 final int verificationId = msg.arg1; 1659 1660 final PackageVerificationState state = mPendingVerification.get(verificationId); 1661 if (state == null) { 1662 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1663 break; 1664 } 1665 1666 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1667 1668 state.setVerifierResponse(response.callerUid, response.code); 1669 1670 if (state.isVerificationComplete()) { 1671 mPendingVerification.remove(verificationId); 1672 1673 final InstallArgs args = state.getInstallArgs(); 1674 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1675 1676 int ret; 1677 if (state.isInstallAllowed()) { 1678 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1679 broadcastPackageVerified(verificationId, originUri, 1680 response.code, state.getInstallArgs().getUser()); 1681 try { 1682 ret = args.copyApk(mContainerService, true); 1683 } catch (RemoteException e) { 1684 Slog.e(TAG, "Could not contact the ContainerService"); 1685 } 1686 } else { 1687 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1688 } 1689 1690 Trace.asyncTraceEnd( 1691 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1692 1693 processPendingInstall(args, ret); 1694 mHandler.sendEmptyMessage(MCS_UNBIND); 1695 } 1696 1697 break; 1698 } 1699 case START_INTENT_FILTER_VERIFICATIONS: { 1700 IFVerificationParams params = (IFVerificationParams) msg.obj; 1701 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1702 params.replacing, params.pkg); 1703 break; 1704 } 1705 case INTENT_FILTER_VERIFIED: { 1706 final int verificationId = msg.arg1; 1707 1708 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1709 verificationId); 1710 if (state == null) { 1711 Slog.w(TAG, "Invalid IntentFilter verification token " 1712 + verificationId + " received"); 1713 break; 1714 } 1715 1716 final int userId = state.getUserId(); 1717 1718 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1719 "Processing IntentFilter verification with token:" 1720 + verificationId + " and userId:" + userId); 1721 1722 final IntentFilterVerificationResponse response = 1723 (IntentFilterVerificationResponse) msg.obj; 1724 1725 state.setVerifierResponse(response.callerUid, response.code); 1726 1727 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1728 "IntentFilter verification with token:" + verificationId 1729 + " and userId:" + userId 1730 + " is settings verifier response with response code:" 1731 + response.code); 1732 1733 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1734 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1735 + response.getFailedDomainsString()); 1736 } 1737 1738 if (state.isVerificationComplete()) { 1739 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1740 } else { 1741 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1742 "IntentFilter verification with token:" + verificationId 1743 + " was not said to be complete"); 1744 } 1745 1746 break; 1747 } 1748 } 1749 } 1750 } 1751 1752 private StorageEventListener mStorageListener = new StorageEventListener() { 1753 @Override 1754 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1755 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1756 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1757 final String volumeUuid = vol.getFsUuid(); 1758 1759 // Clean up any users or apps that were removed or recreated 1760 // while this volume was missing 1761 reconcileUsers(volumeUuid); 1762 reconcileApps(volumeUuid); 1763 1764 // Clean up any install sessions that expired or were 1765 // cancelled while this volume was missing 1766 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1767 1768 loadPrivatePackages(vol); 1769 1770 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1771 unloadPrivatePackages(vol); 1772 } 1773 } 1774 1775 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1776 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1777 updateExternalMediaStatus(true, false); 1778 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1779 updateExternalMediaStatus(false, false); 1780 } 1781 } 1782 } 1783 1784 @Override 1785 public void onVolumeForgotten(String fsUuid) { 1786 if (TextUtils.isEmpty(fsUuid)) { 1787 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1788 return; 1789 } 1790 1791 // Remove any apps installed on the forgotten volume 1792 synchronized (mPackages) { 1793 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1794 for (PackageSetting ps : packages) { 1795 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1796 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1797 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1798 } 1799 1800 mSettings.onVolumeForgotten(fsUuid); 1801 mSettings.writeLPr(); 1802 } 1803 } 1804 }; 1805 1806 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1807 String[] grantedPermissions) { 1808 if (userId >= UserHandle.USER_SYSTEM) { 1809 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1810 } else if (userId == UserHandle.USER_ALL) { 1811 final int[] userIds; 1812 synchronized (mPackages) { 1813 userIds = UserManagerService.getInstance().getUserIds(); 1814 } 1815 for (int someUserId : userIds) { 1816 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1817 } 1818 } 1819 1820 // We could have touched GID membership, so flush out packages.list 1821 synchronized (mPackages) { 1822 mSettings.writePackageListLPr(); 1823 } 1824 } 1825 1826 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1827 String[] grantedPermissions) { 1828 SettingBase sb = (SettingBase) pkg.mExtras; 1829 if (sb == null) { 1830 return; 1831 } 1832 1833 PermissionsState permissionsState = sb.getPermissionsState(); 1834 1835 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1836 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1837 1838 synchronized (mPackages) { 1839 for (String permission : pkg.requestedPermissions) { 1840 BasePermission bp = mSettings.mPermissions.get(permission); 1841 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1842 && (grantedPermissions == null 1843 || ArrayUtils.contains(grantedPermissions, permission))) { 1844 final int flags = permissionsState.getPermissionFlags(permission, userId); 1845 // Installer cannot change immutable permissions. 1846 if ((flags & immutableFlags) == 0) { 1847 grantRuntimePermission(pkg.packageName, permission, userId); 1848 } 1849 } 1850 } 1851 } 1852 } 1853 1854 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1855 Bundle extras = null; 1856 switch (res.returnCode) { 1857 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1858 extras = new Bundle(); 1859 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1860 res.origPermission); 1861 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1862 res.origPackage); 1863 break; 1864 } 1865 case PackageManager.INSTALL_SUCCEEDED: { 1866 extras = new Bundle(); 1867 extras.putBoolean(Intent.EXTRA_REPLACING, 1868 res.removedInfo != null && res.removedInfo.removedPackage != null); 1869 break; 1870 } 1871 } 1872 return extras; 1873 } 1874 1875 void scheduleWriteSettingsLocked() { 1876 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1877 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1878 } 1879 } 1880 1881 void scheduleWritePackageRestrictionsLocked(int userId) { 1882 if (!sUserManager.exists(userId)) return; 1883 mDirtyUsers.add(userId); 1884 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1885 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1886 } 1887 } 1888 1889 public static PackageManagerService main(Context context, Installer installer, 1890 boolean factoryTest, boolean onlyCore) { 1891 PackageManagerService m = new PackageManagerService(context, installer, 1892 factoryTest, onlyCore); 1893 m.enableSystemUserPackages(); 1894 ServiceManager.addService("package", m); 1895 return m; 1896 } 1897 1898 private void enableSystemUserPackages() { 1899 if (!UserManager.isSplitSystemUser()) { 1900 return; 1901 } 1902 // For system user, enable apps based on the following conditions: 1903 // - app is whitelisted or belong to one of these groups: 1904 // -- system app which has no launcher icons 1905 // -- system app which has INTERACT_ACROSS_USERS permission 1906 // -- system IME app 1907 // - app is not in the blacklist 1908 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 1909 Set<String> enableApps = new ArraySet<>(); 1910 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 1911 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 1912 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 1913 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 1914 enableApps.addAll(wlApps); 1915 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 1916 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 1917 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 1918 enableApps.removeAll(blApps); 1919 Log.i(TAG, "Applications installed for system user: " + enableApps); 1920 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 1921 UserHandle.SYSTEM); 1922 final int allAppsSize = allAps.size(); 1923 synchronized (mPackages) { 1924 for (int i = 0; i < allAppsSize; i++) { 1925 String pName = allAps.get(i); 1926 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 1927 // Should not happen, but we shouldn't be failing if it does 1928 if (pkgSetting == null) { 1929 continue; 1930 } 1931 boolean install = enableApps.contains(pName); 1932 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 1933 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 1934 + " for system user"); 1935 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 1936 } 1937 } 1938 } 1939 } 1940 1941 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1942 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1943 Context.DISPLAY_SERVICE); 1944 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1945 } 1946 1947 public PackageManagerService(Context context, Installer installer, 1948 boolean factoryTest, boolean onlyCore) { 1949 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1950 SystemClock.uptimeMillis()); 1951 1952 if (mSdkVersion <= 0) { 1953 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1954 } 1955 1956 mContext = context; 1957 mFactoryTest = factoryTest; 1958 mOnlyCore = onlyCore; 1959 mMetrics = new DisplayMetrics(); 1960 mSettings = new Settings(mPackages); 1961 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1962 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1963 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1964 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1965 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1966 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1967 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1968 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1969 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1970 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1971 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1972 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1973 1974 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1975 if (separateProcesses != null && separateProcesses.length() > 0) { 1976 if ("*".equals(separateProcesses)) { 1977 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1978 mSeparateProcesses = null; 1979 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1980 } else { 1981 mDefParseFlags = 0; 1982 mSeparateProcesses = separateProcesses.split(","); 1983 Slog.w(TAG, "Running with debug.separate_processes: " 1984 + separateProcesses); 1985 } 1986 } else { 1987 mDefParseFlags = 0; 1988 mSeparateProcesses = null; 1989 } 1990 1991 mInstaller = installer; 1992 mPackageDexOptimizer = new PackageDexOptimizer(this); 1993 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1994 1995 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1996 FgThread.get().getLooper()); 1997 1998 getDefaultDisplayMetrics(context, mMetrics); 1999 2000 SystemConfig systemConfig = SystemConfig.getInstance(); 2001 mGlobalGids = systemConfig.getGlobalGids(); 2002 mSystemPermissions = systemConfig.getSystemPermissions(); 2003 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2004 2005 synchronized (mInstallLock) { 2006 // writer 2007 synchronized (mPackages) { 2008 mHandlerThread = new ServiceThread(TAG, 2009 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2010 mHandlerThread.start(); 2011 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2012 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2013 2014 File dataDir = Environment.getDataDirectory(); 2015 mAppInstallDir = new File(dataDir, "app"); 2016 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2017 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2018 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2019 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2020 2021 sUserManager = new UserManagerService(context, this, mPackages); 2022 2023 // Propagate permission configuration in to package manager. 2024 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2025 = systemConfig.getPermissions(); 2026 for (int i=0; i<permConfig.size(); i++) { 2027 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2028 BasePermission bp = mSettings.mPermissions.get(perm.name); 2029 if (bp == null) { 2030 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2031 mSettings.mPermissions.put(perm.name, bp); 2032 } 2033 if (perm.gids != null) { 2034 bp.setGids(perm.gids, perm.perUser); 2035 } 2036 } 2037 2038 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2039 for (int i=0; i<libConfig.size(); i++) { 2040 mSharedLibraries.put(libConfig.keyAt(i), 2041 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2042 } 2043 2044 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2045 2046 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2047 2048 String customResolverActivity = Resources.getSystem().getString( 2049 R.string.config_customResolverActivity); 2050 if (TextUtils.isEmpty(customResolverActivity)) { 2051 customResolverActivity = null; 2052 } else { 2053 mCustomResolverComponentName = ComponentName.unflattenFromString( 2054 customResolverActivity); 2055 } 2056 2057 long startTime = SystemClock.uptimeMillis(); 2058 2059 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2060 startTime); 2061 2062 // Set flag to monitor and not change apk file paths when 2063 // scanning install directories. 2064 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2065 2066 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2067 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2068 2069 if (bootClassPath == null) { 2070 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2071 } 2072 2073 if (systemServerClassPath == null) { 2074 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2075 } 2076 2077 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2078 final String[] dexCodeInstructionSets = 2079 getDexCodeInstructionSets( 2080 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2081 2082 /** 2083 * Ensure all external libraries have had dexopt run on them. 2084 */ 2085 if (mSharedLibraries.size() > 0) { 2086 // NOTE: For now, we're compiling these system "shared libraries" 2087 // (and framework jars) into all available architectures. It's possible 2088 // to compile them only when we come across an app that uses them (there's 2089 // already logic for that in scanPackageLI) but that adds some complexity. 2090 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2091 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2092 final String lib = libEntry.path; 2093 if (lib == null) { 2094 continue; 2095 } 2096 2097 try { 2098 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 2099 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2100 // Shared libraries do not have profiles so we perform a full 2101 // AOT compilation. 2102 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2103 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2104 StorageManager.UUID_PRIVATE_INTERNAL, 2105 false /*useProfiles*/); 2106 } 2107 } catch (FileNotFoundException e) { 2108 Slog.w(TAG, "Library not found: " + lib); 2109 } catch (IOException | InstallerException e) { 2110 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2111 + e.getMessage()); 2112 } 2113 } 2114 } 2115 } 2116 2117 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2118 2119 final VersionInfo ver = mSettings.getInternalVersion(); 2120 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2121 // when upgrading from pre-M, promote system app permissions from install to runtime 2122 mPromoteSystemApps = 2123 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2124 2125 // save off the names of pre-existing system packages prior to scanning; we don't 2126 // want to automatically grant runtime permissions for new system apps 2127 if (mPromoteSystemApps) { 2128 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2129 while (pkgSettingIter.hasNext()) { 2130 PackageSetting ps = pkgSettingIter.next(); 2131 if (isSystemApp(ps)) { 2132 mExistingSystemPackages.add(ps.name); 2133 } 2134 } 2135 } 2136 2137 // Collect vendor overlay packages. 2138 // (Do this before scanning any apps.) 2139 // For security and version matching reason, only consider 2140 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2141 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2142 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2143 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2144 2145 // Find base frameworks (resource packages without code). 2146 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2147 | PackageParser.PARSE_IS_SYSTEM_DIR 2148 | PackageParser.PARSE_IS_PRIVILEGED, 2149 scanFlags | SCAN_NO_DEX, 0); 2150 2151 // Collected privileged system packages. 2152 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2153 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2154 | PackageParser.PARSE_IS_SYSTEM_DIR 2155 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2156 2157 // Collect ordinary system packages. 2158 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2159 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2160 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2161 2162 // Collect all vendor packages. 2163 File vendorAppDir = new File("/vendor/app"); 2164 try { 2165 vendorAppDir = vendorAppDir.getCanonicalFile(); 2166 } catch (IOException e) { 2167 // failed to look up canonical path, continue with original one 2168 } 2169 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2170 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2171 2172 // Collect all OEM packages. 2173 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2174 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2175 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2176 2177 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2178 try { 2179 mInstaller.moveFiles(); 2180 } catch (InstallerException e) { 2181 logCriticalInfo(Log.WARN, "Update commands failed: " + e); 2182 } 2183 2184 // Prune any system packages that no longer exist. 2185 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2186 if (!mOnlyCore) { 2187 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2188 while (psit.hasNext()) { 2189 PackageSetting ps = psit.next(); 2190 2191 /* 2192 * If this is not a system app, it can't be a 2193 * disable system app. 2194 */ 2195 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2196 continue; 2197 } 2198 2199 /* 2200 * If the package is scanned, it's not erased. 2201 */ 2202 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2203 if (scannedPkg != null) { 2204 /* 2205 * If the system app is both scanned and in the 2206 * disabled packages list, then it must have been 2207 * added via OTA. Remove it from the currently 2208 * scanned package so the previously user-installed 2209 * application can be scanned. 2210 */ 2211 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2212 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2213 + ps.name + "; removing system app. Last known codePath=" 2214 + ps.codePathString + ", installStatus=" + ps.installStatus 2215 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2216 + scannedPkg.mVersionCode); 2217 removePackageLI(ps, true); 2218 mExpectingBetter.put(ps.name, ps.codePath); 2219 } 2220 2221 continue; 2222 } 2223 2224 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2225 psit.remove(); 2226 logCriticalInfo(Log.WARN, "System package " + ps.name 2227 + " no longer exists; wiping its data"); 2228 removeDataDirsLI(null, ps.name); 2229 } else { 2230 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2231 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2232 possiblyDeletedUpdatedSystemApps.add(ps.name); 2233 } 2234 } 2235 } 2236 } 2237 2238 //look for any incomplete package installations 2239 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2240 //clean up list 2241 for(int i = 0; i < deletePkgsList.size(); i++) { 2242 //clean up here 2243 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2244 } 2245 //delete tmp files 2246 deleteTempPackageFiles(); 2247 2248 // Remove any shared userIDs that have no associated packages 2249 mSettings.pruneSharedUsersLPw(); 2250 2251 if (!mOnlyCore) { 2252 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2253 SystemClock.uptimeMillis()); 2254 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2255 2256 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2257 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2258 2259 scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL, 2260 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2261 2262 /** 2263 * Remove disable package settings for any updated system 2264 * apps that were removed via an OTA. If they're not a 2265 * previously-updated app, remove them completely. 2266 * Otherwise, just revoke their system-level permissions. 2267 */ 2268 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2269 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2270 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2271 2272 String msg; 2273 if (deletedPkg == null) { 2274 msg = "Updated system package " + deletedAppName 2275 + " no longer exists; wiping its data"; 2276 removeDataDirsLI(null, deletedAppName); 2277 } else { 2278 msg = "Updated system app + " + deletedAppName 2279 + " no longer present; removing system privileges for " 2280 + deletedAppName; 2281 2282 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2283 2284 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2285 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2286 } 2287 logCriticalInfo(Log.WARN, msg); 2288 } 2289 2290 /** 2291 * Make sure all system apps that we expected to appear on 2292 * the userdata partition actually showed up. If they never 2293 * appeared, crawl back and revive the system version. 2294 */ 2295 for (int i = 0; i < mExpectingBetter.size(); i++) { 2296 final String packageName = mExpectingBetter.keyAt(i); 2297 if (!mPackages.containsKey(packageName)) { 2298 final File scanFile = mExpectingBetter.valueAt(i); 2299 2300 logCriticalInfo(Log.WARN, "Expected better " + packageName 2301 + " but never showed up; reverting to system"); 2302 2303 final int reparseFlags; 2304 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2305 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2306 | PackageParser.PARSE_IS_SYSTEM_DIR 2307 | PackageParser.PARSE_IS_PRIVILEGED; 2308 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2309 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2310 | PackageParser.PARSE_IS_SYSTEM_DIR; 2311 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2312 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2313 | PackageParser.PARSE_IS_SYSTEM_DIR; 2314 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2315 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2316 | PackageParser.PARSE_IS_SYSTEM_DIR; 2317 } else { 2318 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2319 continue; 2320 } 2321 2322 mSettings.enableSystemPackageLPw(packageName); 2323 2324 try { 2325 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2326 } catch (PackageManagerException e) { 2327 Slog.e(TAG, "Failed to parse original system package: " 2328 + e.getMessage()); 2329 } 2330 } 2331 } 2332 } 2333 mExpectingBetter.clear(); 2334 2335 // Now that we know all of the shared libraries, update all clients to have 2336 // the correct library paths. 2337 updateAllSharedLibrariesLPw(); 2338 2339 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2340 // NOTE: We ignore potential failures here during a system scan (like 2341 // the rest of the commands above) because there's precious little we 2342 // can do about it. A settings error is reported, though. 2343 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2344 false /* boot complete */); 2345 } 2346 2347 // Now that we know all the packages we are keeping, 2348 // read and update their last usage times. 2349 mPackageUsage.readLP(); 2350 2351 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2352 SystemClock.uptimeMillis()); 2353 Slog.i(TAG, "Time to scan packages: " 2354 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2355 + " seconds"); 2356 2357 // If the platform SDK has changed since the last time we booted, 2358 // we need to re-grant app permission to catch any new ones that 2359 // appear. This is really a hack, and means that apps can in some 2360 // cases get permissions that the user didn't initially explicitly 2361 // allow... it would be nice to have some better way to handle 2362 // this situation. 2363 int updateFlags = UPDATE_PERMISSIONS_ALL; 2364 if (ver.sdkVersion != mSdkVersion) { 2365 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2366 + mSdkVersion + "; regranting permissions for internal storage"); 2367 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2368 } 2369 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2370 ver.sdkVersion = mSdkVersion; 2371 2372 // If this is the first boot or an update from pre-M, and it is a normal 2373 // boot, then we need to initialize the default preferred apps across 2374 // all defined users. 2375 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2376 for (UserInfo user : sUserManager.getUsers(true)) { 2377 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2378 applyFactoryDefaultBrowserLPw(user.id); 2379 primeDomainVerificationsLPw(user.id); 2380 } 2381 } 2382 2383 // Prepare storage for system user really early during boot, 2384 // since core system apps like SettingsProvider and SystemUI 2385 // can't wait for user to start 2386 final int flags; 2387 if (StorageManager.isFileBasedEncryptionEnabled()) { 2388 flags = Installer.FLAG_DE_STORAGE; 2389 } else { 2390 flags = Installer.FLAG_DE_STORAGE | Installer.FLAG_CE_STORAGE; 2391 } 2392 reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, flags); 2393 2394 // If this is first boot after an OTA, and a normal boot, then 2395 // we need to clear code cache directories. 2396 if (mIsUpgrade && !onlyCore) { 2397 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2398 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2399 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2400 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2401 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2402 } 2403 } 2404 ver.fingerprint = Build.FINGERPRINT; 2405 } 2406 2407 checkDefaultBrowser(); 2408 2409 // clear only after permissions and other defaults have been updated 2410 mExistingSystemPackages.clear(); 2411 mPromoteSystemApps = false; 2412 2413 // All the changes are done during package scanning. 2414 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2415 2416 // can downgrade to reader 2417 mSettings.writeLPr(); 2418 2419 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2420 SystemClock.uptimeMillis()); 2421 2422 if (!mOnlyCore) { 2423 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2424 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2425 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2426 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2427 mIntentFilterVerifierComponent); 2428 } else { 2429 mRequiredVerifierPackage = null; 2430 mRequiredInstallerPackage = null; 2431 mIntentFilterVerifierComponent = null; 2432 mIntentFilterVerifier = null; 2433 } 2434 2435 mInstallerService = new PackageInstallerService(context, this); 2436 2437 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2438 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2439 // both the installer and resolver must be present to enable ephemeral 2440 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2441 if (DEBUG_EPHEMERAL) { 2442 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2443 + " installer:" + ephemeralInstallerComponent); 2444 } 2445 mEphemeralResolverComponent = ephemeralResolverComponent; 2446 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2447 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2448 mEphemeralResolverConnection = 2449 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2450 } else { 2451 if (DEBUG_EPHEMERAL) { 2452 final String missingComponent = 2453 (ephemeralResolverComponent == null) 2454 ? (ephemeralInstallerComponent == null) 2455 ? "resolver and installer" 2456 : "resolver" 2457 : "installer"; 2458 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2459 } 2460 mEphemeralResolverComponent = null; 2461 mEphemeralInstallerComponent = null; 2462 mEphemeralResolverConnection = null; 2463 } 2464 2465 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2466 } // synchronized (mPackages) 2467 } // synchronized (mInstallLock) 2468 2469 // Now after opening every single application zip, make sure they 2470 // are all flushed. Not really needed, but keeps things nice and 2471 // tidy. 2472 Runtime.getRuntime().gc(); 2473 2474 // The initial scanning above does many calls into installd while 2475 // holding the mPackages lock, but we're mostly interested in yelling 2476 // once we have a booted system. 2477 mInstaller.setWarnIfHeld(mPackages); 2478 2479 // Expose private service for system components to use. 2480 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2481 } 2482 2483 @Override 2484 public boolean isFirstBoot() { 2485 return !mRestoredSettings; 2486 } 2487 2488 @Override 2489 public boolean isOnlyCoreApps() { 2490 return mOnlyCore; 2491 } 2492 2493 @Override 2494 public boolean isUpgrade() { 2495 return mIsUpgrade; 2496 } 2497 2498 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2499 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2500 2501 final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE, 2502 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2503 if (matches.size() == 1) { 2504 return matches.get(0).getComponentInfo().packageName; 2505 } else { 2506 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2507 return null; 2508 } 2509 } 2510 2511 private @NonNull String getRequiredInstallerLPr() { 2512 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2513 intent.addCategory(Intent.CATEGORY_DEFAULT); 2514 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2515 2516 final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE, 2517 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2518 if (matches.size() == 1) { 2519 return matches.get(0).getComponentInfo().packageName; 2520 } else { 2521 throw new RuntimeException("There must be exactly one installer; found " + matches); 2522 } 2523 } 2524 2525 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2526 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2527 2528 final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE, 2529 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2530 ResolveInfo best = null; 2531 final int N = matches.size(); 2532 for (int i = 0; i < N; i++) { 2533 final ResolveInfo cur = matches.get(i); 2534 final String packageName = cur.getComponentInfo().packageName; 2535 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2536 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2537 continue; 2538 } 2539 2540 if (best == null || cur.priority > best.priority) { 2541 best = cur; 2542 } 2543 } 2544 2545 if (best != null) { 2546 return best.getComponentInfo().getComponentName(); 2547 } else { 2548 throw new RuntimeException("There must be at least one intent filter verifier"); 2549 } 2550 } 2551 2552 private @Nullable ComponentName getEphemeralResolverLPr() { 2553 final String[] packageArray = 2554 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2555 if (packageArray.length == 0) { 2556 if (DEBUG_EPHEMERAL) { 2557 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2558 } 2559 return null; 2560 } 2561 2562 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2563 final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, null, 2564 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2565 2566 final int N = resolvers.size(); 2567 if (N == 0) { 2568 if (DEBUG_EPHEMERAL) { 2569 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2570 } 2571 return null; 2572 } 2573 2574 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2575 for (int i = 0; i < N; i++) { 2576 final ResolveInfo info = resolvers.get(i); 2577 2578 if (info.serviceInfo == null) { 2579 continue; 2580 } 2581 2582 final String packageName = info.serviceInfo.packageName; 2583 if (!possiblePackages.contains(packageName)) { 2584 if (DEBUG_EPHEMERAL) { 2585 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2586 + " pkg: " + packageName + ", info:" + info); 2587 } 2588 continue; 2589 } 2590 2591 if (DEBUG_EPHEMERAL) { 2592 Slog.v(TAG, "Ephemeral resolver found;" 2593 + " pkg: " + packageName + ", info:" + info); 2594 } 2595 return new ComponentName(packageName, info.serviceInfo.name); 2596 } 2597 if (DEBUG_EPHEMERAL) { 2598 Slog.v(TAG, "Ephemeral resolver NOT found"); 2599 } 2600 return null; 2601 } 2602 2603 private @Nullable ComponentName getEphemeralInstallerLPr() { 2604 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2605 intent.addCategory(Intent.CATEGORY_DEFAULT); 2606 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2607 2608 final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE, 2609 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2610 if (matches.size() == 0) { 2611 return null; 2612 } else if (matches.size() == 1) { 2613 return matches.get(0).getComponentInfo().getComponentName(); 2614 } else { 2615 throw new RuntimeException( 2616 "There must be at most one ephemeral installer; found " + matches); 2617 } 2618 } 2619 2620 private void primeDomainVerificationsLPw(int userId) { 2621 if (DEBUG_DOMAIN_VERIFICATION) { 2622 Slog.d(TAG, "Priming domain verifications in user " + userId); 2623 } 2624 2625 SystemConfig systemConfig = SystemConfig.getInstance(); 2626 ArraySet<String> packages = systemConfig.getLinkedApps(); 2627 ArraySet<String> domains = new ArraySet<String>(); 2628 2629 for (String packageName : packages) { 2630 PackageParser.Package pkg = mPackages.get(packageName); 2631 if (pkg != null) { 2632 if (!pkg.isSystemApp()) { 2633 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2634 continue; 2635 } 2636 2637 domains.clear(); 2638 for (PackageParser.Activity a : pkg.activities) { 2639 for (ActivityIntentInfo filter : a.intents) { 2640 if (hasValidDomains(filter)) { 2641 domains.addAll(filter.getHostsList()); 2642 } 2643 } 2644 } 2645 2646 if (domains.size() > 0) { 2647 if (DEBUG_DOMAIN_VERIFICATION) { 2648 Slog.v(TAG, " + " + packageName); 2649 } 2650 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2651 // state w.r.t. the formal app-linkage "no verification attempted" state; 2652 // and then 'always' in the per-user state actually used for intent resolution. 2653 final IntentFilterVerificationInfo ivi; 2654 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2655 new ArrayList<String>(domains)); 2656 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2657 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2658 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2659 } else { 2660 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2661 + "' does not handle web links"); 2662 } 2663 } else { 2664 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2665 } 2666 } 2667 2668 scheduleWritePackageRestrictionsLocked(userId); 2669 scheduleWriteSettingsLocked(); 2670 } 2671 2672 private void applyFactoryDefaultBrowserLPw(int userId) { 2673 // The default browser app's package name is stored in a string resource, 2674 // with a product-specific overlay used for vendor customization. 2675 String browserPkg = mContext.getResources().getString( 2676 com.android.internal.R.string.default_browser); 2677 if (!TextUtils.isEmpty(browserPkg)) { 2678 // non-empty string => required to be a known package 2679 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2680 if (ps == null) { 2681 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2682 browserPkg = null; 2683 } else { 2684 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2685 } 2686 } 2687 2688 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2689 // default. If there's more than one, just leave everything alone. 2690 if (browserPkg == null) { 2691 calculateDefaultBrowserLPw(userId); 2692 } 2693 } 2694 2695 private void calculateDefaultBrowserLPw(int userId) { 2696 List<String> allBrowsers = resolveAllBrowserApps(userId); 2697 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2698 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2699 } 2700 2701 private List<String> resolveAllBrowserApps(int userId) { 2702 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2703 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2704 PackageManager.MATCH_ALL, userId); 2705 2706 final int count = list.size(); 2707 List<String> result = new ArrayList<String>(count); 2708 for (int i=0; i<count; i++) { 2709 ResolveInfo info = list.get(i); 2710 if (info.activityInfo == null 2711 || !info.handleAllWebDataURI 2712 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2713 || result.contains(info.activityInfo.packageName)) { 2714 continue; 2715 } 2716 result.add(info.activityInfo.packageName); 2717 } 2718 2719 return result; 2720 } 2721 2722 private boolean packageIsBrowser(String packageName, int userId) { 2723 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2724 PackageManager.MATCH_ALL, userId); 2725 final int N = list.size(); 2726 for (int i = 0; i < N; i++) { 2727 ResolveInfo info = list.get(i); 2728 if (packageName.equals(info.activityInfo.packageName)) { 2729 return true; 2730 } 2731 } 2732 return false; 2733 } 2734 2735 private void checkDefaultBrowser() { 2736 final int myUserId = UserHandle.myUserId(); 2737 final String packageName = getDefaultBrowserPackageName(myUserId); 2738 if (packageName != null) { 2739 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2740 if (info == null) { 2741 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2742 synchronized (mPackages) { 2743 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2744 } 2745 } 2746 } 2747 } 2748 2749 @Override 2750 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2751 throws RemoteException { 2752 try { 2753 return super.onTransact(code, data, reply, flags); 2754 } catch (RuntimeException e) { 2755 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2756 Slog.wtf(TAG, "Package Manager Crash", e); 2757 } 2758 throw e; 2759 } 2760 } 2761 2762 void cleanupInstallFailedPackage(PackageSetting ps) { 2763 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2764 2765 removeDataDirsLI(ps.volumeUuid, ps.name); 2766 if (ps.codePath != null) { 2767 removeCodePathLI(ps.codePath); 2768 } 2769 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2770 if (ps.resourcePath.isDirectory()) { 2771 FileUtils.deleteContents(ps.resourcePath); 2772 } 2773 ps.resourcePath.delete(); 2774 } 2775 mSettings.removePackageLPw(ps.name); 2776 } 2777 2778 static int[] appendInts(int[] cur, int[] add) { 2779 if (add == null) return cur; 2780 if (cur == null) return add; 2781 final int N = add.length; 2782 for (int i=0; i<N; i++) { 2783 cur = appendInt(cur, add[i]); 2784 } 2785 return cur; 2786 } 2787 2788 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2789 if (!sUserManager.exists(userId)) return null; 2790 final PackageSetting ps = (PackageSetting) p.mExtras; 2791 if (ps == null) { 2792 return null; 2793 } 2794 2795 final PermissionsState permissionsState = ps.getPermissionsState(); 2796 2797 final int[] gids = permissionsState.computeGids(userId); 2798 final Set<String> permissions = permissionsState.getPermissions(userId); 2799 final PackageUserState state = ps.readUserState(userId); 2800 2801 return PackageParser.generatePackageInfo(p, gids, flags, 2802 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2803 } 2804 2805 @Override 2806 public void checkPackageStartable(String packageName, int userId) { 2807 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 2808 2809 synchronized (mPackages) { 2810 final PackageSetting ps = mSettings.mPackages.get(packageName); 2811 if (ps == null) { 2812 throw new SecurityException("Package " + packageName + " was not found!"); 2813 } 2814 2815 if (ps.frozen) { 2816 throw new SecurityException("Package " + packageName + " is currently frozen!"); 2817 } 2818 2819 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware() 2820 || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) { 2821 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 2822 } 2823 } 2824 } 2825 2826 @Override 2827 public boolean isPackageAvailable(String packageName, int userId) { 2828 if (!sUserManager.exists(userId)) return false; 2829 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2830 synchronized (mPackages) { 2831 PackageParser.Package p = mPackages.get(packageName); 2832 if (p != null) { 2833 final PackageSetting ps = (PackageSetting) p.mExtras; 2834 if (ps != null) { 2835 final PackageUserState state = ps.readUserState(userId); 2836 if (state != null) { 2837 return PackageParser.isAvailable(state); 2838 } 2839 } 2840 } 2841 } 2842 return false; 2843 } 2844 2845 @Override 2846 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2847 if (!sUserManager.exists(userId)) return null; 2848 flags = updateFlagsForPackage(flags, userId, packageName); 2849 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2850 // reader 2851 synchronized (mPackages) { 2852 PackageParser.Package p = mPackages.get(packageName); 2853 if (DEBUG_PACKAGE_INFO) 2854 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2855 if (p != null) { 2856 return generatePackageInfo(p, flags, userId); 2857 } 2858 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2859 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2860 } 2861 } 2862 return null; 2863 } 2864 2865 @Override 2866 public String[] currentToCanonicalPackageNames(String[] names) { 2867 String[] out = new String[names.length]; 2868 // reader 2869 synchronized (mPackages) { 2870 for (int i=names.length-1; i>=0; i--) { 2871 PackageSetting ps = mSettings.mPackages.get(names[i]); 2872 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2873 } 2874 } 2875 return out; 2876 } 2877 2878 @Override 2879 public String[] canonicalToCurrentPackageNames(String[] names) { 2880 String[] out = new String[names.length]; 2881 // reader 2882 synchronized (mPackages) { 2883 for (int i=names.length-1; i>=0; i--) { 2884 String cur = mSettings.mRenamedPackages.get(names[i]); 2885 out[i] = cur != null ? cur : names[i]; 2886 } 2887 } 2888 return out; 2889 } 2890 2891 @Override 2892 public int getPackageUid(String packageName, int flags, int userId) { 2893 if (!sUserManager.exists(userId)) return -1; 2894 flags = updateFlagsForPackage(flags, userId, packageName); 2895 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2896 2897 // reader 2898 synchronized (mPackages) { 2899 final PackageParser.Package p = mPackages.get(packageName); 2900 if (p != null && p.isMatch(flags)) { 2901 return UserHandle.getUid(userId, p.applicationInfo.uid); 2902 } 2903 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2904 final PackageSetting ps = mSettings.mPackages.get(packageName); 2905 if (ps != null && ps.isMatch(flags)) { 2906 return UserHandle.getUid(userId, ps.appId); 2907 } 2908 } 2909 } 2910 2911 return -1; 2912 } 2913 2914 @Override 2915 public int[] getPackageGids(String packageName, int flags, int userId) { 2916 if (!sUserManager.exists(userId)) return null; 2917 flags = updateFlagsForPackage(flags, userId, packageName); 2918 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2919 "getPackageGids"); 2920 2921 // reader 2922 synchronized (mPackages) { 2923 final PackageParser.Package p = mPackages.get(packageName); 2924 if (p != null && p.isMatch(flags)) { 2925 PackageSetting ps = (PackageSetting) p.mExtras; 2926 return ps.getPermissionsState().computeGids(userId); 2927 } 2928 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2929 final PackageSetting ps = mSettings.mPackages.get(packageName); 2930 if (ps != null && ps.isMatch(flags)) { 2931 return ps.getPermissionsState().computeGids(userId); 2932 } 2933 } 2934 } 2935 2936 return null; 2937 } 2938 2939 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 2940 if (bp.perm != null) { 2941 return PackageParser.generatePermissionInfo(bp.perm, flags); 2942 } 2943 PermissionInfo pi = new PermissionInfo(); 2944 pi.name = bp.name; 2945 pi.packageName = bp.sourcePackage; 2946 pi.nonLocalizedLabel = bp.name; 2947 pi.protectionLevel = bp.protectionLevel; 2948 return pi; 2949 } 2950 2951 @Override 2952 public PermissionInfo getPermissionInfo(String name, int flags) { 2953 // reader 2954 synchronized (mPackages) { 2955 final BasePermission p = mSettings.mPermissions.get(name); 2956 if (p != null) { 2957 return generatePermissionInfo(p, flags); 2958 } 2959 return null; 2960 } 2961 } 2962 2963 @Override 2964 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2965 // reader 2966 synchronized (mPackages) { 2967 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2968 for (BasePermission p : mSettings.mPermissions.values()) { 2969 if (group == null) { 2970 if (p.perm == null || p.perm.info.group == null) { 2971 out.add(generatePermissionInfo(p, flags)); 2972 } 2973 } else { 2974 if (p.perm != null && group.equals(p.perm.info.group)) { 2975 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2976 } 2977 } 2978 } 2979 2980 if (out.size() > 0) { 2981 return out; 2982 } 2983 return mPermissionGroups.containsKey(group) ? out : null; 2984 } 2985 } 2986 2987 @Override 2988 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2989 // reader 2990 synchronized (mPackages) { 2991 return PackageParser.generatePermissionGroupInfo( 2992 mPermissionGroups.get(name), flags); 2993 } 2994 } 2995 2996 @Override 2997 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2998 // reader 2999 synchronized (mPackages) { 3000 final int N = mPermissionGroups.size(); 3001 ArrayList<PermissionGroupInfo> out 3002 = new ArrayList<PermissionGroupInfo>(N); 3003 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3004 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3005 } 3006 return out; 3007 } 3008 } 3009 3010 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3011 int userId) { 3012 if (!sUserManager.exists(userId)) return null; 3013 PackageSetting ps = mSettings.mPackages.get(packageName); 3014 if (ps != null) { 3015 if (ps.pkg == null) { 3016 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 3017 flags, userId); 3018 if (pInfo != null) { 3019 return pInfo.applicationInfo; 3020 } 3021 return null; 3022 } 3023 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3024 ps.readUserState(userId), userId); 3025 } 3026 return null; 3027 } 3028 3029 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 3030 int userId) { 3031 if (!sUserManager.exists(userId)) return null; 3032 PackageSetting ps = mSettings.mPackages.get(packageName); 3033 if (ps != null) { 3034 PackageParser.Package pkg = ps.pkg; 3035 if (pkg == null) { 3036 if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) { 3037 return null; 3038 } 3039 // Only data remains, so we aren't worried about code paths 3040 pkg = new PackageParser.Package(packageName); 3041 pkg.applicationInfo.packageName = packageName; 3042 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 3043 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 3044 pkg.applicationInfo.uid = ps.appId; 3045 pkg.applicationInfo.initForUser(userId); 3046 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 3047 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 3048 } 3049 return generatePackageInfo(pkg, flags, userId); 3050 } 3051 return null; 3052 } 3053 3054 @Override 3055 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3056 if (!sUserManager.exists(userId)) return null; 3057 flags = updateFlagsForApplication(flags, userId, packageName); 3058 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 3059 // writer 3060 synchronized (mPackages) { 3061 PackageParser.Package p = mPackages.get(packageName); 3062 if (DEBUG_PACKAGE_INFO) Log.v( 3063 TAG, "getApplicationInfo " + packageName 3064 + ": " + p); 3065 if (p != null) { 3066 PackageSetting ps = mSettings.mPackages.get(packageName); 3067 if (ps == null) return null; 3068 // Note: isEnabledLP() does not apply here - always return info 3069 return PackageParser.generateApplicationInfo( 3070 p, flags, ps.readUserState(userId), userId); 3071 } 3072 if ("android".equals(packageName)||"system".equals(packageName)) { 3073 return mAndroidApplication; 3074 } 3075 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3076 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3077 } 3078 } 3079 return null; 3080 } 3081 3082 @Override 3083 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3084 final IPackageDataObserver observer) { 3085 mContext.enforceCallingOrSelfPermission( 3086 android.Manifest.permission.CLEAR_APP_CACHE, null); 3087 // Queue up an async operation since clearing cache may take a little while. 3088 mHandler.post(new Runnable() { 3089 public void run() { 3090 mHandler.removeCallbacks(this); 3091 boolean success = true; 3092 synchronized (mInstallLock) { 3093 try { 3094 mInstaller.freeCache(volumeUuid, freeStorageSize); 3095 } catch (InstallerException e) { 3096 Slog.w(TAG, "Couldn't clear application caches: " + e); 3097 success = false; 3098 } 3099 } 3100 if (observer != null) { 3101 try { 3102 observer.onRemoveCompleted(null, success); 3103 } catch (RemoteException e) { 3104 Slog.w(TAG, "RemoveException when invoking call back"); 3105 } 3106 } 3107 } 3108 }); 3109 } 3110 3111 @Override 3112 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3113 final IntentSender pi) { 3114 mContext.enforceCallingOrSelfPermission( 3115 android.Manifest.permission.CLEAR_APP_CACHE, null); 3116 // Queue up an async operation since clearing cache may take a little while. 3117 mHandler.post(new Runnable() { 3118 public void run() { 3119 mHandler.removeCallbacks(this); 3120 boolean success = true; 3121 synchronized (mInstallLock) { 3122 try { 3123 mInstaller.freeCache(volumeUuid, freeStorageSize); 3124 } catch (InstallerException e) { 3125 Slog.w(TAG, "Couldn't clear application caches: " + e); 3126 success = false; 3127 } 3128 } 3129 if(pi != null) { 3130 try { 3131 // Callback via pending intent 3132 int code = success ? 1 : 0; 3133 pi.sendIntent(null, code, null, 3134 null, null); 3135 } catch (SendIntentException e1) { 3136 Slog.i(TAG, "Failed to send pending intent"); 3137 } 3138 } 3139 } 3140 }); 3141 } 3142 3143 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3144 synchronized (mInstallLock) { 3145 try { 3146 mInstaller.freeCache(volumeUuid, freeStorageSize); 3147 } catch (InstallerException e) { 3148 throw new IOException("Failed to free enough space", e); 3149 } 3150 } 3151 } 3152 3153 /** 3154 * Return if the user key is currently unlocked. 3155 */ 3156 private boolean isUserKeyUnlocked(int userId) { 3157 if (StorageManager.isFileBasedEncryptionEnabled()) { 3158 final IMountService mount = IMountService.Stub 3159 .asInterface(ServiceManager.getService("mount")); 3160 if (mount == null) { 3161 Slog.w(TAG, "Early during boot, assuming locked"); 3162 return false; 3163 } 3164 final long token = Binder.clearCallingIdentity(); 3165 try { 3166 return mount.isUserKeyUnlocked(userId); 3167 } catch (RemoteException e) { 3168 throw e.rethrowAsRuntimeException(); 3169 } finally { 3170 Binder.restoreCallingIdentity(token); 3171 } 3172 } else { 3173 return true; 3174 } 3175 } 3176 3177 /** 3178 * Update given flags based on encryption status of current user. 3179 */ 3180 private int updateFlags(int flags, int userId) { 3181 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3182 | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) { 3183 // Caller expressed an explicit opinion about what encryption 3184 // aware/unaware components they want to see, so fall through and 3185 // give them what they want 3186 } else { 3187 // Caller expressed no opinion, so match based on user state 3188 if (isUserKeyUnlocked(userId)) { 3189 flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE; 3190 } else { 3191 flags |= PackageManager.MATCH_ENCRYPTION_AWARE; 3192 } 3193 } 3194 3195 // Safe mode means we should ignore any third-party apps 3196 if (mSafeMode) { 3197 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3198 } 3199 3200 return flags; 3201 } 3202 3203 /** 3204 * Update given flags when being used to request {@link PackageInfo}. 3205 */ 3206 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3207 boolean triaged = true; 3208 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3209 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3210 // Caller is asking for component details, so they'd better be 3211 // asking for specific encryption matching behavior, or be triaged 3212 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3213 | PackageManager.MATCH_ENCRYPTION_AWARE 3214 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3215 triaged = false; 3216 } 3217 } 3218 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3219 | PackageManager.MATCH_SYSTEM_ONLY 3220 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3221 triaged = false; 3222 } 3223 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3224 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3225 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3226 } 3227 return updateFlags(flags, userId); 3228 } 3229 3230 /** 3231 * Update given flags when being used to request {@link ApplicationInfo}. 3232 */ 3233 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3234 return updateFlagsForPackage(flags, userId, cookie); 3235 } 3236 3237 /** 3238 * Update given flags when being used to request {@link ComponentInfo}. 3239 */ 3240 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3241 if (cookie instanceof Intent) { 3242 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3243 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3244 } 3245 } 3246 3247 boolean triaged = true; 3248 // Caller is asking for component details, so they'd better be 3249 // asking for specific encryption matching behavior, or be triaged 3250 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3251 | PackageManager.MATCH_ENCRYPTION_AWARE 3252 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3253 triaged = false; 3254 } 3255 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3256 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3257 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3258 } 3259 return updateFlags(flags, userId); 3260 } 3261 3262 /** 3263 * Update given flags when being used to request {@link ResolveInfo}. 3264 */ 3265 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3266 return updateFlagsForComponent(flags, userId, cookie); 3267 } 3268 3269 @Override 3270 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3271 if (!sUserManager.exists(userId)) return null; 3272 flags = updateFlagsForComponent(flags, userId, component); 3273 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 3274 synchronized (mPackages) { 3275 PackageParser.Activity a = mActivities.mActivities.get(component); 3276 3277 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3278 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3279 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3280 if (ps == null) return null; 3281 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3282 userId); 3283 } 3284 if (mResolveComponentName.equals(component)) { 3285 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3286 new PackageUserState(), userId); 3287 } 3288 } 3289 return null; 3290 } 3291 3292 @Override 3293 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3294 String resolvedType) { 3295 synchronized (mPackages) { 3296 if (component.equals(mResolveComponentName)) { 3297 // The resolver supports EVERYTHING! 3298 return true; 3299 } 3300 PackageParser.Activity a = mActivities.mActivities.get(component); 3301 if (a == null) { 3302 return false; 3303 } 3304 for (int i=0; i<a.intents.size(); i++) { 3305 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3306 intent.getData(), intent.getCategories(), TAG) >= 0) { 3307 return true; 3308 } 3309 } 3310 return false; 3311 } 3312 } 3313 3314 @Override 3315 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3316 if (!sUserManager.exists(userId)) return null; 3317 flags = updateFlagsForComponent(flags, userId, component); 3318 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3319 synchronized (mPackages) { 3320 PackageParser.Activity a = mReceivers.mActivities.get(component); 3321 if (DEBUG_PACKAGE_INFO) Log.v( 3322 TAG, "getReceiverInfo " + component + ": " + a); 3323 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3324 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3325 if (ps == null) return null; 3326 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3327 userId); 3328 } 3329 } 3330 return null; 3331 } 3332 3333 @Override 3334 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3335 if (!sUserManager.exists(userId)) return null; 3336 flags = updateFlagsForComponent(flags, userId, component); 3337 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3338 synchronized (mPackages) { 3339 PackageParser.Service s = mServices.mServices.get(component); 3340 if (DEBUG_PACKAGE_INFO) Log.v( 3341 TAG, "getServiceInfo " + component + ": " + s); 3342 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3343 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3344 if (ps == null) return null; 3345 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3346 userId); 3347 } 3348 } 3349 return null; 3350 } 3351 3352 @Override 3353 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3354 if (!sUserManager.exists(userId)) return null; 3355 flags = updateFlagsForComponent(flags, userId, component); 3356 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3357 synchronized (mPackages) { 3358 PackageParser.Provider p = mProviders.mProviders.get(component); 3359 if (DEBUG_PACKAGE_INFO) Log.v( 3360 TAG, "getProviderInfo " + component + ": " + p); 3361 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3362 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3363 if (ps == null) return null; 3364 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3365 userId); 3366 } 3367 } 3368 return null; 3369 } 3370 3371 @Override 3372 public String[] getSystemSharedLibraryNames() { 3373 Set<String> libSet; 3374 synchronized (mPackages) { 3375 libSet = mSharedLibraries.keySet(); 3376 int size = libSet.size(); 3377 if (size > 0) { 3378 String[] libs = new String[size]; 3379 libSet.toArray(libs); 3380 return libs; 3381 } 3382 } 3383 return null; 3384 } 3385 3386 /** 3387 * @hide 3388 */ 3389 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3390 synchronized (mPackages) { 3391 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3392 if (lib != null && lib.apk != null) { 3393 return mPackages.get(lib.apk); 3394 } 3395 } 3396 return null; 3397 } 3398 3399 @Override 3400 public FeatureInfo[] getSystemAvailableFeatures() { 3401 Collection<FeatureInfo> featSet; 3402 synchronized (mPackages) { 3403 featSet = mAvailableFeatures.values(); 3404 int size = featSet.size(); 3405 if (size > 0) { 3406 FeatureInfo[] features = new FeatureInfo[size+1]; 3407 featSet.toArray(features); 3408 FeatureInfo fi = new FeatureInfo(); 3409 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3410 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3411 features[size] = fi; 3412 return features; 3413 } 3414 } 3415 return null; 3416 } 3417 3418 @Override 3419 public boolean hasSystemFeature(String name) { 3420 synchronized (mPackages) { 3421 return mAvailableFeatures.containsKey(name); 3422 } 3423 } 3424 3425 @Override 3426 public int checkPermission(String permName, String pkgName, int userId) { 3427 if (!sUserManager.exists(userId)) { 3428 return PackageManager.PERMISSION_DENIED; 3429 } 3430 3431 synchronized (mPackages) { 3432 final PackageParser.Package p = mPackages.get(pkgName); 3433 if (p != null && p.mExtras != null) { 3434 final PackageSetting ps = (PackageSetting) p.mExtras; 3435 final PermissionsState permissionsState = ps.getPermissionsState(); 3436 if (permissionsState.hasPermission(permName, userId)) { 3437 return PackageManager.PERMISSION_GRANTED; 3438 } 3439 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3440 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3441 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3442 return PackageManager.PERMISSION_GRANTED; 3443 } 3444 } 3445 } 3446 3447 return PackageManager.PERMISSION_DENIED; 3448 } 3449 3450 @Override 3451 public int checkUidPermission(String permName, int uid) { 3452 final int userId = UserHandle.getUserId(uid); 3453 3454 if (!sUserManager.exists(userId)) { 3455 return PackageManager.PERMISSION_DENIED; 3456 } 3457 3458 synchronized (mPackages) { 3459 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3460 if (obj != null) { 3461 final SettingBase ps = (SettingBase) obj; 3462 final PermissionsState permissionsState = ps.getPermissionsState(); 3463 if (permissionsState.hasPermission(permName, userId)) { 3464 return PackageManager.PERMISSION_GRANTED; 3465 } 3466 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3467 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3468 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3469 return PackageManager.PERMISSION_GRANTED; 3470 } 3471 } else { 3472 ArraySet<String> perms = mSystemPermissions.get(uid); 3473 if (perms != null) { 3474 if (perms.contains(permName)) { 3475 return PackageManager.PERMISSION_GRANTED; 3476 } 3477 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3478 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3479 return PackageManager.PERMISSION_GRANTED; 3480 } 3481 } 3482 } 3483 } 3484 3485 return PackageManager.PERMISSION_DENIED; 3486 } 3487 3488 @Override 3489 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3490 if (UserHandle.getCallingUserId() != userId) { 3491 mContext.enforceCallingPermission( 3492 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3493 "isPermissionRevokedByPolicy for user " + userId); 3494 } 3495 3496 if (checkPermission(permission, packageName, userId) 3497 == PackageManager.PERMISSION_GRANTED) { 3498 return false; 3499 } 3500 3501 final long identity = Binder.clearCallingIdentity(); 3502 try { 3503 final int flags = getPermissionFlags(permission, packageName, userId); 3504 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3505 } finally { 3506 Binder.restoreCallingIdentity(identity); 3507 } 3508 } 3509 3510 @Override 3511 public String getPermissionControllerPackageName() { 3512 synchronized (mPackages) { 3513 return mRequiredInstallerPackage; 3514 } 3515 } 3516 3517 /** 3518 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3519 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3520 * @param checkShell TODO(yamasani): 3521 * @param message the message to log on security exception 3522 */ 3523 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3524 boolean checkShell, String message) { 3525 if (userId < 0) { 3526 throw new IllegalArgumentException("Invalid userId " + userId); 3527 } 3528 if (checkShell) { 3529 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3530 } 3531 if (userId == UserHandle.getUserId(callingUid)) return; 3532 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3533 if (requireFullPermission) { 3534 mContext.enforceCallingOrSelfPermission( 3535 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3536 } else { 3537 try { 3538 mContext.enforceCallingOrSelfPermission( 3539 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3540 } catch (SecurityException se) { 3541 mContext.enforceCallingOrSelfPermission( 3542 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3543 } 3544 } 3545 } 3546 } 3547 3548 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3549 if (callingUid == Process.SHELL_UID) { 3550 if (userHandle >= 0 3551 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3552 throw new SecurityException("Shell does not have permission to access user " 3553 + userHandle); 3554 } else if (userHandle < 0) { 3555 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3556 + Debug.getCallers(3)); 3557 } 3558 } 3559 } 3560 3561 private BasePermission findPermissionTreeLP(String permName) { 3562 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3563 if (permName.startsWith(bp.name) && 3564 permName.length() > bp.name.length() && 3565 permName.charAt(bp.name.length()) == '.') { 3566 return bp; 3567 } 3568 } 3569 return null; 3570 } 3571 3572 private BasePermission checkPermissionTreeLP(String permName) { 3573 if (permName != null) { 3574 BasePermission bp = findPermissionTreeLP(permName); 3575 if (bp != null) { 3576 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3577 return bp; 3578 } 3579 throw new SecurityException("Calling uid " 3580 + Binder.getCallingUid() 3581 + " is not allowed to add to permission tree " 3582 + bp.name + " owned by uid " + bp.uid); 3583 } 3584 } 3585 throw new SecurityException("No permission tree found for " + permName); 3586 } 3587 3588 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3589 if (s1 == null) { 3590 return s2 == null; 3591 } 3592 if (s2 == null) { 3593 return false; 3594 } 3595 if (s1.getClass() != s2.getClass()) { 3596 return false; 3597 } 3598 return s1.equals(s2); 3599 } 3600 3601 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3602 if (pi1.icon != pi2.icon) return false; 3603 if (pi1.logo != pi2.logo) return false; 3604 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3605 if (!compareStrings(pi1.name, pi2.name)) return false; 3606 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3607 // We'll take care of setting this one. 3608 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3609 // These are not currently stored in settings. 3610 //if (!compareStrings(pi1.group, pi2.group)) return false; 3611 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3612 //if (pi1.labelRes != pi2.labelRes) return false; 3613 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3614 return true; 3615 } 3616 3617 int permissionInfoFootprint(PermissionInfo info) { 3618 int size = info.name.length(); 3619 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3620 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3621 return size; 3622 } 3623 3624 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3625 int size = 0; 3626 for (BasePermission perm : mSettings.mPermissions.values()) { 3627 if (perm.uid == tree.uid) { 3628 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3629 } 3630 } 3631 return size; 3632 } 3633 3634 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3635 // We calculate the max size of permissions defined by this uid and throw 3636 // if that plus the size of 'info' would exceed our stated maximum. 3637 if (tree.uid != Process.SYSTEM_UID) { 3638 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3639 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3640 throw new SecurityException("Permission tree size cap exceeded"); 3641 } 3642 } 3643 } 3644 3645 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3646 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3647 throw new SecurityException("Label must be specified in permission"); 3648 } 3649 BasePermission tree = checkPermissionTreeLP(info.name); 3650 BasePermission bp = mSettings.mPermissions.get(info.name); 3651 boolean added = bp == null; 3652 boolean changed = true; 3653 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3654 if (added) { 3655 enforcePermissionCapLocked(info, tree); 3656 bp = new BasePermission(info.name, tree.sourcePackage, 3657 BasePermission.TYPE_DYNAMIC); 3658 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3659 throw new SecurityException( 3660 "Not allowed to modify non-dynamic permission " 3661 + info.name); 3662 } else { 3663 if (bp.protectionLevel == fixedLevel 3664 && bp.perm.owner.equals(tree.perm.owner) 3665 && bp.uid == tree.uid 3666 && comparePermissionInfos(bp.perm.info, info)) { 3667 changed = false; 3668 } 3669 } 3670 bp.protectionLevel = fixedLevel; 3671 info = new PermissionInfo(info); 3672 info.protectionLevel = fixedLevel; 3673 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3674 bp.perm.info.packageName = tree.perm.info.packageName; 3675 bp.uid = tree.uid; 3676 if (added) { 3677 mSettings.mPermissions.put(info.name, bp); 3678 } 3679 if (changed) { 3680 if (!async) { 3681 mSettings.writeLPr(); 3682 } else { 3683 scheduleWriteSettingsLocked(); 3684 } 3685 } 3686 return added; 3687 } 3688 3689 @Override 3690 public boolean addPermission(PermissionInfo info) { 3691 synchronized (mPackages) { 3692 return addPermissionLocked(info, false); 3693 } 3694 } 3695 3696 @Override 3697 public boolean addPermissionAsync(PermissionInfo info) { 3698 synchronized (mPackages) { 3699 return addPermissionLocked(info, true); 3700 } 3701 } 3702 3703 @Override 3704 public void removePermission(String name) { 3705 synchronized (mPackages) { 3706 checkPermissionTreeLP(name); 3707 BasePermission bp = mSettings.mPermissions.get(name); 3708 if (bp != null) { 3709 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3710 throw new SecurityException( 3711 "Not allowed to modify non-dynamic permission " 3712 + name); 3713 } 3714 mSettings.mPermissions.remove(name); 3715 mSettings.writeLPr(); 3716 } 3717 } 3718 } 3719 3720 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3721 BasePermission bp) { 3722 int index = pkg.requestedPermissions.indexOf(bp.name); 3723 if (index == -1) { 3724 throw new SecurityException("Package " + pkg.packageName 3725 + " has not requested permission " + bp.name); 3726 } 3727 if (!bp.isRuntime() && !bp.isDevelopment()) { 3728 throw new SecurityException("Permission " + bp.name 3729 + " is not a changeable permission type"); 3730 } 3731 } 3732 3733 @Override 3734 public void grantRuntimePermission(String packageName, String name, final int userId) { 3735 if (!sUserManager.exists(userId)) { 3736 Log.e(TAG, "No such user:" + userId); 3737 return; 3738 } 3739 3740 mContext.enforceCallingOrSelfPermission( 3741 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3742 "grantRuntimePermission"); 3743 3744 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3745 "grantRuntimePermission"); 3746 3747 final int uid; 3748 final SettingBase sb; 3749 3750 synchronized (mPackages) { 3751 final PackageParser.Package pkg = mPackages.get(packageName); 3752 if (pkg == null) { 3753 throw new IllegalArgumentException("Unknown package: " + packageName); 3754 } 3755 3756 final BasePermission bp = mSettings.mPermissions.get(name); 3757 if (bp == null) { 3758 throw new IllegalArgumentException("Unknown permission: " + name); 3759 } 3760 3761 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3762 3763 // If a permission review is required for legacy apps we represent 3764 // their permissions as always granted runtime ones since we need 3765 // to keep the review required permission flag per user while an 3766 // install permission's state is shared across all users. 3767 if (Build.PERMISSIONS_REVIEW_REQUIRED 3768 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3769 && bp.isRuntime()) { 3770 return; 3771 } 3772 3773 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3774 sb = (SettingBase) pkg.mExtras; 3775 if (sb == null) { 3776 throw new IllegalArgumentException("Unknown package: " + packageName); 3777 } 3778 3779 final PermissionsState permissionsState = sb.getPermissionsState(); 3780 3781 final int flags = permissionsState.getPermissionFlags(name, userId); 3782 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3783 throw new SecurityException("Cannot grant system fixed permission " 3784 + name + " for package " + packageName); 3785 } 3786 3787 if (bp.isDevelopment()) { 3788 // Development permissions must be handled specially, since they are not 3789 // normal runtime permissions. For now they apply to all users. 3790 if (permissionsState.grantInstallPermission(bp) != 3791 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3792 scheduleWriteSettingsLocked(); 3793 } 3794 return; 3795 } 3796 3797 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 3798 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 3799 return; 3800 } 3801 3802 final int result = permissionsState.grantRuntimePermission(bp, userId); 3803 switch (result) { 3804 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3805 return; 3806 } 3807 3808 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3809 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3810 mHandler.post(new Runnable() { 3811 @Override 3812 public void run() { 3813 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3814 } 3815 }); 3816 } 3817 break; 3818 } 3819 3820 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3821 3822 // Not critical if that is lost - app has to request again. 3823 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3824 } 3825 3826 // Only need to do this if user is initialized. Otherwise it's a new user 3827 // and there are no processes running as the user yet and there's no need 3828 // to make an expensive call to remount processes for the changed permissions. 3829 if (READ_EXTERNAL_STORAGE.equals(name) 3830 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3831 final long token = Binder.clearCallingIdentity(); 3832 try { 3833 if (sUserManager.isInitialized(userId)) { 3834 MountServiceInternal mountServiceInternal = LocalServices.getService( 3835 MountServiceInternal.class); 3836 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3837 } 3838 } finally { 3839 Binder.restoreCallingIdentity(token); 3840 } 3841 } 3842 } 3843 3844 @Override 3845 public void revokeRuntimePermission(String packageName, String name, int userId) { 3846 if (!sUserManager.exists(userId)) { 3847 Log.e(TAG, "No such user:" + userId); 3848 return; 3849 } 3850 3851 mContext.enforceCallingOrSelfPermission( 3852 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3853 "revokeRuntimePermission"); 3854 3855 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3856 "revokeRuntimePermission"); 3857 3858 final int appId; 3859 3860 synchronized (mPackages) { 3861 final PackageParser.Package pkg = mPackages.get(packageName); 3862 if (pkg == null) { 3863 throw new IllegalArgumentException("Unknown package: " + packageName); 3864 } 3865 3866 final BasePermission bp = mSettings.mPermissions.get(name); 3867 if (bp == null) { 3868 throw new IllegalArgumentException("Unknown permission: " + name); 3869 } 3870 3871 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3872 3873 // If a permission review is required for legacy apps we represent 3874 // their permissions as always granted runtime ones since we need 3875 // to keep the review required permission flag per user while an 3876 // install permission's state is shared across all users. 3877 if (Build.PERMISSIONS_REVIEW_REQUIRED 3878 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3879 && bp.isRuntime()) { 3880 return; 3881 } 3882 3883 SettingBase sb = (SettingBase) pkg.mExtras; 3884 if (sb == null) { 3885 throw new IllegalArgumentException("Unknown package: " + packageName); 3886 } 3887 3888 final PermissionsState permissionsState = sb.getPermissionsState(); 3889 3890 final int flags = permissionsState.getPermissionFlags(name, userId); 3891 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3892 throw new SecurityException("Cannot revoke system fixed permission " 3893 + name + " for package " + packageName); 3894 } 3895 3896 if (bp.isDevelopment()) { 3897 // Development permissions must be handled specially, since they are not 3898 // normal runtime permissions. For now they apply to all users. 3899 if (permissionsState.revokeInstallPermission(bp) != 3900 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3901 scheduleWriteSettingsLocked(); 3902 } 3903 return; 3904 } 3905 3906 if (permissionsState.revokeRuntimePermission(bp, userId) == 3907 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3908 return; 3909 } 3910 3911 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3912 3913 // Critical, after this call app should never have the permission. 3914 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3915 3916 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3917 } 3918 3919 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3920 } 3921 3922 @Override 3923 public void resetRuntimePermissions() { 3924 mContext.enforceCallingOrSelfPermission( 3925 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3926 "revokeRuntimePermission"); 3927 3928 int callingUid = Binder.getCallingUid(); 3929 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3930 mContext.enforceCallingOrSelfPermission( 3931 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3932 "resetRuntimePermissions"); 3933 } 3934 3935 synchronized (mPackages) { 3936 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3937 for (int userId : UserManagerService.getInstance().getUserIds()) { 3938 final int packageCount = mPackages.size(); 3939 for (int i = 0; i < packageCount; i++) { 3940 PackageParser.Package pkg = mPackages.valueAt(i); 3941 if (!(pkg.mExtras instanceof PackageSetting)) { 3942 continue; 3943 } 3944 PackageSetting ps = (PackageSetting) pkg.mExtras; 3945 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3946 } 3947 } 3948 } 3949 } 3950 3951 @Override 3952 public int getPermissionFlags(String name, String packageName, int userId) { 3953 if (!sUserManager.exists(userId)) { 3954 return 0; 3955 } 3956 3957 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3958 3959 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3960 "getPermissionFlags"); 3961 3962 synchronized (mPackages) { 3963 final PackageParser.Package pkg = mPackages.get(packageName); 3964 if (pkg == null) { 3965 throw new IllegalArgumentException("Unknown package: " + packageName); 3966 } 3967 3968 final BasePermission bp = mSettings.mPermissions.get(name); 3969 if (bp == null) { 3970 throw new IllegalArgumentException("Unknown permission: " + name); 3971 } 3972 3973 SettingBase sb = (SettingBase) pkg.mExtras; 3974 if (sb == null) { 3975 throw new IllegalArgumentException("Unknown package: " + packageName); 3976 } 3977 3978 PermissionsState permissionsState = sb.getPermissionsState(); 3979 return permissionsState.getPermissionFlags(name, userId); 3980 } 3981 } 3982 3983 @Override 3984 public void updatePermissionFlags(String name, String packageName, int flagMask, 3985 int flagValues, int userId) { 3986 if (!sUserManager.exists(userId)) { 3987 return; 3988 } 3989 3990 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3991 3992 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3993 "updatePermissionFlags"); 3994 3995 // Only the system can change these flags and nothing else. 3996 if (getCallingUid() != Process.SYSTEM_UID) { 3997 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3998 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3999 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4000 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4001 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4002 } 4003 4004 synchronized (mPackages) { 4005 final PackageParser.Package pkg = mPackages.get(packageName); 4006 if (pkg == null) { 4007 throw new IllegalArgumentException("Unknown package: " + packageName); 4008 } 4009 4010 final BasePermission bp = mSettings.mPermissions.get(name); 4011 if (bp == null) { 4012 throw new IllegalArgumentException("Unknown permission: " + name); 4013 } 4014 4015 SettingBase sb = (SettingBase) pkg.mExtras; 4016 if (sb == null) { 4017 throw new IllegalArgumentException("Unknown package: " + packageName); 4018 } 4019 4020 PermissionsState permissionsState = sb.getPermissionsState(); 4021 4022 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4023 4024 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4025 // Install and runtime permissions are stored in different places, 4026 // so figure out what permission changed and persist the change. 4027 if (permissionsState.getInstallPermissionState(name) != null) { 4028 scheduleWriteSettingsLocked(); 4029 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4030 || hadState) { 4031 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4032 } 4033 } 4034 } 4035 } 4036 4037 /** 4038 * Update the permission flags for all packages and runtime permissions of a user in order 4039 * to allow device or profile owner to remove POLICY_FIXED. 4040 */ 4041 @Override 4042 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4043 if (!sUserManager.exists(userId)) { 4044 return; 4045 } 4046 4047 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4048 4049 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 4050 "updatePermissionFlagsForAllApps"); 4051 4052 // Only the system can change system fixed flags. 4053 if (getCallingUid() != Process.SYSTEM_UID) { 4054 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4055 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4056 } 4057 4058 synchronized (mPackages) { 4059 boolean changed = false; 4060 final int packageCount = mPackages.size(); 4061 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4062 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4063 SettingBase sb = (SettingBase) pkg.mExtras; 4064 if (sb == null) { 4065 continue; 4066 } 4067 PermissionsState permissionsState = sb.getPermissionsState(); 4068 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4069 userId, flagMask, flagValues); 4070 } 4071 if (changed) { 4072 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4073 } 4074 } 4075 } 4076 4077 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4078 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4079 != PackageManager.PERMISSION_GRANTED 4080 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4081 != PackageManager.PERMISSION_GRANTED) { 4082 throw new SecurityException(message + " requires " 4083 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4084 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4085 } 4086 } 4087 4088 @Override 4089 public boolean shouldShowRequestPermissionRationale(String permissionName, 4090 String packageName, int userId) { 4091 if (UserHandle.getCallingUserId() != userId) { 4092 mContext.enforceCallingPermission( 4093 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4094 "canShowRequestPermissionRationale for user " + userId); 4095 } 4096 4097 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4098 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4099 return false; 4100 } 4101 4102 if (checkPermission(permissionName, packageName, userId) 4103 == PackageManager.PERMISSION_GRANTED) { 4104 return false; 4105 } 4106 4107 final int flags; 4108 4109 final long identity = Binder.clearCallingIdentity(); 4110 try { 4111 flags = getPermissionFlags(permissionName, 4112 packageName, userId); 4113 } finally { 4114 Binder.restoreCallingIdentity(identity); 4115 } 4116 4117 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4118 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4119 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4120 4121 if ((flags & fixedFlags) != 0) { 4122 return false; 4123 } 4124 4125 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4126 } 4127 4128 @Override 4129 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4130 mContext.enforceCallingOrSelfPermission( 4131 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4132 "addOnPermissionsChangeListener"); 4133 4134 synchronized (mPackages) { 4135 mOnPermissionChangeListeners.addListenerLocked(listener); 4136 } 4137 } 4138 4139 @Override 4140 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4141 synchronized (mPackages) { 4142 mOnPermissionChangeListeners.removeListenerLocked(listener); 4143 } 4144 } 4145 4146 @Override 4147 public boolean isProtectedBroadcast(String actionName) { 4148 synchronized (mPackages) { 4149 if (mProtectedBroadcasts.contains(actionName)) { 4150 return true; 4151 } else if (actionName != null) { 4152 // TODO: remove these terrible hacks 4153 if (actionName.startsWith("android.net.netmon.lingerExpired") 4154 || actionName.startsWith("com.android.server.sip.SipWakeupTimer")) { 4155 return true; 4156 } 4157 } 4158 } 4159 return false; 4160 } 4161 4162 @Override 4163 public int checkSignatures(String pkg1, String pkg2) { 4164 synchronized (mPackages) { 4165 final PackageParser.Package p1 = mPackages.get(pkg1); 4166 final PackageParser.Package p2 = mPackages.get(pkg2); 4167 if (p1 == null || p1.mExtras == null 4168 || p2 == null || p2.mExtras == null) { 4169 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4170 } 4171 return compareSignatures(p1.mSignatures, p2.mSignatures); 4172 } 4173 } 4174 4175 @Override 4176 public int checkUidSignatures(int uid1, int uid2) { 4177 // Map to base uids. 4178 uid1 = UserHandle.getAppId(uid1); 4179 uid2 = UserHandle.getAppId(uid2); 4180 // reader 4181 synchronized (mPackages) { 4182 Signature[] s1; 4183 Signature[] s2; 4184 Object obj = mSettings.getUserIdLPr(uid1); 4185 if (obj != null) { 4186 if (obj instanceof SharedUserSetting) { 4187 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4188 } else if (obj instanceof PackageSetting) { 4189 s1 = ((PackageSetting)obj).signatures.mSignatures; 4190 } else { 4191 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4192 } 4193 } else { 4194 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4195 } 4196 obj = mSettings.getUserIdLPr(uid2); 4197 if (obj != null) { 4198 if (obj instanceof SharedUserSetting) { 4199 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4200 } else if (obj instanceof PackageSetting) { 4201 s2 = ((PackageSetting)obj).signatures.mSignatures; 4202 } else { 4203 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4204 } 4205 } else { 4206 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4207 } 4208 return compareSignatures(s1, s2); 4209 } 4210 } 4211 4212 private void killUid(int appId, int userId, String reason) { 4213 final long identity = Binder.clearCallingIdentity(); 4214 try { 4215 IActivityManager am = ActivityManagerNative.getDefault(); 4216 if (am != null) { 4217 try { 4218 am.killUid(appId, userId, reason); 4219 } catch (RemoteException e) { 4220 /* ignore - same process */ 4221 } 4222 } 4223 } finally { 4224 Binder.restoreCallingIdentity(identity); 4225 } 4226 } 4227 4228 /** 4229 * Compares two sets of signatures. Returns: 4230 * <br /> 4231 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4232 * <br /> 4233 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4234 * <br /> 4235 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4236 * <br /> 4237 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4238 * <br /> 4239 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4240 */ 4241 static int compareSignatures(Signature[] s1, Signature[] s2) { 4242 if (s1 == null) { 4243 return s2 == null 4244 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4245 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4246 } 4247 4248 if (s2 == null) { 4249 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4250 } 4251 4252 if (s1.length != s2.length) { 4253 return PackageManager.SIGNATURE_NO_MATCH; 4254 } 4255 4256 // Since both signature sets are of size 1, we can compare without HashSets. 4257 if (s1.length == 1) { 4258 return s1[0].equals(s2[0]) ? 4259 PackageManager.SIGNATURE_MATCH : 4260 PackageManager.SIGNATURE_NO_MATCH; 4261 } 4262 4263 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4264 for (Signature sig : s1) { 4265 set1.add(sig); 4266 } 4267 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4268 for (Signature sig : s2) { 4269 set2.add(sig); 4270 } 4271 // Make sure s2 contains all signatures in s1. 4272 if (set1.equals(set2)) { 4273 return PackageManager.SIGNATURE_MATCH; 4274 } 4275 return PackageManager.SIGNATURE_NO_MATCH; 4276 } 4277 4278 /** 4279 * If the database version for this type of package (internal storage or 4280 * external storage) is less than the version where package signatures 4281 * were updated, return true. 4282 */ 4283 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4284 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4285 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4286 } 4287 4288 /** 4289 * Used for backward compatibility to make sure any packages with 4290 * certificate chains get upgraded to the new style. {@code existingSigs} 4291 * will be in the old format (since they were stored on disk from before the 4292 * system upgrade) and {@code scannedSigs} will be in the newer format. 4293 */ 4294 private int compareSignaturesCompat(PackageSignatures existingSigs, 4295 PackageParser.Package scannedPkg) { 4296 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4297 return PackageManager.SIGNATURE_NO_MATCH; 4298 } 4299 4300 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4301 for (Signature sig : existingSigs.mSignatures) { 4302 existingSet.add(sig); 4303 } 4304 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4305 for (Signature sig : scannedPkg.mSignatures) { 4306 try { 4307 Signature[] chainSignatures = sig.getChainSignatures(); 4308 for (Signature chainSig : chainSignatures) { 4309 scannedCompatSet.add(chainSig); 4310 } 4311 } catch (CertificateEncodingException e) { 4312 scannedCompatSet.add(sig); 4313 } 4314 } 4315 /* 4316 * Make sure the expanded scanned set contains all signatures in the 4317 * existing one. 4318 */ 4319 if (scannedCompatSet.equals(existingSet)) { 4320 // Migrate the old signatures to the new scheme. 4321 existingSigs.assignSignatures(scannedPkg.mSignatures); 4322 // The new KeySets will be re-added later in the scanning process. 4323 synchronized (mPackages) { 4324 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4325 } 4326 return PackageManager.SIGNATURE_MATCH; 4327 } 4328 return PackageManager.SIGNATURE_NO_MATCH; 4329 } 4330 4331 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4332 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4333 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4334 } 4335 4336 private int compareSignaturesRecover(PackageSignatures existingSigs, 4337 PackageParser.Package scannedPkg) { 4338 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4339 return PackageManager.SIGNATURE_NO_MATCH; 4340 } 4341 4342 String msg = null; 4343 try { 4344 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4345 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4346 + scannedPkg.packageName); 4347 return PackageManager.SIGNATURE_MATCH; 4348 } 4349 } catch (CertificateException e) { 4350 msg = e.getMessage(); 4351 } 4352 4353 logCriticalInfo(Log.INFO, 4354 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4355 return PackageManager.SIGNATURE_NO_MATCH; 4356 } 4357 4358 @Override 4359 public String[] getPackagesForUid(int uid) { 4360 uid = UserHandle.getAppId(uid); 4361 // reader 4362 synchronized (mPackages) { 4363 Object obj = mSettings.getUserIdLPr(uid); 4364 if (obj instanceof SharedUserSetting) { 4365 final SharedUserSetting sus = (SharedUserSetting) obj; 4366 final int N = sus.packages.size(); 4367 final String[] res = new String[N]; 4368 final Iterator<PackageSetting> it = sus.packages.iterator(); 4369 int i = 0; 4370 while (it.hasNext()) { 4371 res[i++] = it.next().name; 4372 } 4373 return res; 4374 } else if (obj instanceof PackageSetting) { 4375 final PackageSetting ps = (PackageSetting) obj; 4376 return new String[] { ps.name }; 4377 } 4378 } 4379 return null; 4380 } 4381 4382 @Override 4383 public String getNameForUid(int uid) { 4384 // reader 4385 synchronized (mPackages) { 4386 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4387 if (obj instanceof SharedUserSetting) { 4388 final SharedUserSetting sus = (SharedUserSetting) obj; 4389 return sus.name + ":" + sus.userId; 4390 } else if (obj instanceof PackageSetting) { 4391 final PackageSetting ps = (PackageSetting) obj; 4392 return ps.name; 4393 } 4394 } 4395 return null; 4396 } 4397 4398 @Override 4399 public int getUidForSharedUser(String sharedUserName) { 4400 if(sharedUserName == null) { 4401 return -1; 4402 } 4403 // reader 4404 synchronized (mPackages) { 4405 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4406 if (suid == null) { 4407 return -1; 4408 } 4409 return suid.userId; 4410 } 4411 } 4412 4413 @Override 4414 public int getFlagsForUid(int uid) { 4415 synchronized (mPackages) { 4416 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4417 if (obj instanceof SharedUserSetting) { 4418 final SharedUserSetting sus = (SharedUserSetting) obj; 4419 return sus.pkgFlags; 4420 } else if (obj instanceof PackageSetting) { 4421 final PackageSetting ps = (PackageSetting) obj; 4422 return ps.pkgFlags; 4423 } 4424 } 4425 return 0; 4426 } 4427 4428 @Override 4429 public int getPrivateFlagsForUid(int uid) { 4430 synchronized (mPackages) { 4431 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4432 if (obj instanceof SharedUserSetting) { 4433 final SharedUserSetting sus = (SharedUserSetting) obj; 4434 return sus.pkgPrivateFlags; 4435 } else if (obj instanceof PackageSetting) { 4436 final PackageSetting ps = (PackageSetting) obj; 4437 return ps.pkgPrivateFlags; 4438 } 4439 } 4440 return 0; 4441 } 4442 4443 @Override 4444 public boolean isUidPrivileged(int uid) { 4445 uid = UserHandle.getAppId(uid); 4446 // reader 4447 synchronized (mPackages) { 4448 Object obj = mSettings.getUserIdLPr(uid); 4449 if (obj instanceof SharedUserSetting) { 4450 final SharedUserSetting sus = (SharedUserSetting) obj; 4451 final Iterator<PackageSetting> it = sus.packages.iterator(); 4452 while (it.hasNext()) { 4453 if (it.next().isPrivileged()) { 4454 return true; 4455 } 4456 } 4457 } else if (obj instanceof PackageSetting) { 4458 final PackageSetting ps = (PackageSetting) obj; 4459 return ps.isPrivileged(); 4460 } 4461 } 4462 return false; 4463 } 4464 4465 @Override 4466 public String[] getAppOpPermissionPackages(String permissionName) { 4467 synchronized (mPackages) { 4468 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4469 if (pkgs == null) { 4470 return null; 4471 } 4472 return pkgs.toArray(new String[pkgs.size()]); 4473 } 4474 } 4475 4476 @Override 4477 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4478 int flags, int userId) { 4479 if (!sUserManager.exists(userId)) return null; 4480 flags = updateFlagsForResolve(flags, userId, intent); 4481 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4482 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4483 final ResolveInfo bestChoice = 4484 chooseBestActivity(intent, resolvedType, flags, query, userId); 4485 4486 if (isEphemeralAllowed(intent, query, userId)) { 4487 final EphemeralResolveInfo ai = 4488 getEphemeralResolveInfo(intent, resolvedType, userId); 4489 if (ai != null) { 4490 if (DEBUG_EPHEMERAL) { 4491 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4492 } 4493 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4494 bestChoice.ephemeralResolveInfo = ai; 4495 } 4496 } 4497 return bestChoice; 4498 } 4499 4500 @Override 4501 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4502 IntentFilter filter, int match, ComponentName activity) { 4503 final int userId = UserHandle.getCallingUserId(); 4504 if (DEBUG_PREFERRED) { 4505 Log.v(TAG, "setLastChosenActivity intent=" + intent 4506 + " resolvedType=" + resolvedType 4507 + " flags=" + flags 4508 + " filter=" + filter 4509 + " match=" + match 4510 + " activity=" + activity); 4511 filter.dump(new PrintStreamPrinter(System.out), " "); 4512 } 4513 intent.setComponent(null); 4514 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4515 // Find any earlier preferred or last chosen entries and nuke them 4516 findPreferredActivity(intent, resolvedType, 4517 flags, query, 0, false, true, false, userId); 4518 // Add the new activity as the last chosen for this filter 4519 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4520 "Setting last chosen"); 4521 } 4522 4523 @Override 4524 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4525 final int userId = UserHandle.getCallingUserId(); 4526 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4527 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4528 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4529 false, false, false, userId); 4530 } 4531 4532 4533 private boolean isEphemeralAllowed( 4534 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4535 // Short circuit and return early if possible. 4536 if (DISABLE_EPHEMERAL_APPS) { 4537 return false; 4538 } 4539 final int callingUser = UserHandle.getCallingUserId(); 4540 if (callingUser != UserHandle.USER_SYSTEM) { 4541 return false; 4542 } 4543 if (mEphemeralResolverConnection == null) { 4544 return false; 4545 } 4546 if (intent.getComponent() != null) { 4547 return false; 4548 } 4549 if (intent.getPackage() != null) { 4550 return false; 4551 } 4552 final boolean isWebUri = hasWebURI(intent); 4553 if (!isWebUri) { 4554 return false; 4555 } 4556 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4557 synchronized (mPackages) { 4558 final int count = resolvedActivites.size(); 4559 for (int n = 0; n < count; n++) { 4560 ResolveInfo info = resolvedActivites.get(n); 4561 String packageName = info.activityInfo.packageName; 4562 PackageSetting ps = mSettings.mPackages.get(packageName); 4563 if (ps != null) { 4564 // Try to get the status from User settings first 4565 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4566 int status = (int) (packedStatus >> 32); 4567 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4568 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4569 if (DEBUG_EPHEMERAL) { 4570 Slog.v(TAG, "DENY ephemeral apps;" 4571 + " pkg: " + packageName + ", status: " + status); 4572 } 4573 return false; 4574 } 4575 } 4576 } 4577 } 4578 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4579 return true; 4580 } 4581 4582 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4583 int userId) { 4584 MessageDigest digest = null; 4585 try { 4586 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4587 } catch (NoSuchAlgorithmException e) { 4588 // If we can't create a digest, ignore ephemeral apps. 4589 return null; 4590 } 4591 4592 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4593 final byte[] digestBytes = digest.digest(hostBytes); 4594 int shaPrefix = 4595 digestBytes[0] << 24 4596 | digestBytes[1] << 16 4597 | digestBytes[2] << 8 4598 | digestBytes[3] << 0; 4599 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4600 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4601 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4602 // No hash prefix match; there are no ephemeral apps for this domain. 4603 return null; 4604 } 4605 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4606 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4607 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4608 continue; 4609 } 4610 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4611 // No filters; this should never happen. 4612 if (filters.isEmpty()) { 4613 continue; 4614 } 4615 // We have a domain match; resolve the filters to see if anything matches. 4616 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4617 for (int j = filters.size() - 1; j >= 0; --j) { 4618 final EphemeralResolveIntentInfo intentInfo = 4619 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4620 ephemeralResolver.addFilter(intentInfo); 4621 } 4622 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4623 intent, resolvedType, false /*defaultOnly*/, userId); 4624 if (!matchedResolveInfoList.isEmpty()) { 4625 return matchedResolveInfoList.get(0); 4626 } 4627 } 4628 // Hash or filter mis-match; no ephemeral apps for this domain. 4629 return null; 4630 } 4631 4632 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4633 int flags, List<ResolveInfo> query, int userId) { 4634 if (query != null) { 4635 final int N = query.size(); 4636 if (N == 1) { 4637 return query.get(0); 4638 } else if (N > 1) { 4639 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4640 // If there is more than one activity with the same priority, 4641 // then let the user decide between them. 4642 ResolveInfo r0 = query.get(0); 4643 ResolveInfo r1 = query.get(1); 4644 if (DEBUG_INTENT_MATCHING || debug) { 4645 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4646 + r1.activityInfo.name + "=" + r1.priority); 4647 } 4648 // If the first activity has a higher priority, or a different 4649 // default, then it is always desirable to pick it. 4650 if (r0.priority != r1.priority 4651 || r0.preferredOrder != r1.preferredOrder 4652 || r0.isDefault != r1.isDefault) { 4653 return query.get(0); 4654 } 4655 // If we have saved a preference for a preferred activity for 4656 // this Intent, use that. 4657 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4658 flags, query, r0.priority, true, false, debug, userId); 4659 if (ri != null) { 4660 return ri; 4661 } 4662 ri = new ResolveInfo(mResolveInfo); 4663 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4664 ri.activityInfo.applicationInfo = new ApplicationInfo( 4665 ri.activityInfo.applicationInfo); 4666 if (userId != 0) { 4667 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4668 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4669 } 4670 // Make sure that the resolver is displayable in car mode 4671 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4672 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4673 return ri; 4674 } 4675 } 4676 return null; 4677 } 4678 4679 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4680 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4681 final int N = query.size(); 4682 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4683 .get(userId); 4684 // Get the list of persistent preferred activities that handle the intent 4685 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4686 List<PersistentPreferredActivity> pprefs = ppir != null 4687 ? ppir.queryIntent(intent, resolvedType, 4688 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4689 : null; 4690 if (pprefs != null && pprefs.size() > 0) { 4691 final int M = pprefs.size(); 4692 for (int i=0; i<M; i++) { 4693 final PersistentPreferredActivity ppa = pprefs.get(i); 4694 if (DEBUG_PREFERRED || debug) { 4695 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4696 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4697 + "\n component=" + ppa.mComponent); 4698 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4699 } 4700 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4701 flags | MATCH_DISABLED_COMPONENTS, userId); 4702 if (DEBUG_PREFERRED || debug) { 4703 Slog.v(TAG, "Found persistent preferred activity:"); 4704 if (ai != null) { 4705 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4706 } else { 4707 Slog.v(TAG, " null"); 4708 } 4709 } 4710 if (ai == null) { 4711 // This previously registered persistent preferred activity 4712 // component is no longer known. Ignore it and do NOT remove it. 4713 continue; 4714 } 4715 for (int j=0; j<N; j++) { 4716 final ResolveInfo ri = query.get(j); 4717 if (!ri.activityInfo.applicationInfo.packageName 4718 .equals(ai.applicationInfo.packageName)) { 4719 continue; 4720 } 4721 if (!ri.activityInfo.name.equals(ai.name)) { 4722 continue; 4723 } 4724 // Found a persistent preference that can handle the intent. 4725 if (DEBUG_PREFERRED || debug) { 4726 Slog.v(TAG, "Returning persistent preferred activity: " + 4727 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4728 } 4729 return ri; 4730 } 4731 } 4732 } 4733 return null; 4734 } 4735 4736 // TODO: handle preferred activities missing while user has amnesia 4737 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4738 List<ResolveInfo> query, int priority, boolean always, 4739 boolean removeMatches, boolean debug, int userId) { 4740 if (!sUserManager.exists(userId)) return null; 4741 flags = updateFlagsForResolve(flags, userId, intent); 4742 // writer 4743 synchronized (mPackages) { 4744 if (intent.getSelector() != null) { 4745 intent = intent.getSelector(); 4746 } 4747 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4748 4749 // Try to find a matching persistent preferred activity. 4750 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4751 debug, userId); 4752 4753 // If a persistent preferred activity matched, use it. 4754 if (pri != null) { 4755 return pri; 4756 } 4757 4758 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4759 // Get the list of preferred activities that handle the intent 4760 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4761 List<PreferredActivity> prefs = pir != null 4762 ? pir.queryIntent(intent, resolvedType, 4763 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4764 : null; 4765 if (prefs != null && prefs.size() > 0) { 4766 boolean changed = false; 4767 try { 4768 // First figure out how good the original match set is. 4769 // We will only allow preferred activities that came 4770 // from the same match quality. 4771 int match = 0; 4772 4773 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4774 4775 final int N = query.size(); 4776 for (int j=0; j<N; j++) { 4777 final ResolveInfo ri = query.get(j); 4778 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4779 + ": 0x" + Integer.toHexString(match)); 4780 if (ri.match > match) { 4781 match = ri.match; 4782 } 4783 } 4784 4785 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4786 + Integer.toHexString(match)); 4787 4788 match &= IntentFilter.MATCH_CATEGORY_MASK; 4789 final int M = prefs.size(); 4790 for (int i=0; i<M; i++) { 4791 final PreferredActivity pa = prefs.get(i); 4792 if (DEBUG_PREFERRED || debug) { 4793 Slog.v(TAG, "Checking PreferredActivity ds=" 4794 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4795 + "\n component=" + pa.mPref.mComponent); 4796 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4797 } 4798 if (pa.mPref.mMatch != match) { 4799 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4800 + Integer.toHexString(pa.mPref.mMatch)); 4801 continue; 4802 } 4803 // If it's not an "always" type preferred activity and that's what we're 4804 // looking for, skip it. 4805 if (always && !pa.mPref.mAlways) { 4806 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4807 continue; 4808 } 4809 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4810 flags | MATCH_DISABLED_COMPONENTS, userId); 4811 if (DEBUG_PREFERRED || debug) { 4812 Slog.v(TAG, "Found preferred activity:"); 4813 if (ai != null) { 4814 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4815 } else { 4816 Slog.v(TAG, " null"); 4817 } 4818 } 4819 if (ai == null) { 4820 // This previously registered preferred activity 4821 // component is no longer known. Most likely an update 4822 // to the app was installed and in the new version this 4823 // component no longer exists. Clean it up by removing 4824 // it from the preferred activities list, and skip it. 4825 Slog.w(TAG, "Removing dangling preferred activity: " 4826 + pa.mPref.mComponent); 4827 pir.removeFilter(pa); 4828 changed = true; 4829 continue; 4830 } 4831 for (int j=0; j<N; j++) { 4832 final ResolveInfo ri = query.get(j); 4833 if (!ri.activityInfo.applicationInfo.packageName 4834 .equals(ai.applicationInfo.packageName)) { 4835 continue; 4836 } 4837 if (!ri.activityInfo.name.equals(ai.name)) { 4838 continue; 4839 } 4840 4841 if (removeMatches) { 4842 pir.removeFilter(pa); 4843 changed = true; 4844 if (DEBUG_PREFERRED) { 4845 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4846 } 4847 break; 4848 } 4849 4850 // Okay we found a previously set preferred or last chosen app. 4851 // If the result set is different from when this 4852 // was created, we need to clear it and re-ask the 4853 // user their preference, if we're looking for an "always" type entry. 4854 if (always && !pa.mPref.sameSet(query)) { 4855 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4856 + intent + " type " + resolvedType); 4857 if (DEBUG_PREFERRED) { 4858 Slog.v(TAG, "Removing preferred activity since set changed " 4859 + pa.mPref.mComponent); 4860 } 4861 pir.removeFilter(pa); 4862 // Re-add the filter as a "last chosen" entry (!always) 4863 PreferredActivity lastChosen = new PreferredActivity( 4864 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4865 pir.addFilter(lastChosen); 4866 changed = true; 4867 return null; 4868 } 4869 4870 // Yay! Either the set matched or we're looking for the last chosen 4871 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4872 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4873 return ri; 4874 } 4875 } 4876 } finally { 4877 if (changed) { 4878 if (DEBUG_PREFERRED) { 4879 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4880 } 4881 scheduleWritePackageRestrictionsLocked(userId); 4882 } 4883 } 4884 } 4885 } 4886 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4887 return null; 4888 } 4889 4890 /* 4891 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4892 */ 4893 @Override 4894 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4895 int targetUserId) { 4896 mContext.enforceCallingOrSelfPermission( 4897 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4898 List<CrossProfileIntentFilter> matches = 4899 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4900 if (matches != null) { 4901 int size = matches.size(); 4902 for (int i = 0; i < size; i++) { 4903 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4904 } 4905 } 4906 if (hasWebURI(intent)) { 4907 // cross-profile app linking works only towards the parent. 4908 final UserInfo parent = getProfileParent(sourceUserId); 4909 synchronized(mPackages) { 4910 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4911 intent, resolvedType, 0, sourceUserId, parent.id); 4912 return xpDomainInfo != null; 4913 } 4914 } 4915 return false; 4916 } 4917 4918 private UserInfo getProfileParent(int userId) { 4919 final long identity = Binder.clearCallingIdentity(); 4920 try { 4921 return sUserManager.getProfileParent(userId); 4922 } finally { 4923 Binder.restoreCallingIdentity(identity); 4924 } 4925 } 4926 4927 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4928 String resolvedType, int userId) { 4929 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4930 if (resolver != null) { 4931 return resolver.queryIntent(intent, resolvedType, false, userId); 4932 } 4933 return null; 4934 } 4935 4936 @Override 4937 public List<ResolveInfo> queryIntentActivities(Intent intent, 4938 String resolvedType, int flags, int userId) { 4939 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4940 flags = updateFlagsForResolve(flags, userId, intent); 4941 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4942 ComponentName comp = intent.getComponent(); 4943 if (comp == null) { 4944 if (intent.getSelector() != null) { 4945 intent = intent.getSelector(); 4946 comp = intent.getComponent(); 4947 } 4948 } 4949 4950 if (comp != null) { 4951 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4952 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4953 if (ai != null) { 4954 final ResolveInfo ri = new ResolveInfo(); 4955 ri.activityInfo = ai; 4956 list.add(ri); 4957 } 4958 return list; 4959 } 4960 4961 // reader 4962 synchronized (mPackages) { 4963 final String pkgName = intent.getPackage(); 4964 if (pkgName == null) { 4965 List<CrossProfileIntentFilter> matchingFilters = 4966 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4967 // Check for results that need to skip the current profile. 4968 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4969 resolvedType, flags, userId); 4970 if (xpResolveInfo != null) { 4971 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4972 result.add(xpResolveInfo); 4973 return filterIfNotSystemUser(result, userId); 4974 } 4975 4976 // Check for results in the current profile. 4977 List<ResolveInfo> result = mActivities.queryIntent( 4978 intent, resolvedType, flags, userId); 4979 result = filterIfNotSystemUser(result, userId); 4980 4981 // Check for cross profile results. 4982 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 4983 xpResolveInfo = queryCrossProfileIntents( 4984 matchingFilters, intent, resolvedType, flags, userId, 4985 hasNonNegativePriorityResult); 4986 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4987 boolean isVisibleToUser = filterIfNotSystemUser( 4988 Collections.singletonList(xpResolveInfo), userId).size() > 0; 4989 if (isVisibleToUser) { 4990 result.add(xpResolveInfo); 4991 Collections.sort(result, mResolvePrioritySorter); 4992 } 4993 } 4994 if (hasWebURI(intent)) { 4995 CrossProfileDomainInfo xpDomainInfo = null; 4996 final UserInfo parent = getProfileParent(userId); 4997 if (parent != null) { 4998 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4999 flags, userId, parent.id); 5000 } 5001 if (xpDomainInfo != null) { 5002 if (xpResolveInfo != null) { 5003 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5004 // in the result. 5005 result.remove(xpResolveInfo); 5006 } 5007 if (result.size() == 0) { 5008 result.add(xpDomainInfo.resolveInfo); 5009 return result; 5010 } 5011 } else if (result.size() <= 1) { 5012 return result; 5013 } 5014 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5015 xpDomainInfo, userId); 5016 Collections.sort(result, mResolvePrioritySorter); 5017 } 5018 return result; 5019 } 5020 final PackageParser.Package pkg = mPackages.get(pkgName); 5021 if (pkg != null) { 5022 return filterIfNotSystemUser( 5023 mActivities.queryIntentForPackage( 5024 intent, resolvedType, flags, pkg.activities, userId), 5025 userId); 5026 } 5027 return new ArrayList<ResolveInfo>(); 5028 } 5029 } 5030 5031 private static class CrossProfileDomainInfo { 5032 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5033 ResolveInfo resolveInfo; 5034 /* Best domain verification status of the activities found in the other profile */ 5035 int bestDomainVerificationStatus; 5036 } 5037 5038 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5039 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5040 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5041 sourceUserId)) { 5042 return null; 5043 } 5044 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5045 resolvedType, flags, parentUserId); 5046 5047 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5048 return null; 5049 } 5050 CrossProfileDomainInfo result = null; 5051 int size = resultTargetUser.size(); 5052 for (int i = 0; i < size; i++) { 5053 ResolveInfo riTargetUser = resultTargetUser.get(i); 5054 // Intent filter verification is only for filters that specify a host. So don't return 5055 // those that handle all web uris. 5056 if (riTargetUser.handleAllWebDataURI) { 5057 continue; 5058 } 5059 String packageName = riTargetUser.activityInfo.packageName; 5060 PackageSetting ps = mSettings.mPackages.get(packageName); 5061 if (ps == null) { 5062 continue; 5063 } 5064 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5065 int status = (int)(verificationState >> 32); 5066 if (result == null) { 5067 result = new CrossProfileDomainInfo(); 5068 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5069 sourceUserId, parentUserId); 5070 result.bestDomainVerificationStatus = status; 5071 } else { 5072 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5073 result.bestDomainVerificationStatus); 5074 } 5075 } 5076 // Don't consider matches with status NEVER across profiles. 5077 if (result != null && result.bestDomainVerificationStatus 5078 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5079 return null; 5080 } 5081 return result; 5082 } 5083 5084 /** 5085 * Verification statuses are ordered from the worse to the best, except for 5086 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5087 */ 5088 private int bestDomainVerificationStatus(int status1, int status2) { 5089 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5090 return status2; 5091 } 5092 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5093 return status1; 5094 } 5095 return (int) MathUtils.max(status1, status2); 5096 } 5097 5098 private boolean isUserEnabled(int userId) { 5099 long callingId = Binder.clearCallingIdentity(); 5100 try { 5101 UserInfo userInfo = sUserManager.getUserInfo(userId); 5102 return userInfo != null && userInfo.isEnabled(); 5103 } finally { 5104 Binder.restoreCallingIdentity(callingId); 5105 } 5106 } 5107 5108 /** 5109 * Filter out activities with systemUserOnly flag set, when current user is not System. 5110 * 5111 * @return filtered list 5112 */ 5113 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5114 if (userId == UserHandle.USER_SYSTEM) { 5115 return resolveInfos; 5116 } 5117 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5118 ResolveInfo info = resolveInfos.get(i); 5119 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5120 resolveInfos.remove(i); 5121 } 5122 } 5123 return resolveInfos; 5124 } 5125 5126 /** 5127 * @param resolveInfos list of resolve infos in descending priority order 5128 * @return if the list contains a resolve info with non-negative priority 5129 */ 5130 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5131 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5132 } 5133 5134 private static boolean hasWebURI(Intent intent) { 5135 if (intent.getData() == null) { 5136 return false; 5137 } 5138 final String scheme = intent.getScheme(); 5139 if (TextUtils.isEmpty(scheme)) { 5140 return false; 5141 } 5142 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5143 } 5144 5145 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5146 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5147 int userId) { 5148 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5149 5150 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5151 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5152 candidates.size()); 5153 } 5154 5155 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5156 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5157 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5158 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5159 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5160 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5161 5162 synchronized (mPackages) { 5163 final int count = candidates.size(); 5164 // First, try to use linked apps. Partition the candidates into four lists: 5165 // one for the final results, one for the "do not use ever", one for "undefined status" 5166 // and finally one for "browser app type". 5167 for (int n=0; n<count; n++) { 5168 ResolveInfo info = candidates.get(n); 5169 String packageName = info.activityInfo.packageName; 5170 PackageSetting ps = mSettings.mPackages.get(packageName); 5171 if (ps != null) { 5172 // Add to the special match all list (Browser use case) 5173 if (info.handleAllWebDataURI) { 5174 matchAllList.add(info); 5175 continue; 5176 } 5177 // Try to get the status from User settings first 5178 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5179 int status = (int)(packedStatus >> 32); 5180 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5181 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5182 if (DEBUG_DOMAIN_VERIFICATION) { 5183 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5184 + " : linkgen=" + linkGeneration); 5185 } 5186 // Use link-enabled generation as preferredOrder, i.e. 5187 // prefer newly-enabled over earlier-enabled. 5188 info.preferredOrder = linkGeneration; 5189 alwaysList.add(info); 5190 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5191 if (DEBUG_DOMAIN_VERIFICATION) { 5192 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5193 } 5194 neverList.add(info); 5195 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5196 if (DEBUG_DOMAIN_VERIFICATION) { 5197 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5198 } 5199 alwaysAskList.add(info); 5200 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5201 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5202 if (DEBUG_DOMAIN_VERIFICATION) { 5203 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5204 } 5205 undefinedList.add(info); 5206 } 5207 } 5208 } 5209 5210 // We'll want to include browser possibilities in a few cases 5211 boolean includeBrowser = false; 5212 5213 // First try to add the "always" resolution(s) for the current user, if any 5214 if (alwaysList.size() > 0) { 5215 result.addAll(alwaysList); 5216 } else { 5217 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5218 result.addAll(undefinedList); 5219 // Maybe add one for the other profile. 5220 if (xpDomainInfo != null && ( 5221 xpDomainInfo.bestDomainVerificationStatus 5222 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5223 result.add(xpDomainInfo.resolveInfo); 5224 } 5225 includeBrowser = true; 5226 } 5227 5228 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5229 // If there were 'always' entries their preferred order has been set, so we also 5230 // back that off to make the alternatives equivalent 5231 if (alwaysAskList.size() > 0) { 5232 for (ResolveInfo i : result) { 5233 i.preferredOrder = 0; 5234 } 5235 result.addAll(alwaysAskList); 5236 includeBrowser = true; 5237 } 5238 5239 if (includeBrowser) { 5240 // Also add browsers (all of them or only the default one) 5241 if (DEBUG_DOMAIN_VERIFICATION) { 5242 Slog.v(TAG, " ...including browsers in candidate set"); 5243 } 5244 if ((matchFlags & MATCH_ALL) != 0) { 5245 result.addAll(matchAllList); 5246 } else { 5247 // Browser/generic handling case. If there's a default browser, go straight 5248 // to that (but only if there is no other higher-priority match). 5249 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5250 int maxMatchPrio = 0; 5251 ResolveInfo defaultBrowserMatch = null; 5252 final int numCandidates = matchAllList.size(); 5253 for (int n = 0; n < numCandidates; n++) { 5254 ResolveInfo info = matchAllList.get(n); 5255 // track the highest overall match priority... 5256 if (info.priority > maxMatchPrio) { 5257 maxMatchPrio = info.priority; 5258 } 5259 // ...and the highest-priority default browser match 5260 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5261 if (defaultBrowserMatch == null 5262 || (defaultBrowserMatch.priority < info.priority)) { 5263 if (debug) { 5264 Slog.v(TAG, "Considering default browser match " + info); 5265 } 5266 defaultBrowserMatch = info; 5267 } 5268 } 5269 } 5270 if (defaultBrowserMatch != null 5271 && defaultBrowserMatch.priority >= maxMatchPrio 5272 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5273 { 5274 if (debug) { 5275 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5276 } 5277 result.add(defaultBrowserMatch); 5278 } else { 5279 result.addAll(matchAllList); 5280 } 5281 } 5282 5283 // If there is nothing selected, add all candidates and remove the ones that the user 5284 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5285 if (result.size() == 0) { 5286 result.addAll(candidates); 5287 result.removeAll(neverList); 5288 } 5289 } 5290 } 5291 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5292 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5293 result.size()); 5294 for (ResolveInfo info : result) { 5295 Slog.v(TAG, " + " + info.activityInfo); 5296 } 5297 } 5298 return result; 5299 } 5300 5301 // Returns a packed value as a long: 5302 // 5303 // high 'int'-sized word: link status: undefined/ask/never/always. 5304 // low 'int'-sized word: relative priority among 'always' results. 5305 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5306 long result = ps.getDomainVerificationStatusForUser(userId); 5307 // if none available, get the master status 5308 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5309 if (ps.getIntentFilterVerificationInfo() != null) { 5310 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5311 } 5312 } 5313 return result; 5314 } 5315 5316 private ResolveInfo querySkipCurrentProfileIntents( 5317 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5318 int flags, int sourceUserId) { 5319 if (matchingFilters != null) { 5320 int size = matchingFilters.size(); 5321 for (int i = 0; i < size; i ++) { 5322 CrossProfileIntentFilter filter = matchingFilters.get(i); 5323 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5324 // Checking if there are activities in the target user that can handle the 5325 // intent. 5326 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5327 resolvedType, flags, sourceUserId); 5328 if (resolveInfo != null) { 5329 return resolveInfo; 5330 } 5331 } 5332 } 5333 } 5334 return null; 5335 } 5336 5337 // Return matching ResolveInfo in target user if any. 5338 private ResolveInfo queryCrossProfileIntents( 5339 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5340 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5341 if (matchingFilters != null) { 5342 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5343 // match the same intent. For performance reasons, it is better not to 5344 // run queryIntent twice for the same userId 5345 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5346 int size = matchingFilters.size(); 5347 for (int i = 0; i < size; i++) { 5348 CrossProfileIntentFilter filter = matchingFilters.get(i); 5349 int targetUserId = filter.getTargetUserId(); 5350 boolean skipCurrentProfile = 5351 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5352 boolean skipCurrentProfileIfNoMatchFound = 5353 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5354 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5355 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5356 // Checking if there are activities in the target user that can handle the 5357 // intent. 5358 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5359 resolvedType, flags, sourceUserId); 5360 if (resolveInfo != null) return resolveInfo; 5361 alreadyTriedUserIds.put(targetUserId, true); 5362 } 5363 } 5364 } 5365 return null; 5366 } 5367 5368 /** 5369 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5370 * will forward the intent to the filter's target user. 5371 * Otherwise, returns null. 5372 */ 5373 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5374 String resolvedType, int flags, int sourceUserId) { 5375 int targetUserId = filter.getTargetUserId(); 5376 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5377 resolvedType, flags, targetUserId); 5378 if (resultTargetUser != null && !resultTargetUser.isEmpty() 5379 && isUserEnabled(targetUserId)) { 5380 return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId); 5381 } 5382 return null; 5383 } 5384 5385 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5386 int sourceUserId, int targetUserId) { 5387 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5388 long ident = Binder.clearCallingIdentity(); 5389 boolean targetIsProfile; 5390 try { 5391 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5392 } finally { 5393 Binder.restoreCallingIdentity(ident); 5394 } 5395 String className; 5396 if (targetIsProfile) { 5397 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5398 } else { 5399 className = FORWARD_INTENT_TO_PARENT; 5400 } 5401 ComponentName forwardingActivityComponentName = new ComponentName( 5402 mAndroidApplication.packageName, className); 5403 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5404 sourceUserId); 5405 if (!targetIsProfile) { 5406 forwardingActivityInfo.showUserIcon = targetUserId; 5407 forwardingResolveInfo.noResourceId = true; 5408 } 5409 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5410 forwardingResolveInfo.priority = 0; 5411 forwardingResolveInfo.preferredOrder = 0; 5412 forwardingResolveInfo.match = 0; 5413 forwardingResolveInfo.isDefault = true; 5414 forwardingResolveInfo.filter = filter; 5415 forwardingResolveInfo.targetUserId = targetUserId; 5416 return forwardingResolveInfo; 5417 } 5418 5419 @Override 5420 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5421 Intent[] specifics, String[] specificTypes, Intent intent, 5422 String resolvedType, int flags, int userId) { 5423 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5424 flags = updateFlagsForResolve(flags, userId, intent); 5425 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 5426 false, "query intent activity options"); 5427 final String resultsAction = intent.getAction(); 5428 5429 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 5430 | PackageManager.GET_RESOLVED_FILTER, userId); 5431 5432 if (DEBUG_INTENT_MATCHING) { 5433 Log.v(TAG, "Query " + intent + ": " + results); 5434 } 5435 5436 int specificsPos = 0; 5437 int N; 5438 5439 // todo: note that the algorithm used here is O(N^2). This 5440 // isn't a problem in our current environment, but if we start running 5441 // into situations where we have more than 5 or 10 matches then this 5442 // should probably be changed to something smarter... 5443 5444 // First we go through and resolve each of the specific items 5445 // that were supplied, taking care of removing any corresponding 5446 // duplicate items in the generic resolve list. 5447 if (specifics != null) { 5448 for (int i=0; i<specifics.length; i++) { 5449 final Intent sintent = specifics[i]; 5450 if (sintent == null) { 5451 continue; 5452 } 5453 5454 if (DEBUG_INTENT_MATCHING) { 5455 Log.v(TAG, "Specific #" + i + ": " + sintent); 5456 } 5457 5458 String action = sintent.getAction(); 5459 if (resultsAction != null && resultsAction.equals(action)) { 5460 // If this action was explicitly requested, then don't 5461 // remove things that have it. 5462 action = null; 5463 } 5464 5465 ResolveInfo ri = null; 5466 ActivityInfo ai = null; 5467 5468 ComponentName comp = sintent.getComponent(); 5469 if (comp == null) { 5470 ri = resolveIntent( 5471 sintent, 5472 specificTypes != null ? specificTypes[i] : null, 5473 flags, userId); 5474 if (ri == null) { 5475 continue; 5476 } 5477 if (ri == mResolveInfo) { 5478 // ACK! Must do something better with this. 5479 } 5480 ai = ri.activityInfo; 5481 comp = new ComponentName(ai.applicationInfo.packageName, 5482 ai.name); 5483 } else { 5484 ai = getActivityInfo(comp, flags, userId); 5485 if (ai == null) { 5486 continue; 5487 } 5488 } 5489 5490 // Look for any generic query activities that are duplicates 5491 // of this specific one, and remove them from the results. 5492 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5493 N = results.size(); 5494 int j; 5495 for (j=specificsPos; j<N; j++) { 5496 ResolveInfo sri = results.get(j); 5497 if ((sri.activityInfo.name.equals(comp.getClassName()) 5498 && sri.activityInfo.applicationInfo.packageName.equals( 5499 comp.getPackageName())) 5500 || (action != null && sri.filter.matchAction(action))) { 5501 results.remove(j); 5502 if (DEBUG_INTENT_MATCHING) Log.v( 5503 TAG, "Removing duplicate item from " + j 5504 + " due to specific " + specificsPos); 5505 if (ri == null) { 5506 ri = sri; 5507 } 5508 j--; 5509 N--; 5510 } 5511 } 5512 5513 // Add this specific item to its proper place. 5514 if (ri == null) { 5515 ri = new ResolveInfo(); 5516 ri.activityInfo = ai; 5517 } 5518 results.add(specificsPos, ri); 5519 ri.specificIndex = i; 5520 specificsPos++; 5521 } 5522 } 5523 5524 // Now we go through the remaining generic results and remove any 5525 // duplicate actions that are found here. 5526 N = results.size(); 5527 for (int i=specificsPos; i<N-1; i++) { 5528 final ResolveInfo rii = results.get(i); 5529 if (rii.filter == null) { 5530 continue; 5531 } 5532 5533 // Iterate over all of the actions of this result's intent 5534 // filter... typically this should be just one. 5535 final Iterator<String> it = rii.filter.actionsIterator(); 5536 if (it == null) { 5537 continue; 5538 } 5539 while (it.hasNext()) { 5540 final String action = it.next(); 5541 if (resultsAction != null && resultsAction.equals(action)) { 5542 // If this action was explicitly requested, then don't 5543 // remove things that have it. 5544 continue; 5545 } 5546 for (int j=i+1; j<N; j++) { 5547 final ResolveInfo rij = results.get(j); 5548 if (rij.filter != null && rij.filter.hasAction(action)) { 5549 results.remove(j); 5550 if (DEBUG_INTENT_MATCHING) Log.v( 5551 TAG, "Removing duplicate item from " + j 5552 + " due to action " + action + " at " + i); 5553 j--; 5554 N--; 5555 } 5556 } 5557 } 5558 5559 // If the caller didn't request filter information, drop it now 5560 // so we don't have to marshall/unmarshall it. 5561 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5562 rii.filter = null; 5563 } 5564 } 5565 5566 // Filter out the caller activity if so requested. 5567 if (caller != null) { 5568 N = results.size(); 5569 for (int i=0; i<N; i++) { 5570 ActivityInfo ainfo = results.get(i).activityInfo; 5571 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5572 && caller.getClassName().equals(ainfo.name)) { 5573 results.remove(i); 5574 break; 5575 } 5576 } 5577 } 5578 5579 // If the caller didn't request filter information, 5580 // drop them now so we don't have to 5581 // marshall/unmarshall it. 5582 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5583 N = results.size(); 5584 for (int i=0; i<N; i++) { 5585 results.get(i).filter = null; 5586 } 5587 } 5588 5589 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5590 return results; 5591 } 5592 5593 @Override 5594 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5595 int userId) { 5596 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5597 flags = updateFlagsForResolve(flags, userId, intent); 5598 ComponentName comp = intent.getComponent(); 5599 if (comp == null) { 5600 if (intent.getSelector() != null) { 5601 intent = intent.getSelector(); 5602 comp = intent.getComponent(); 5603 } 5604 } 5605 if (comp != null) { 5606 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5607 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5608 if (ai != null) { 5609 ResolveInfo ri = new ResolveInfo(); 5610 ri.activityInfo = ai; 5611 list.add(ri); 5612 } 5613 return list; 5614 } 5615 5616 // reader 5617 synchronized (mPackages) { 5618 String pkgName = intent.getPackage(); 5619 if (pkgName == null) { 5620 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5621 } 5622 final PackageParser.Package pkg = mPackages.get(pkgName); 5623 if (pkg != null) { 5624 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5625 userId); 5626 } 5627 return null; 5628 } 5629 } 5630 5631 @Override 5632 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5633 if (!sUserManager.exists(userId)) return null; 5634 flags = updateFlagsForResolve(flags, userId, intent); 5635 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5636 if (query != null) { 5637 if (query.size() >= 1) { 5638 // If there is more than one service with the same priority, 5639 // just arbitrarily pick the first one. 5640 return query.get(0); 5641 } 5642 } 5643 return null; 5644 } 5645 5646 @Override 5647 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5648 int userId) { 5649 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5650 flags = updateFlagsForResolve(flags, userId, intent); 5651 ComponentName comp = intent.getComponent(); 5652 if (comp == null) { 5653 if (intent.getSelector() != null) { 5654 intent = intent.getSelector(); 5655 comp = intent.getComponent(); 5656 } 5657 } 5658 if (comp != null) { 5659 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5660 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5661 if (si != null) { 5662 final ResolveInfo ri = new ResolveInfo(); 5663 ri.serviceInfo = si; 5664 list.add(ri); 5665 } 5666 return list; 5667 } 5668 5669 // reader 5670 synchronized (mPackages) { 5671 String pkgName = intent.getPackage(); 5672 if (pkgName == null) { 5673 return mServices.queryIntent(intent, resolvedType, flags, userId); 5674 } 5675 final PackageParser.Package pkg = mPackages.get(pkgName); 5676 if (pkg != null) { 5677 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5678 userId); 5679 } 5680 return null; 5681 } 5682 } 5683 5684 @Override 5685 public List<ResolveInfo> queryIntentContentProviders( 5686 Intent intent, String resolvedType, int flags, int userId) { 5687 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5688 flags = updateFlagsForResolve(flags, userId, intent); 5689 ComponentName comp = intent.getComponent(); 5690 if (comp == null) { 5691 if (intent.getSelector() != null) { 5692 intent = intent.getSelector(); 5693 comp = intent.getComponent(); 5694 } 5695 } 5696 if (comp != null) { 5697 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5698 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5699 if (pi != null) { 5700 final ResolveInfo ri = new ResolveInfo(); 5701 ri.providerInfo = pi; 5702 list.add(ri); 5703 } 5704 return list; 5705 } 5706 5707 // reader 5708 synchronized (mPackages) { 5709 String pkgName = intent.getPackage(); 5710 if (pkgName == null) { 5711 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5712 } 5713 final PackageParser.Package pkg = mPackages.get(pkgName); 5714 if (pkg != null) { 5715 return mProviders.queryIntentForPackage( 5716 intent, resolvedType, flags, pkg.providers, userId); 5717 } 5718 return null; 5719 } 5720 } 5721 5722 @Override 5723 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5724 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5725 flags = updateFlagsForPackage(flags, userId, null); 5726 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5727 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5728 5729 // writer 5730 synchronized (mPackages) { 5731 ArrayList<PackageInfo> list; 5732 if (listUninstalled) { 5733 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5734 for (PackageSetting ps : mSettings.mPackages.values()) { 5735 PackageInfo pi; 5736 if (ps.pkg != null) { 5737 pi = generatePackageInfo(ps.pkg, flags, userId); 5738 } else { 5739 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5740 } 5741 if (pi != null) { 5742 list.add(pi); 5743 } 5744 } 5745 } else { 5746 list = new ArrayList<PackageInfo>(mPackages.size()); 5747 for (PackageParser.Package p : mPackages.values()) { 5748 PackageInfo pi = generatePackageInfo(p, flags, userId); 5749 if (pi != null) { 5750 list.add(pi); 5751 } 5752 } 5753 } 5754 5755 return new ParceledListSlice<PackageInfo>(list); 5756 } 5757 } 5758 5759 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5760 String[] permissions, boolean[] tmp, int flags, int userId) { 5761 int numMatch = 0; 5762 final PermissionsState permissionsState = ps.getPermissionsState(); 5763 for (int i=0; i<permissions.length; i++) { 5764 final String permission = permissions[i]; 5765 if (permissionsState.hasPermission(permission, userId)) { 5766 tmp[i] = true; 5767 numMatch++; 5768 } else { 5769 tmp[i] = false; 5770 } 5771 } 5772 if (numMatch == 0) { 5773 return; 5774 } 5775 PackageInfo pi; 5776 if (ps.pkg != null) { 5777 pi = generatePackageInfo(ps.pkg, flags, userId); 5778 } else { 5779 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5780 } 5781 // The above might return null in cases of uninstalled apps or install-state 5782 // skew across users/profiles. 5783 if (pi != null) { 5784 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5785 if (numMatch == permissions.length) { 5786 pi.requestedPermissions = permissions; 5787 } else { 5788 pi.requestedPermissions = new String[numMatch]; 5789 numMatch = 0; 5790 for (int i=0; i<permissions.length; i++) { 5791 if (tmp[i]) { 5792 pi.requestedPermissions[numMatch] = permissions[i]; 5793 numMatch++; 5794 } 5795 } 5796 } 5797 } 5798 list.add(pi); 5799 } 5800 } 5801 5802 @Override 5803 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5804 String[] permissions, int flags, int userId) { 5805 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5806 flags = updateFlagsForPackage(flags, userId, permissions); 5807 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5808 5809 // writer 5810 synchronized (mPackages) { 5811 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5812 boolean[] tmpBools = new boolean[permissions.length]; 5813 if (listUninstalled) { 5814 for (PackageSetting ps : mSettings.mPackages.values()) { 5815 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5816 } 5817 } else { 5818 for (PackageParser.Package pkg : mPackages.values()) { 5819 PackageSetting ps = (PackageSetting)pkg.mExtras; 5820 if (ps != null) { 5821 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5822 userId); 5823 } 5824 } 5825 } 5826 5827 return new ParceledListSlice<PackageInfo>(list); 5828 } 5829 } 5830 5831 @Override 5832 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5833 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5834 flags = updateFlagsForApplication(flags, userId, null); 5835 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5836 5837 // writer 5838 synchronized (mPackages) { 5839 ArrayList<ApplicationInfo> list; 5840 if (listUninstalled) { 5841 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5842 for (PackageSetting ps : mSettings.mPackages.values()) { 5843 ApplicationInfo ai; 5844 if (ps.pkg != null) { 5845 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5846 ps.readUserState(userId), userId); 5847 } else { 5848 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5849 } 5850 if (ai != null) { 5851 list.add(ai); 5852 } 5853 } 5854 } else { 5855 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5856 for (PackageParser.Package p : mPackages.values()) { 5857 if (p.mExtras != null) { 5858 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5859 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5860 if (ai != null) { 5861 list.add(ai); 5862 } 5863 } 5864 } 5865 } 5866 5867 return new ParceledListSlice<ApplicationInfo>(list); 5868 } 5869 } 5870 5871 @Override 5872 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 5873 if (DISABLE_EPHEMERAL_APPS) { 5874 return null; 5875 } 5876 5877 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 5878 "getEphemeralApplications"); 5879 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5880 "getEphemeralApplications"); 5881 synchronized (mPackages) { 5882 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 5883 .getEphemeralApplicationsLPw(userId); 5884 if (ephemeralApps != null) { 5885 return new ParceledListSlice<>(ephemeralApps); 5886 } 5887 } 5888 return null; 5889 } 5890 5891 @Override 5892 public boolean isEphemeralApplication(String packageName, int userId) { 5893 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5894 "isEphemeral"); 5895 if (DISABLE_EPHEMERAL_APPS) { 5896 return false; 5897 } 5898 5899 if (!isCallerSameApp(packageName)) { 5900 return false; 5901 } 5902 synchronized (mPackages) { 5903 PackageParser.Package pkg = mPackages.get(packageName); 5904 if (pkg != null) { 5905 return pkg.applicationInfo.isEphemeralApp(); 5906 } 5907 } 5908 return false; 5909 } 5910 5911 @Override 5912 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 5913 if (DISABLE_EPHEMERAL_APPS) { 5914 return null; 5915 } 5916 5917 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5918 "getCookie"); 5919 if (!isCallerSameApp(packageName)) { 5920 return null; 5921 } 5922 synchronized (mPackages) { 5923 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 5924 packageName, userId); 5925 } 5926 } 5927 5928 @Override 5929 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 5930 if (DISABLE_EPHEMERAL_APPS) { 5931 return true; 5932 } 5933 5934 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5935 "setCookie"); 5936 if (!isCallerSameApp(packageName)) { 5937 return false; 5938 } 5939 synchronized (mPackages) { 5940 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 5941 packageName, cookie, userId); 5942 } 5943 } 5944 5945 @Override 5946 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 5947 if (DISABLE_EPHEMERAL_APPS) { 5948 return null; 5949 } 5950 5951 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 5952 "getEphemeralApplicationIcon"); 5953 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5954 "getEphemeralApplicationIcon"); 5955 synchronized (mPackages) { 5956 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 5957 packageName, userId); 5958 } 5959 } 5960 5961 private boolean isCallerSameApp(String packageName) { 5962 PackageParser.Package pkg = mPackages.get(packageName); 5963 return pkg != null 5964 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 5965 } 5966 5967 public List<ApplicationInfo> getPersistentApplications(int flags) { 5968 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5969 5970 // reader 5971 synchronized (mPackages) { 5972 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5973 final int userId = UserHandle.getCallingUserId(); 5974 while (i.hasNext()) { 5975 final PackageParser.Package p = i.next(); 5976 if (p.applicationInfo != null 5977 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5978 && (!mSafeMode || isSystemApp(p))) { 5979 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5980 if (ps != null) { 5981 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5982 ps.readUserState(userId), userId); 5983 if (ai != null) { 5984 finalList.add(ai); 5985 } 5986 } 5987 } 5988 } 5989 } 5990 5991 return finalList; 5992 } 5993 5994 @Override 5995 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5996 if (!sUserManager.exists(userId)) return null; 5997 flags = updateFlagsForComponent(flags, userId, name); 5998 // reader 5999 synchronized (mPackages) { 6000 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6001 PackageSetting ps = provider != null 6002 ? mSettings.mPackages.get(provider.owner.packageName) 6003 : null; 6004 return ps != null 6005 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6006 ? PackageParser.generateProviderInfo(provider, flags, 6007 ps.readUserState(userId), userId) 6008 : null; 6009 } 6010 } 6011 6012 /** 6013 * @deprecated 6014 */ 6015 @Deprecated 6016 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6017 // reader 6018 synchronized (mPackages) { 6019 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6020 .entrySet().iterator(); 6021 final int userId = UserHandle.getCallingUserId(); 6022 while (i.hasNext()) { 6023 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6024 PackageParser.Provider p = entry.getValue(); 6025 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6026 6027 if (ps != null && p.syncable 6028 && (!mSafeMode || (p.info.applicationInfo.flags 6029 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6030 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6031 ps.readUserState(userId), userId); 6032 if (info != null) { 6033 outNames.add(entry.getKey()); 6034 outInfo.add(info); 6035 } 6036 } 6037 } 6038 } 6039 } 6040 6041 @Override 6042 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6043 int uid, int flags) { 6044 final int userId = processName != null ? UserHandle.getUserId(uid) 6045 : UserHandle.getCallingUserId(); 6046 if (!sUserManager.exists(userId)) return null; 6047 flags = updateFlagsForComponent(flags, userId, processName); 6048 6049 ArrayList<ProviderInfo> finalList = null; 6050 // reader 6051 synchronized (mPackages) { 6052 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6053 while (i.hasNext()) { 6054 final PackageParser.Provider p = i.next(); 6055 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6056 if (ps != null && p.info.authority != null 6057 && (processName == null 6058 || (p.info.processName.equals(processName) 6059 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6060 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6061 if (finalList == null) { 6062 finalList = new ArrayList<ProviderInfo>(3); 6063 } 6064 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6065 ps.readUserState(userId), userId); 6066 if (info != null) { 6067 finalList.add(info); 6068 } 6069 } 6070 } 6071 } 6072 6073 if (finalList != null) { 6074 Collections.sort(finalList, mProviderInitOrderSorter); 6075 return new ParceledListSlice<ProviderInfo>(finalList); 6076 } 6077 6078 return null; 6079 } 6080 6081 @Override 6082 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6083 // reader 6084 synchronized (mPackages) { 6085 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6086 return PackageParser.generateInstrumentationInfo(i, flags); 6087 } 6088 } 6089 6090 @Override 6091 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 6092 int flags) { 6093 ArrayList<InstrumentationInfo> finalList = 6094 new ArrayList<InstrumentationInfo>(); 6095 6096 // reader 6097 synchronized (mPackages) { 6098 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6099 while (i.hasNext()) { 6100 final PackageParser.Instrumentation p = i.next(); 6101 if (targetPackage == null 6102 || targetPackage.equals(p.info.targetPackage)) { 6103 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6104 flags); 6105 if (ii != null) { 6106 finalList.add(ii); 6107 } 6108 } 6109 } 6110 } 6111 6112 return finalList; 6113 } 6114 6115 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6116 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6117 if (overlays == null) { 6118 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6119 return; 6120 } 6121 for (PackageParser.Package opkg : overlays.values()) { 6122 // Not much to do if idmap fails: we already logged the error 6123 // and we certainly don't want to abort installation of pkg simply 6124 // because an overlay didn't fit properly. For these reasons, 6125 // ignore the return value of createIdmapForPackagePairLI. 6126 createIdmapForPackagePairLI(pkg, opkg); 6127 } 6128 } 6129 6130 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6131 PackageParser.Package opkg) { 6132 if (!opkg.mTrustedOverlay) { 6133 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6134 opkg.baseCodePath + ": overlay not trusted"); 6135 return false; 6136 } 6137 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6138 if (overlaySet == null) { 6139 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6140 opkg.baseCodePath + " but target package has no known overlays"); 6141 return false; 6142 } 6143 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6144 // TODO: generate idmap for split APKs 6145 try { 6146 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6147 } catch (InstallerException e) { 6148 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6149 + opkg.baseCodePath); 6150 return false; 6151 } 6152 PackageParser.Package[] overlayArray = 6153 overlaySet.values().toArray(new PackageParser.Package[0]); 6154 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6155 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6156 return p1.mOverlayPriority - p2.mOverlayPriority; 6157 } 6158 }; 6159 Arrays.sort(overlayArray, cmp); 6160 6161 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6162 int i = 0; 6163 for (PackageParser.Package p : overlayArray) { 6164 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6165 } 6166 return true; 6167 } 6168 6169 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6170 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6171 try { 6172 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6173 } finally { 6174 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6175 } 6176 } 6177 6178 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6179 final File[] files = dir.listFiles(); 6180 if (ArrayUtils.isEmpty(files)) { 6181 Log.d(TAG, "No files in app dir " + dir); 6182 return; 6183 } 6184 6185 if (DEBUG_PACKAGE_SCANNING) { 6186 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6187 + " flags=0x" + Integer.toHexString(parseFlags)); 6188 } 6189 6190 for (File file : files) { 6191 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6192 && !PackageInstallerService.isStageName(file.getName()); 6193 if (!isPackage) { 6194 // Ignore entries which are not packages 6195 continue; 6196 } 6197 try { 6198 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6199 scanFlags, currentTime, null); 6200 } catch (PackageManagerException e) { 6201 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6202 6203 // Delete invalid userdata apps 6204 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6205 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6206 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6207 removeCodePathLI(file); 6208 } 6209 } 6210 } 6211 } 6212 6213 private static File getSettingsProblemFile() { 6214 File dataDir = Environment.getDataDirectory(); 6215 File systemDir = new File(dataDir, "system"); 6216 File fname = new File(systemDir, "uiderrors.txt"); 6217 return fname; 6218 } 6219 6220 static void reportSettingsProblem(int priority, String msg) { 6221 logCriticalInfo(priority, msg); 6222 } 6223 6224 static void logCriticalInfo(int priority, String msg) { 6225 Slog.println(priority, TAG, msg); 6226 EventLogTags.writePmCriticalInfo(msg); 6227 try { 6228 File fname = getSettingsProblemFile(); 6229 FileOutputStream out = new FileOutputStream(fname, true); 6230 PrintWriter pw = new FastPrintWriter(out); 6231 SimpleDateFormat formatter = new SimpleDateFormat(); 6232 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6233 pw.println(dateString + ": " + msg); 6234 pw.close(); 6235 FileUtils.setPermissions( 6236 fname.toString(), 6237 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6238 -1, -1); 6239 } catch (java.io.IOException e) { 6240 } 6241 } 6242 6243 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 6244 PackageParser.Package pkg, File srcFile, int parseFlags) 6245 throws PackageManagerException { 6246 if (ps != null 6247 && ps.codePath.equals(srcFile) 6248 && ps.timeStamp == srcFile.lastModified() 6249 && !isCompatSignatureUpdateNeeded(pkg) 6250 && !isRecoverSignatureUpdateNeeded(pkg)) { 6251 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6252 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6253 ArraySet<PublicKey> signingKs; 6254 synchronized (mPackages) { 6255 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6256 } 6257 if (ps.signatures.mSignatures != null 6258 && ps.signatures.mSignatures.length != 0 6259 && signingKs != null) { 6260 // Optimization: reuse the existing cached certificates 6261 // if the package appears to be unchanged. 6262 pkg.mSignatures = ps.signatures.mSignatures; 6263 pkg.mSigningKeys = signingKs; 6264 return; 6265 } 6266 6267 Slog.w(TAG, "PackageSetting for " + ps.name 6268 + " is missing signatures. Collecting certs again to recover them."); 6269 } else { 6270 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6271 } 6272 6273 try { 6274 pp.collectCertificates(pkg, parseFlags); 6275 } catch (PackageParserException e) { 6276 throw PackageManagerException.from(e); 6277 } 6278 } 6279 6280 /** 6281 * Traces a package scan. 6282 * @see #scanPackageLI(File, int, int, long, UserHandle) 6283 */ 6284 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6285 long currentTime, UserHandle user) throws PackageManagerException { 6286 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6287 try { 6288 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6289 } finally { 6290 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6291 } 6292 } 6293 6294 /** 6295 * Scans a package and returns the newly parsed package. 6296 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6297 */ 6298 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6299 long currentTime, UserHandle user) throws PackageManagerException { 6300 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6301 parseFlags |= mDefParseFlags; 6302 PackageParser pp = new PackageParser(); 6303 pp.setSeparateProcesses(mSeparateProcesses); 6304 pp.setOnlyCoreApps(mOnlyCore); 6305 pp.setDisplayMetrics(mMetrics); 6306 6307 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6308 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6309 } 6310 6311 final PackageParser.Package pkg; 6312 try { 6313 pkg = pp.parsePackage(scanFile, parseFlags); 6314 } catch (PackageParserException e) { 6315 throw PackageManagerException.from(e); 6316 } 6317 6318 PackageSetting ps = null; 6319 PackageSetting updatedPkg; 6320 // reader 6321 synchronized (mPackages) { 6322 // Look to see if we already know about this package. 6323 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6324 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6325 // This package has been renamed to its original name. Let's 6326 // use that. 6327 ps = mSettings.peekPackageLPr(oldName); 6328 } 6329 // If there was no original package, see one for the real package name. 6330 if (ps == null) { 6331 ps = mSettings.peekPackageLPr(pkg.packageName); 6332 } 6333 // Check to see if this package could be hiding/updating a system 6334 // package. Must look for it either under the original or real 6335 // package name depending on our state. 6336 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6337 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6338 } 6339 boolean updatedPkgBetter = false; 6340 // First check if this is a system package that may involve an update 6341 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6342 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6343 // it needs to drop FLAG_PRIVILEGED. 6344 if (locationIsPrivileged(scanFile)) { 6345 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6346 } else { 6347 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6348 } 6349 6350 if (ps != null && !ps.codePath.equals(scanFile)) { 6351 // The path has changed from what was last scanned... check the 6352 // version of the new path against what we have stored to determine 6353 // what to do. 6354 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6355 if (pkg.mVersionCode <= ps.versionCode) { 6356 // The system package has been updated and the code path does not match 6357 // Ignore entry. Skip it. 6358 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6359 + " ignored: updated version " + ps.versionCode 6360 + " better than this " + pkg.mVersionCode); 6361 if (!updatedPkg.codePath.equals(scanFile)) { 6362 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6363 + ps.name + " changing from " + updatedPkg.codePathString 6364 + " to " + scanFile); 6365 updatedPkg.codePath = scanFile; 6366 updatedPkg.codePathString = scanFile.toString(); 6367 updatedPkg.resourcePath = scanFile; 6368 updatedPkg.resourcePathString = scanFile.toString(); 6369 } 6370 updatedPkg.pkg = pkg; 6371 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6372 "Package " + ps.name + " at " + scanFile 6373 + " ignored: updated version " + ps.versionCode 6374 + " better than this " + pkg.mVersionCode); 6375 } else { 6376 // The current app on the system partition is better than 6377 // what we have updated to on the data partition; switch 6378 // back to the system partition version. 6379 // At this point, its safely assumed that package installation for 6380 // apps in system partition will go through. If not there won't be a working 6381 // version of the app 6382 // writer 6383 synchronized (mPackages) { 6384 // Just remove the loaded entries from package lists. 6385 mPackages.remove(ps.name); 6386 } 6387 6388 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6389 + " reverting from " + ps.codePathString 6390 + ": new version " + pkg.mVersionCode 6391 + " better than installed " + ps.versionCode); 6392 6393 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6394 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6395 synchronized (mInstallLock) { 6396 args.cleanUpResourcesLI(); 6397 } 6398 synchronized (mPackages) { 6399 mSettings.enableSystemPackageLPw(ps.name); 6400 } 6401 updatedPkgBetter = true; 6402 } 6403 } 6404 } 6405 6406 if (updatedPkg != null) { 6407 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6408 // initially 6409 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6410 6411 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6412 // flag set initially 6413 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6414 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6415 } 6416 } 6417 6418 // Verify certificates against what was last scanned 6419 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 6420 6421 /* 6422 * A new system app appeared, but we already had a non-system one of the 6423 * same name installed earlier. 6424 */ 6425 boolean shouldHideSystemApp = false; 6426 if (updatedPkg == null && ps != null 6427 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6428 /* 6429 * Check to make sure the signatures match first. If they don't, 6430 * wipe the installed application and its data. 6431 */ 6432 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6433 != PackageManager.SIGNATURE_MATCH) { 6434 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6435 + " signatures don't match existing userdata copy; removing"); 6436 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 6437 ps = null; 6438 } else { 6439 /* 6440 * If the newly-added system app is an older version than the 6441 * already installed version, hide it. It will be scanned later 6442 * and re-added like an update. 6443 */ 6444 if (pkg.mVersionCode <= ps.versionCode) { 6445 shouldHideSystemApp = true; 6446 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6447 + " but new version " + pkg.mVersionCode + " better than installed " 6448 + ps.versionCode + "; hiding system"); 6449 } else { 6450 /* 6451 * The newly found system app is a newer version that the 6452 * one previously installed. Simply remove the 6453 * already-installed application and replace it with our own 6454 * while keeping the application data. 6455 */ 6456 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6457 + " reverting from " + ps.codePathString + ": new version " 6458 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6459 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6460 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6461 synchronized (mInstallLock) { 6462 args.cleanUpResourcesLI(); 6463 } 6464 } 6465 } 6466 } 6467 6468 // The apk is forward locked (not public) if its code and resources 6469 // are kept in different files. (except for app in either system or 6470 // vendor path). 6471 // TODO grab this value from PackageSettings 6472 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6473 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6474 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6475 } 6476 } 6477 6478 // TODO: extend to support forward-locked splits 6479 String resourcePath = null; 6480 String baseResourcePath = null; 6481 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6482 if (ps != null && ps.resourcePathString != null) { 6483 resourcePath = ps.resourcePathString; 6484 baseResourcePath = ps.resourcePathString; 6485 } else { 6486 // Should not happen at all. Just log an error. 6487 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6488 } 6489 } else { 6490 resourcePath = pkg.codePath; 6491 baseResourcePath = pkg.baseCodePath; 6492 } 6493 6494 // Set application objects path explicitly. 6495 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 6496 pkg.applicationInfo.setCodePath(pkg.codePath); 6497 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 6498 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 6499 pkg.applicationInfo.setResourcePath(resourcePath); 6500 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 6501 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 6502 6503 // Note that we invoke the following method only if we are about to unpack an application 6504 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6505 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6506 6507 /* 6508 * If the system app should be overridden by a previously installed 6509 * data, hide the system app now and let the /data/app scan pick it up 6510 * again. 6511 */ 6512 if (shouldHideSystemApp) { 6513 synchronized (mPackages) { 6514 mSettings.disableSystemPackageLPw(pkg.packageName); 6515 } 6516 } 6517 6518 return scannedPkg; 6519 } 6520 6521 private static String fixProcessName(String defProcessName, 6522 String processName, int uid) { 6523 if (processName == null) { 6524 return defProcessName; 6525 } 6526 return processName; 6527 } 6528 6529 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6530 throws PackageManagerException { 6531 if (pkgSetting.signatures.mSignatures != null) { 6532 // Already existing package. Make sure signatures match 6533 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6534 == PackageManager.SIGNATURE_MATCH; 6535 if (!match) { 6536 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6537 == PackageManager.SIGNATURE_MATCH; 6538 } 6539 if (!match) { 6540 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6541 == PackageManager.SIGNATURE_MATCH; 6542 } 6543 if (!match) { 6544 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6545 + pkg.packageName + " signatures do not match the " 6546 + "previously installed version; ignoring!"); 6547 } 6548 } 6549 6550 // Check for shared user signatures 6551 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6552 // Already existing package. Make sure signatures match 6553 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6554 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6555 if (!match) { 6556 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6557 == PackageManager.SIGNATURE_MATCH; 6558 } 6559 if (!match) { 6560 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6561 == PackageManager.SIGNATURE_MATCH; 6562 } 6563 if (!match) { 6564 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6565 "Package " + pkg.packageName 6566 + " has no signatures that match those in shared user " 6567 + pkgSetting.sharedUser.name + "; ignoring!"); 6568 } 6569 } 6570 } 6571 6572 /** 6573 * Enforces that only the system UID or root's UID can call a method exposed 6574 * via Binder. 6575 * 6576 * @param message used as message if SecurityException is thrown 6577 * @throws SecurityException if the caller is not system or root 6578 */ 6579 private static final void enforceSystemOrRoot(String message) { 6580 final int uid = Binder.getCallingUid(); 6581 if (uid != Process.SYSTEM_UID && uid != 0) { 6582 throw new SecurityException(message); 6583 } 6584 } 6585 6586 @Override 6587 public void performFstrimIfNeeded() { 6588 enforceSystemOrRoot("Only the system can request fstrim"); 6589 6590 // Before everything else, see whether we need to fstrim. 6591 try { 6592 IMountService ms = PackageHelper.getMountService(); 6593 if (ms != null) { 6594 final boolean isUpgrade = isUpgrade(); 6595 boolean doTrim = isUpgrade; 6596 if (doTrim) { 6597 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6598 } else { 6599 final long interval = android.provider.Settings.Global.getLong( 6600 mContext.getContentResolver(), 6601 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6602 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6603 if (interval > 0) { 6604 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6605 if (timeSinceLast > interval) { 6606 doTrim = true; 6607 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6608 + "; running immediately"); 6609 } 6610 } 6611 } 6612 if (doTrim) { 6613 if (!isFirstBoot()) { 6614 try { 6615 ActivityManagerNative.getDefault().showBootMessage( 6616 mContext.getResources().getString( 6617 R.string.android_upgrading_fstrim), true); 6618 } catch (RemoteException e) { 6619 } 6620 } 6621 ms.runMaintenance(); 6622 } 6623 } else { 6624 Slog.e(TAG, "Mount service unavailable!"); 6625 } 6626 } catch (RemoteException e) { 6627 // Can't happen; MountService is local 6628 } 6629 } 6630 6631 @Override 6632 public void extractPackagesIfNeeded() { 6633 enforceSystemOrRoot("Only the system can request package extraction"); 6634 6635 // Extract pacakges only if profile-guided compilation is enabled because 6636 // otherwise BackgroundDexOptService will not dexopt them later. 6637 if (mUseJitProfiles) { 6638 ArraySet<String> pkgs = getOptimizablePackages(); 6639 if (pkgs != null) { 6640 for (String pkg : pkgs) { 6641 performDexOpt(pkg, null /* instructionSet */, false /* useProfiles */, 6642 true /* extractOnly */); 6643 } 6644 } 6645 } 6646 } 6647 6648 private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) { 6649 List<ResolveInfo> ris = null; 6650 try { 6651 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6652 intent, null, 0, userId); 6653 } catch (RemoteException e) { 6654 } 6655 ArraySet<String> pkgNames = new ArraySet<String>(); 6656 if (ris != null) { 6657 for (ResolveInfo ri : ris) { 6658 pkgNames.add(ri.activityInfo.packageName); 6659 } 6660 } 6661 return pkgNames; 6662 } 6663 6664 @Override 6665 public void notifyPackageUse(String packageName) { 6666 synchronized (mPackages) { 6667 PackageParser.Package p = mPackages.get(packageName); 6668 if (p == null) { 6669 return; 6670 } 6671 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6672 } 6673 } 6674 6675 // TODO: this is not used nor needed. Delete it. 6676 @Override 6677 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6678 return performDexOptTraced(packageName, instructionSet, false /* useProfiles */, 6679 false /* extractOnly */); 6680 } 6681 6682 public boolean performDexOpt(String packageName, String instructionSet, boolean useProfiles, 6683 boolean extractOnly) { 6684 return performDexOptTraced(packageName, instructionSet, useProfiles, extractOnly); 6685 } 6686 6687 private boolean performDexOptTraced(String packageName, String instructionSet, 6688 boolean useProfiles, boolean extractOnly) { 6689 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6690 try { 6691 return performDexOptInternal(packageName, instructionSet, useProfiles, extractOnly); 6692 } finally { 6693 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6694 } 6695 } 6696 6697 private boolean performDexOptInternal(String packageName, String instructionSet, 6698 boolean useProfiles, boolean extractOnly) { 6699 PackageParser.Package p; 6700 final String targetInstructionSet; 6701 synchronized (mPackages) { 6702 p = mPackages.get(packageName); 6703 if (p == null) { 6704 return false; 6705 } 6706 mPackageUsage.write(false); 6707 6708 targetInstructionSet = instructionSet != null ? instructionSet : 6709 getPrimaryInstructionSet(p.applicationInfo); 6710 if (!useProfiles && p.mDexOptPerformed.contains(targetInstructionSet)) { 6711 // Skip only if we do not use profiles since they might trigger a recompilation. 6712 return false; 6713 } 6714 } 6715 long callingId = Binder.clearCallingIdentity(); 6716 try { 6717 synchronized (mInstallLock) { 6718 final String[] instructionSets = new String[] { targetInstructionSet }; 6719 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6720 true /* inclDependencies */, p.volumeUuid, useProfiles, extractOnly); 6721 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6722 } 6723 } finally { 6724 Binder.restoreCallingIdentity(callingId); 6725 } 6726 } 6727 6728 public ArraySet<String> getOptimizablePackages() { 6729 ArraySet<String> pkgs = new ArraySet<String>(); 6730 synchronized (mPackages) { 6731 for (PackageParser.Package p : mPackages.values()) { 6732 if (PackageDexOptimizer.canOptimizePackage(p)) { 6733 pkgs.add(p.packageName); 6734 } 6735 } 6736 } 6737 return pkgs; 6738 } 6739 6740 public void shutdown() { 6741 mPackageUsage.write(true); 6742 } 6743 6744 @Override 6745 public void forceDexOpt(String packageName) { 6746 enforceSystemOrRoot("forceDexOpt"); 6747 6748 PackageParser.Package pkg; 6749 synchronized (mPackages) { 6750 pkg = mPackages.get(packageName); 6751 if (pkg == null) { 6752 throw new IllegalArgumentException("Unknown package: " + packageName); 6753 } 6754 } 6755 6756 synchronized (mInstallLock) { 6757 final String[] instructionSets = new String[] { 6758 getPrimaryInstructionSet(pkg.applicationInfo) }; 6759 6760 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6761 6762 // Whoever is calling forceDexOpt wants a fully compiled package. 6763 // Don't use profiles since that may cause compilation to be skipped. 6764 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6765 true /* inclDependencies */, pkg.volumeUuid, false /* useProfiles */, 6766 false /* extractOnly */); 6767 6768 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6769 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6770 throw new IllegalStateException("Failed to dexopt: " + res); 6771 } 6772 } 6773 } 6774 6775 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6776 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6777 Slog.w(TAG, "Unable to update from " + oldPkg.name 6778 + " to " + newPkg.packageName 6779 + ": old package not in system partition"); 6780 return false; 6781 } else if (mPackages.get(oldPkg.name) != null) { 6782 Slog.w(TAG, "Unable to update from " + oldPkg.name 6783 + " to " + newPkg.packageName 6784 + ": old package still exists"); 6785 return false; 6786 } 6787 return true; 6788 } 6789 6790 private boolean removeDataDirsLI(String volumeUuid, String packageName) { 6791 // TODO: triage flags as part of 26466827 6792 final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 6793 6794 boolean res = true; 6795 final int[] users = sUserManager.getUserIds(); 6796 for (int user : users) { 6797 try { 6798 mInstaller.destroyAppData(volumeUuid, packageName, user, flags); 6799 } catch (InstallerException e) { 6800 Slog.w(TAG, "Failed to delete data directory", e); 6801 res = false; 6802 } 6803 } 6804 return res; 6805 } 6806 6807 void removeCodePathLI(File codePath) { 6808 if (codePath.isDirectory()) { 6809 try { 6810 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 6811 } catch (InstallerException e) { 6812 Slog.w(TAG, "Failed to remove code path", e); 6813 } 6814 } else { 6815 codePath.delete(); 6816 } 6817 } 6818 6819 void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) { 6820 try { 6821 mInstaller.destroyAppData(volumeUuid, packageName, userId, flags); 6822 } catch (InstallerException e) { 6823 Slog.w(TAG, "Failed to destroy app data", e); 6824 } 6825 } 6826 6827 void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags, 6828 int appId, String seinfo) { 6829 try { 6830 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo); 6831 } catch (InstallerException e) { 6832 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 6833 } 6834 } 6835 6836 private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6837 // TODO: triage flags as part of 26466827 6838 final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 6839 6840 final int[] users = sUserManager.getUserIds(); 6841 for (int user : users) { 6842 try { 6843 mInstaller.clearAppData(volumeUuid, packageName, user, 6844 flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 6845 } catch (InstallerException e) { 6846 Slog.w(TAG, "Failed to delete code cache directory", e); 6847 } 6848 } 6849 } 6850 6851 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6852 PackageParser.Package changingLib) { 6853 if (file.path != null) { 6854 usesLibraryFiles.add(file.path); 6855 return; 6856 } 6857 PackageParser.Package p = mPackages.get(file.apk); 6858 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6859 // If we are doing this while in the middle of updating a library apk, 6860 // then we need to make sure to use that new apk for determining the 6861 // dependencies here. (We haven't yet finished committing the new apk 6862 // to the package manager state.) 6863 if (p == null || p.packageName.equals(changingLib.packageName)) { 6864 p = changingLib; 6865 } 6866 } 6867 if (p != null) { 6868 usesLibraryFiles.addAll(p.getAllCodePaths()); 6869 } 6870 } 6871 6872 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6873 PackageParser.Package changingLib) throws PackageManagerException { 6874 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6875 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6876 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6877 for (int i=0; i<N; i++) { 6878 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6879 if (file == null) { 6880 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6881 "Package " + pkg.packageName + " requires unavailable shared library " 6882 + pkg.usesLibraries.get(i) + "; failing!"); 6883 } 6884 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6885 } 6886 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6887 for (int i=0; i<N; i++) { 6888 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6889 if (file == null) { 6890 Slog.w(TAG, "Package " + pkg.packageName 6891 + " desires unavailable shared library " 6892 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6893 } else { 6894 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6895 } 6896 } 6897 N = usesLibraryFiles.size(); 6898 if (N > 0) { 6899 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6900 } else { 6901 pkg.usesLibraryFiles = null; 6902 } 6903 } 6904 } 6905 6906 private static boolean hasString(List<String> list, List<String> which) { 6907 if (list == null) { 6908 return false; 6909 } 6910 for (int i=list.size()-1; i>=0; i--) { 6911 for (int j=which.size()-1; j>=0; j--) { 6912 if (which.get(j).equals(list.get(i))) { 6913 return true; 6914 } 6915 } 6916 } 6917 return false; 6918 } 6919 6920 private void updateAllSharedLibrariesLPw() { 6921 for (PackageParser.Package pkg : mPackages.values()) { 6922 try { 6923 updateSharedLibrariesLPw(pkg, null); 6924 } catch (PackageManagerException e) { 6925 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6926 } 6927 } 6928 } 6929 6930 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6931 PackageParser.Package changingPkg) { 6932 ArrayList<PackageParser.Package> res = null; 6933 for (PackageParser.Package pkg : mPackages.values()) { 6934 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6935 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6936 if (res == null) { 6937 res = new ArrayList<PackageParser.Package>(); 6938 } 6939 res.add(pkg); 6940 try { 6941 updateSharedLibrariesLPw(pkg, changingPkg); 6942 } catch (PackageManagerException e) { 6943 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6944 } 6945 } 6946 } 6947 return res; 6948 } 6949 6950 /** 6951 * Derive the value of the {@code cpuAbiOverride} based on the provided 6952 * value and an optional stored value from the package settings. 6953 */ 6954 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6955 String cpuAbiOverride = null; 6956 6957 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6958 cpuAbiOverride = null; 6959 } else if (abiOverride != null) { 6960 cpuAbiOverride = abiOverride; 6961 } else if (settings != null) { 6962 cpuAbiOverride = settings.cpuAbiOverrideString; 6963 } 6964 6965 return cpuAbiOverride; 6966 } 6967 6968 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 6969 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6970 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6971 try { 6972 return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 6973 } finally { 6974 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6975 } 6976 } 6977 6978 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6979 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6980 boolean success = false; 6981 try { 6982 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6983 currentTime, user); 6984 success = true; 6985 return res; 6986 } finally { 6987 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6988 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6989 } 6990 } 6991 } 6992 6993 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6994 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6995 final File scanFile = new File(pkg.codePath); 6996 if (pkg.applicationInfo.getCodePath() == null || 6997 pkg.applicationInfo.getResourcePath() == null) { 6998 // Bail out. The resource and code paths haven't been set. 6999 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7000 "Code and resource paths haven't been set correctly"); 7001 } 7002 7003 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7004 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7005 } else { 7006 // Only allow system apps to be flagged as core apps. 7007 pkg.coreApp = false; 7008 } 7009 7010 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7011 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7012 } 7013 7014 if (mCustomResolverComponentName != null && 7015 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7016 setUpCustomResolverActivity(pkg); 7017 } 7018 7019 if (pkg.packageName.equals("android")) { 7020 synchronized (mPackages) { 7021 if (mAndroidApplication != null) { 7022 Slog.w(TAG, "*************************************************"); 7023 Slog.w(TAG, "Core android package being redefined. Skipping."); 7024 Slog.w(TAG, " file=" + scanFile); 7025 Slog.w(TAG, "*************************************************"); 7026 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7027 "Core android package being redefined. Skipping."); 7028 } 7029 7030 // Set up information for our fall-back user intent resolution activity. 7031 mPlatformPackage = pkg; 7032 pkg.mVersionCode = mSdkVersion; 7033 mAndroidApplication = pkg.applicationInfo; 7034 7035 if (!mResolverReplaced) { 7036 mResolveActivity.applicationInfo = mAndroidApplication; 7037 mResolveActivity.name = ResolverActivity.class.getName(); 7038 mResolveActivity.packageName = mAndroidApplication.packageName; 7039 mResolveActivity.processName = "system:ui"; 7040 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7041 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7042 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7043 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7044 mResolveActivity.exported = true; 7045 mResolveActivity.enabled = true; 7046 mResolveInfo.activityInfo = mResolveActivity; 7047 mResolveInfo.priority = 0; 7048 mResolveInfo.preferredOrder = 0; 7049 mResolveInfo.match = 0; 7050 mResolveComponentName = new ComponentName( 7051 mAndroidApplication.packageName, mResolveActivity.name); 7052 } 7053 } 7054 } 7055 7056 if (DEBUG_PACKAGE_SCANNING) { 7057 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7058 Log.d(TAG, "Scanning package " + pkg.packageName); 7059 } 7060 7061 if (mPackages.containsKey(pkg.packageName) 7062 || mSharedLibraries.containsKey(pkg.packageName)) { 7063 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7064 "Application package " + pkg.packageName 7065 + " already installed. Skipping duplicate."); 7066 } 7067 7068 // If we're only installing presumed-existing packages, require that the 7069 // scanned APK is both already known and at the path previously established 7070 // for it. Previously unknown packages we pick up normally, but if we have an 7071 // a priori expectation about this package's install presence, enforce it. 7072 // With a singular exception for new system packages. When an OTA contains 7073 // a new system package, we allow the codepath to change from a system location 7074 // to the user-installed location. If we don't allow this change, any newer, 7075 // user-installed version of the application will be ignored. 7076 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7077 if (mExpectingBetter.containsKey(pkg.packageName)) { 7078 logCriticalInfo(Log.WARN, 7079 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7080 } else { 7081 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7082 if (known != null) { 7083 if (DEBUG_PACKAGE_SCANNING) { 7084 Log.d(TAG, "Examining " + pkg.codePath 7085 + " and requiring known paths " + known.codePathString 7086 + " & " + known.resourcePathString); 7087 } 7088 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7089 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 7090 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7091 "Application package " + pkg.packageName 7092 + " found at " + pkg.applicationInfo.getCodePath() 7093 + " but expected at " + known.codePathString + "; ignoring."); 7094 } 7095 } 7096 } 7097 } 7098 7099 // Initialize package source and resource directories 7100 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7101 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7102 7103 SharedUserSetting suid = null; 7104 PackageSetting pkgSetting = null; 7105 7106 if (!isSystemApp(pkg)) { 7107 // Only system apps can use these features. 7108 pkg.mOriginalPackages = null; 7109 pkg.mRealPackage = null; 7110 pkg.mAdoptPermissions = null; 7111 } 7112 7113 // writer 7114 synchronized (mPackages) { 7115 if (pkg.mSharedUserId != null) { 7116 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7117 if (suid == null) { 7118 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7119 "Creating application package " + pkg.packageName 7120 + " for shared user failed"); 7121 } 7122 if (DEBUG_PACKAGE_SCANNING) { 7123 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7124 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7125 + "): packages=" + suid.packages); 7126 } 7127 } 7128 7129 // Check if we are renaming from an original package name. 7130 PackageSetting origPackage = null; 7131 String realName = null; 7132 if (pkg.mOriginalPackages != null) { 7133 // This package may need to be renamed to a previously 7134 // installed name. Let's check on that... 7135 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7136 if (pkg.mOriginalPackages.contains(renamed)) { 7137 // This package had originally been installed as the 7138 // original name, and we have already taken care of 7139 // transitioning to the new one. Just update the new 7140 // one to continue using the old name. 7141 realName = pkg.mRealPackage; 7142 if (!pkg.packageName.equals(renamed)) { 7143 // Callers into this function may have already taken 7144 // care of renaming the package; only do it here if 7145 // it is not already done. 7146 pkg.setPackageName(renamed); 7147 } 7148 7149 } else { 7150 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7151 if ((origPackage = mSettings.peekPackageLPr( 7152 pkg.mOriginalPackages.get(i))) != null) { 7153 // We do have the package already installed under its 7154 // original name... should we use it? 7155 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7156 // New package is not compatible with original. 7157 origPackage = null; 7158 continue; 7159 } else if (origPackage.sharedUser != null) { 7160 // Make sure uid is compatible between packages. 7161 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7162 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7163 + " to " + pkg.packageName + ": old uid " 7164 + origPackage.sharedUser.name 7165 + " differs from " + pkg.mSharedUserId); 7166 origPackage = null; 7167 continue; 7168 } 7169 } else { 7170 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7171 + pkg.packageName + " to old name " + origPackage.name); 7172 } 7173 break; 7174 } 7175 } 7176 } 7177 } 7178 7179 if (mTransferedPackages.contains(pkg.packageName)) { 7180 Slog.w(TAG, "Package " + pkg.packageName 7181 + " was transferred to another, but its .apk remains"); 7182 } 7183 7184 // Just create the setting, don't add it yet. For already existing packages 7185 // the PkgSetting exists already and doesn't have to be created. 7186 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7187 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7188 pkg.applicationInfo.primaryCpuAbi, 7189 pkg.applicationInfo.secondaryCpuAbi, 7190 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7191 user, false); 7192 if (pkgSetting == null) { 7193 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7194 "Creating application package " + pkg.packageName + " failed"); 7195 } 7196 7197 if (pkgSetting.origPackage != null) { 7198 // If we are first transitioning from an original package, 7199 // fix up the new package's name now. We need to do this after 7200 // looking up the package under its new name, so getPackageLP 7201 // can take care of fiddling things correctly. 7202 pkg.setPackageName(origPackage.name); 7203 7204 // File a report about this. 7205 String msg = "New package " + pkgSetting.realName 7206 + " renamed to replace old package " + pkgSetting.name; 7207 reportSettingsProblem(Log.WARN, msg); 7208 7209 // Make a note of it. 7210 mTransferedPackages.add(origPackage.name); 7211 7212 // No longer need to retain this. 7213 pkgSetting.origPackage = null; 7214 } 7215 7216 if (realName != null) { 7217 // Make a note of it. 7218 mTransferedPackages.add(pkg.packageName); 7219 } 7220 7221 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7222 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7223 } 7224 7225 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7226 // Check all shared libraries and map to their actual file path. 7227 // We only do this here for apps not on a system dir, because those 7228 // are the only ones that can fail an install due to this. We 7229 // will take care of the system apps by updating all of their 7230 // library paths after the scan is done. 7231 updateSharedLibrariesLPw(pkg, null); 7232 } 7233 7234 if (mFoundPolicyFile) { 7235 SELinuxMMAC.assignSeinfoValue(pkg); 7236 } 7237 7238 pkg.applicationInfo.uid = pkgSetting.appId; 7239 pkg.mExtras = pkgSetting; 7240 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7241 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7242 // We just determined the app is signed correctly, so bring 7243 // over the latest parsed certs. 7244 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7245 } else { 7246 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7247 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7248 "Package " + pkg.packageName + " upgrade keys do not match the " 7249 + "previously installed version"); 7250 } else { 7251 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7252 String msg = "System package " + pkg.packageName 7253 + " signature changed; retaining data."; 7254 reportSettingsProblem(Log.WARN, msg); 7255 } 7256 } 7257 } else { 7258 try { 7259 verifySignaturesLP(pkgSetting, pkg); 7260 // We just determined the app is signed correctly, so bring 7261 // over the latest parsed certs. 7262 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7263 } catch (PackageManagerException e) { 7264 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7265 throw e; 7266 } 7267 // The signature has changed, but this package is in the system 7268 // image... let's recover! 7269 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7270 // However... if this package is part of a shared user, but it 7271 // doesn't match the signature of the shared user, let's fail. 7272 // What this means is that you can't change the signatures 7273 // associated with an overall shared user, which doesn't seem all 7274 // that unreasonable. 7275 if (pkgSetting.sharedUser != null) { 7276 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7277 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7278 throw new PackageManagerException( 7279 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7280 "Signature mismatch for shared user: " 7281 + pkgSetting.sharedUser); 7282 } 7283 } 7284 // File a report about this. 7285 String msg = "System package " + pkg.packageName 7286 + " signature changed; retaining data."; 7287 reportSettingsProblem(Log.WARN, msg); 7288 } 7289 } 7290 // Verify that this new package doesn't have any content providers 7291 // that conflict with existing packages. Only do this if the 7292 // package isn't already installed, since we don't want to break 7293 // things that are installed. 7294 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7295 final int N = pkg.providers.size(); 7296 int i; 7297 for (i=0; i<N; i++) { 7298 PackageParser.Provider p = pkg.providers.get(i); 7299 if (p.info.authority != null) { 7300 String names[] = p.info.authority.split(";"); 7301 for (int j = 0; j < names.length; j++) { 7302 if (mProvidersByAuthority.containsKey(names[j])) { 7303 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7304 final String otherPackageName = 7305 ((other != null && other.getComponentName() != null) ? 7306 other.getComponentName().getPackageName() : "?"); 7307 throw new PackageManagerException( 7308 INSTALL_FAILED_CONFLICTING_PROVIDER, 7309 "Can't install because provider name " + names[j] 7310 + " (in package " + pkg.applicationInfo.packageName 7311 + ") is already used by " + otherPackageName); 7312 } 7313 } 7314 } 7315 } 7316 } 7317 7318 if (pkg.mAdoptPermissions != null) { 7319 // This package wants to adopt ownership of permissions from 7320 // another package. 7321 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7322 final String origName = pkg.mAdoptPermissions.get(i); 7323 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7324 if (orig != null) { 7325 if (verifyPackageUpdateLPr(orig, pkg)) { 7326 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7327 + pkg.packageName); 7328 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7329 } 7330 } 7331 } 7332 } 7333 } 7334 7335 final String pkgName = pkg.packageName; 7336 7337 final long scanFileTime = scanFile.lastModified(); 7338 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7339 pkg.applicationInfo.processName = fixProcessName( 7340 pkg.applicationInfo.packageName, 7341 pkg.applicationInfo.processName, 7342 pkg.applicationInfo.uid); 7343 7344 if (pkg != mPlatformPackage) { 7345 // Get all of our default paths setup 7346 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7347 } 7348 7349 final String path = scanFile.getPath(); 7350 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7351 7352 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7353 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7354 7355 // Some system apps still use directory structure for native libraries 7356 // in which case we might end up not detecting abi solely based on apk 7357 // structure. Try to detect abi based on directory structure. 7358 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7359 pkg.applicationInfo.primaryCpuAbi == null) { 7360 setBundledAppAbisAndRoots(pkg, pkgSetting); 7361 setNativeLibraryPaths(pkg); 7362 } 7363 7364 } else { 7365 if ((scanFlags & SCAN_MOVE) != 0) { 7366 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7367 // but we already have this packages package info in the PackageSetting. We just 7368 // use that and derive the native library path based on the new codepath. 7369 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7370 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7371 } 7372 7373 // Set native library paths again. For moves, the path will be updated based on the 7374 // ABIs we've determined above. For non-moves, the path will be updated based on the 7375 // ABIs we determined during compilation, but the path will depend on the final 7376 // package path (after the rename away from the stage path). 7377 setNativeLibraryPaths(pkg); 7378 } 7379 7380 // This is a special case for the "system" package, where the ABI is 7381 // dictated by the zygote configuration (and init.rc). We should keep track 7382 // of this ABI so that we can deal with "normal" applications that run under 7383 // the same UID correctly. 7384 if (mPlatformPackage == pkg) { 7385 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7386 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7387 } 7388 7389 // If there's a mismatch between the abi-override in the package setting 7390 // and the abiOverride specified for the install. Warn about this because we 7391 // would've already compiled the app without taking the package setting into 7392 // account. 7393 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7394 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7395 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7396 " for package " + pkg.packageName); 7397 } 7398 } 7399 7400 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7401 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7402 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7403 7404 // Copy the derived override back to the parsed package, so that we can 7405 // update the package settings accordingly. 7406 pkg.cpuAbiOverride = cpuAbiOverride; 7407 7408 if (DEBUG_ABI_SELECTION) { 7409 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7410 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7411 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7412 } 7413 7414 // Push the derived path down into PackageSettings so we know what to 7415 // clean up at uninstall time. 7416 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7417 7418 if (DEBUG_ABI_SELECTION) { 7419 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7420 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7421 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7422 } 7423 7424 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7425 // We don't do this here during boot because we can do it all 7426 // at once after scanning all existing packages. 7427 // 7428 // We also do this *before* we perform dexopt on this package, so that 7429 // we can avoid redundant dexopts, and also to make sure we've got the 7430 // code and package path correct. 7431 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7432 pkg, true /* boot complete */); 7433 } 7434 7435 if (mFactoryTest && pkg.requestedPermissions.contains( 7436 android.Manifest.permission.FACTORY_TEST)) { 7437 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7438 } 7439 7440 ArrayList<PackageParser.Package> clientLibPkgs = null; 7441 7442 // writer 7443 synchronized (mPackages) { 7444 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7445 // Only system apps can add new shared libraries. 7446 if (pkg.libraryNames != null) { 7447 for (int i=0; i<pkg.libraryNames.size(); i++) { 7448 String name = pkg.libraryNames.get(i); 7449 boolean allowed = false; 7450 if (pkg.isUpdatedSystemApp()) { 7451 // New library entries can only be added through the 7452 // system image. This is important to get rid of a lot 7453 // of nasty edge cases: for example if we allowed a non- 7454 // system update of the app to add a library, then uninstalling 7455 // the update would make the library go away, and assumptions 7456 // we made such as through app install filtering would now 7457 // have allowed apps on the device which aren't compatible 7458 // with it. Better to just have the restriction here, be 7459 // conservative, and create many fewer cases that can negatively 7460 // impact the user experience. 7461 final PackageSetting sysPs = mSettings 7462 .getDisabledSystemPkgLPr(pkg.packageName); 7463 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7464 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7465 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7466 allowed = true; 7467 break; 7468 } 7469 } 7470 } 7471 } else { 7472 allowed = true; 7473 } 7474 if (allowed) { 7475 if (!mSharedLibraries.containsKey(name)) { 7476 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7477 } else if (!name.equals(pkg.packageName)) { 7478 Slog.w(TAG, "Package " + pkg.packageName + " library " 7479 + name + " already exists; skipping"); 7480 } 7481 } else { 7482 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7483 + name + " that is not declared on system image; skipping"); 7484 } 7485 } 7486 if ((scanFlags & SCAN_BOOTING) == 0) { 7487 // If we are not booting, we need to update any applications 7488 // that are clients of our shared library. If we are booting, 7489 // this will all be done once the scan is complete. 7490 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7491 } 7492 } 7493 } 7494 } 7495 7496 // Request the ActivityManager to kill the process(only for existing packages) 7497 // so that we do not end up in a confused state while the user is still using the older 7498 // version of the application while the new one gets installed. 7499 if ((scanFlags & SCAN_REPLACING) != 0) { 7500 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7501 7502 killApplication(pkg.applicationInfo.packageName, 7503 pkg.applicationInfo.uid, "replace pkg"); 7504 7505 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7506 } 7507 7508 // Also need to kill any apps that are dependent on the library. 7509 if (clientLibPkgs != null) { 7510 for (int i=0; i<clientLibPkgs.size(); i++) { 7511 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7512 killApplication(clientPkg.applicationInfo.packageName, 7513 clientPkg.applicationInfo.uid, "update lib"); 7514 } 7515 } 7516 7517 // Make sure we're not adding any bogus keyset info 7518 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7519 ksms.assertScannedPackageValid(pkg); 7520 7521 // writer 7522 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7523 7524 boolean createIdmapFailed = false; 7525 synchronized (mPackages) { 7526 // We don't expect installation to fail beyond this point 7527 7528 // Add the new setting to mSettings 7529 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7530 // Add the new setting to mPackages 7531 mPackages.put(pkg.applicationInfo.packageName, pkg); 7532 // Make sure we don't accidentally delete its data. 7533 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7534 while (iter.hasNext()) { 7535 PackageCleanItem item = iter.next(); 7536 if (pkgName.equals(item.packageName)) { 7537 iter.remove(); 7538 } 7539 } 7540 7541 // Take care of first install / last update times. 7542 if (currentTime != 0) { 7543 if (pkgSetting.firstInstallTime == 0) { 7544 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7545 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7546 pkgSetting.lastUpdateTime = currentTime; 7547 } 7548 } else if (pkgSetting.firstInstallTime == 0) { 7549 // We need *something*. Take time time stamp of the file. 7550 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7551 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7552 if (scanFileTime != pkgSetting.timeStamp) { 7553 // A package on the system image has changed; consider this 7554 // to be an update. 7555 pkgSetting.lastUpdateTime = scanFileTime; 7556 } 7557 } 7558 7559 // Add the package's KeySets to the global KeySetManagerService 7560 ksms.addScannedPackageLPw(pkg); 7561 7562 int N = pkg.providers.size(); 7563 StringBuilder r = null; 7564 int i; 7565 for (i=0; i<N; i++) { 7566 PackageParser.Provider p = pkg.providers.get(i); 7567 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7568 p.info.processName, pkg.applicationInfo.uid); 7569 mProviders.addProvider(p); 7570 p.syncable = p.info.isSyncable; 7571 if (p.info.authority != null) { 7572 String names[] = p.info.authority.split(";"); 7573 p.info.authority = null; 7574 for (int j = 0; j < names.length; j++) { 7575 if (j == 1 && p.syncable) { 7576 // We only want the first authority for a provider to possibly be 7577 // syncable, so if we already added this provider using a different 7578 // authority clear the syncable flag. We copy the provider before 7579 // changing it because the mProviders object contains a reference 7580 // to a provider that we don't want to change. 7581 // Only do this for the second authority since the resulting provider 7582 // object can be the same for all future authorities for this provider. 7583 p = new PackageParser.Provider(p); 7584 p.syncable = false; 7585 } 7586 if (!mProvidersByAuthority.containsKey(names[j])) { 7587 mProvidersByAuthority.put(names[j], p); 7588 if (p.info.authority == null) { 7589 p.info.authority = names[j]; 7590 } else { 7591 p.info.authority = p.info.authority + ";" + names[j]; 7592 } 7593 if (DEBUG_PACKAGE_SCANNING) { 7594 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7595 Log.d(TAG, "Registered content provider: " + names[j] 7596 + ", className = " + p.info.name + ", isSyncable = " 7597 + p.info.isSyncable); 7598 } 7599 } else { 7600 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7601 Slog.w(TAG, "Skipping provider name " + names[j] + 7602 " (in package " + pkg.applicationInfo.packageName + 7603 "): name already used by " 7604 + ((other != null && other.getComponentName() != null) 7605 ? other.getComponentName().getPackageName() : "?")); 7606 } 7607 } 7608 } 7609 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7610 if (r == null) { 7611 r = new StringBuilder(256); 7612 } else { 7613 r.append(' '); 7614 } 7615 r.append(p.info.name); 7616 } 7617 } 7618 if (r != null) { 7619 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7620 } 7621 7622 N = pkg.services.size(); 7623 r = null; 7624 for (i=0; i<N; i++) { 7625 PackageParser.Service s = pkg.services.get(i); 7626 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7627 s.info.processName, pkg.applicationInfo.uid); 7628 mServices.addService(s); 7629 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7630 if (r == null) { 7631 r = new StringBuilder(256); 7632 } else { 7633 r.append(' '); 7634 } 7635 r.append(s.info.name); 7636 } 7637 } 7638 if (r != null) { 7639 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7640 } 7641 7642 N = pkg.receivers.size(); 7643 r = null; 7644 for (i=0; i<N; i++) { 7645 PackageParser.Activity a = pkg.receivers.get(i); 7646 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7647 a.info.processName, pkg.applicationInfo.uid); 7648 mReceivers.addActivity(a, "receiver"); 7649 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7650 if (r == null) { 7651 r = new StringBuilder(256); 7652 } else { 7653 r.append(' '); 7654 } 7655 r.append(a.info.name); 7656 } 7657 } 7658 if (r != null) { 7659 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7660 } 7661 7662 N = pkg.activities.size(); 7663 r = null; 7664 for (i=0; i<N; i++) { 7665 PackageParser.Activity a = pkg.activities.get(i); 7666 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7667 a.info.processName, pkg.applicationInfo.uid); 7668 mActivities.addActivity(a, "activity"); 7669 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7670 if (r == null) { 7671 r = new StringBuilder(256); 7672 } else { 7673 r.append(' '); 7674 } 7675 r.append(a.info.name); 7676 } 7677 } 7678 if (r != null) { 7679 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7680 } 7681 7682 N = pkg.permissionGroups.size(); 7683 r = null; 7684 for (i=0; i<N; i++) { 7685 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7686 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7687 if (cur == null) { 7688 mPermissionGroups.put(pg.info.name, pg); 7689 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7690 if (r == null) { 7691 r = new StringBuilder(256); 7692 } else { 7693 r.append(' '); 7694 } 7695 r.append(pg.info.name); 7696 } 7697 } else { 7698 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7699 + pg.info.packageName + " ignored: original from " 7700 + cur.info.packageName); 7701 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7702 if (r == null) { 7703 r = new StringBuilder(256); 7704 } else { 7705 r.append(' '); 7706 } 7707 r.append("DUP:"); 7708 r.append(pg.info.name); 7709 } 7710 } 7711 } 7712 if (r != null) { 7713 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7714 } 7715 7716 N = pkg.permissions.size(); 7717 r = null; 7718 for (i=0; i<N; i++) { 7719 PackageParser.Permission p = pkg.permissions.get(i); 7720 7721 // Assume by default that we did not install this permission into the system. 7722 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7723 7724 // Now that permission groups have a special meaning, we ignore permission 7725 // groups for legacy apps to prevent unexpected behavior. In particular, 7726 // permissions for one app being granted to someone just becuase they happen 7727 // to be in a group defined by another app (before this had no implications). 7728 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7729 p.group = mPermissionGroups.get(p.info.group); 7730 // Warn for a permission in an unknown group. 7731 if (p.info.group != null && p.group == null) { 7732 Slog.w(TAG, "Permission " + p.info.name + " from package " 7733 + p.info.packageName + " in an unknown group " + p.info.group); 7734 } 7735 } 7736 7737 ArrayMap<String, BasePermission> permissionMap = 7738 p.tree ? mSettings.mPermissionTrees 7739 : mSettings.mPermissions; 7740 BasePermission bp = permissionMap.get(p.info.name); 7741 7742 // Allow system apps to redefine non-system permissions 7743 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7744 final boolean currentOwnerIsSystem = (bp.perm != null 7745 && isSystemApp(bp.perm.owner)); 7746 if (isSystemApp(p.owner)) { 7747 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7748 // It's a built-in permission and no owner, take ownership now 7749 bp.packageSetting = pkgSetting; 7750 bp.perm = p; 7751 bp.uid = pkg.applicationInfo.uid; 7752 bp.sourcePackage = p.info.packageName; 7753 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7754 } else if (!currentOwnerIsSystem) { 7755 String msg = "New decl " + p.owner + " of permission " 7756 + p.info.name + " is system; overriding " + bp.sourcePackage; 7757 reportSettingsProblem(Log.WARN, msg); 7758 bp = null; 7759 } 7760 } 7761 } 7762 7763 if (bp == null) { 7764 bp = new BasePermission(p.info.name, p.info.packageName, 7765 BasePermission.TYPE_NORMAL); 7766 permissionMap.put(p.info.name, bp); 7767 } 7768 7769 if (bp.perm == null) { 7770 if (bp.sourcePackage == null 7771 || bp.sourcePackage.equals(p.info.packageName)) { 7772 BasePermission tree = findPermissionTreeLP(p.info.name); 7773 if (tree == null 7774 || tree.sourcePackage.equals(p.info.packageName)) { 7775 bp.packageSetting = pkgSetting; 7776 bp.perm = p; 7777 bp.uid = pkg.applicationInfo.uid; 7778 bp.sourcePackage = p.info.packageName; 7779 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7780 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7781 if (r == null) { 7782 r = new StringBuilder(256); 7783 } else { 7784 r.append(' '); 7785 } 7786 r.append(p.info.name); 7787 } 7788 } else { 7789 Slog.w(TAG, "Permission " + p.info.name + " from package " 7790 + p.info.packageName + " ignored: base tree " 7791 + tree.name + " is from package " 7792 + tree.sourcePackage); 7793 } 7794 } else { 7795 Slog.w(TAG, "Permission " + p.info.name + " from package " 7796 + p.info.packageName + " ignored: original from " 7797 + bp.sourcePackage); 7798 } 7799 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7800 if (r == null) { 7801 r = new StringBuilder(256); 7802 } else { 7803 r.append(' '); 7804 } 7805 r.append("DUP:"); 7806 r.append(p.info.name); 7807 } 7808 if (bp.perm == p) { 7809 bp.protectionLevel = p.info.protectionLevel; 7810 } 7811 } 7812 7813 if (r != null) { 7814 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7815 } 7816 7817 N = pkg.instrumentation.size(); 7818 r = null; 7819 for (i=0; i<N; i++) { 7820 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7821 a.info.packageName = pkg.applicationInfo.packageName; 7822 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7823 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7824 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7825 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7826 a.info.dataDir = pkg.applicationInfo.dataDir; 7827 a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir; 7828 a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir; 7829 7830 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7831 // need other information about the application, like the ABI and what not ? 7832 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7833 mInstrumentation.put(a.getComponentName(), a); 7834 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7835 if (r == null) { 7836 r = new StringBuilder(256); 7837 } else { 7838 r.append(' '); 7839 } 7840 r.append(a.info.name); 7841 } 7842 } 7843 if (r != null) { 7844 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7845 } 7846 7847 if (pkg.protectedBroadcasts != null) { 7848 N = pkg.protectedBroadcasts.size(); 7849 for (i=0; i<N; i++) { 7850 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7851 } 7852 } 7853 7854 pkgSetting.setTimeStamp(scanFileTime); 7855 7856 // Create idmap files for pairs of (packages, overlay packages). 7857 // Note: "android", ie framework-res.apk, is handled by native layers. 7858 if (pkg.mOverlayTarget != null) { 7859 // This is an overlay package. 7860 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7861 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7862 mOverlays.put(pkg.mOverlayTarget, 7863 new ArrayMap<String, PackageParser.Package>()); 7864 } 7865 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7866 map.put(pkg.packageName, pkg); 7867 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7868 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7869 createIdmapFailed = true; 7870 } 7871 } 7872 } else if (mOverlays.containsKey(pkg.packageName) && 7873 !pkg.packageName.equals("android")) { 7874 // This is a regular package, with one or more known overlay packages. 7875 createIdmapsForPackageLI(pkg); 7876 } 7877 } 7878 7879 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7880 7881 if (createIdmapFailed) { 7882 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7883 "scanPackageLI failed to createIdmap"); 7884 } 7885 return pkg; 7886 } 7887 7888 /** 7889 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7890 * is derived purely on the basis of the contents of {@code scanFile} and 7891 * {@code cpuAbiOverride}. 7892 * 7893 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7894 */ 7895 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7896 String cpuAbiOverride, boolean extractLibs) 7897 throws PackageManagerException { 7898 // TODO: We can probably be smarter about this stuff. For installed apps, 7899 // we can calculate this information at install time once and for all. For 7900 // system apps, we can probably assume that this information doesn't change 7901 // after the first boot scan. As things stand, we do lots of unnecessary work. 7902 7903 // Give ourselves some initial paths; we'll come back for another 7904 // pass once we've determined ABI below. 7905 setNativeLibraryPaths(pkg); 7906 7907 // We would never need to extract libs for forward-locked and external packages, 7908 // since the container service will do it for us. We shouldn't attempt to 7909 // extract libs from system app when it was not updated. 7910 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 7911 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 7912 extractLibs = false; 7913 } 7914 7915 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7916 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7917 7918 NativeLibraryHelper.Handle handle = null; 7919 try { 7920 handle = NativeLibraryHelper.Handle.create(pkg); 7921 // TODO(multiArch): This can be null for apps that didn't go through the 7922 // usual installation process. We can calculate it again, like we 7923 // do during install time. 7924 // 7925 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7926 // unnecessary. 7927 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7928 7929 // Null out the abis so that they can be recalculated. 7930 pkg.applicationInfo.primaryCpuAbi = null; 7931 pkg.applicationInfo.secondaryCpuAbi = null; 7932 if (isMultiArch(pkg.applicationInfo)) { 7933 // Warn if we've set an abiOverride for multi-lib packages.. 7934 // By definition, we need to copy both 32 and 64 bit libraries for 7935 // such packages. 7936 if (pkg.cpuAbiOverride != null 7937 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7938 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7939 } 7940 7941 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7942 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7943 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7944 if (extractLibs) { 7945 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7946 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7947 useIsaSpecificSubdirs); 7948 } else { 7949 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7950 } 7951 } 7952 7953 maybeThrowExceptionForMultiArchCopy( 7954 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7955 7956 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7957 if (extractLibs) { 7958 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7959 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7960 useIsaSpecificSubdirs); 7961 } else { 7962 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7963 } 7964 } 7965 7966 maybeThrowExceptionForMultiArchCopy( 7967 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7968 7969 if (abi64 >= 0) { 7970 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7971 } 7972 7973 if (abi32 >= 0) { 7974 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7975 if (abi64 >= 0) { 7976 pkg.applicationInfo.secondaryCpuAbi = abi; 7977 } else { 7978 pkg.applicationInfo.primaryCpuAbi = abi; 7979 } 7980 } 7981 } else { 7982 String[] abiList = (cpuAbiOverride != null) ? 7983 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7984 7985 // Enable gross and lame hacks for apps that are built with old 7986 // SDK tools. We must scan their APKs for renderscript bitcode and 7987 // not launch them if it's present. Don't bother checking on devices 7988 // that don't have 64 bit support. 7989 boolean needsRenderScriptOverride = false; 7990 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7991 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7992 abiList = Build.SUPPORTED_32_BIT_ABIS; 7993 needsRenderScriptOverride = true; 7994 } 7995 7996 final int copyRet; 7997 if (extractLibs) { 7998 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7999 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8000 } else { 8001 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8002 } 8003 8004 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8005 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8006 "Error unpackaging native libs for app, errorCode=" + copyRet); 8007 } 8008 8009 if (copyRet >= 0) { 8010 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8011 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8012 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8013 } else if (needsRenderScriptOverride) { 8014 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8015 } 8016 } 8017 } catch (IOException ioe) { 8018 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8019 } finally { 8020 IoUtils.closeQuietly(handle); 8021 } 8022 8023 // Now that we've calculated the ABIs and determined if it's an internal app, 8024 // we will go ahead and populate the nativeLibraryPath. 8025 setNativeLibraryPaths(pkg); 8026 } 8027 8028 /** 8029 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8030 * i.e, so that all packages can be run inside a single process if required. 8031 * 8032 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8033 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8034 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8035 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8036 * updating a package that belongs to a shared user. 8037 * 8038 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8039 * adds unnecessary complexity. 8040 */ 8041 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8042 PackageParser.Package scannedPackage, boolean bootComplete) { 8043 String requiredInstructionSet = null; 8044 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8045 requiredInstructionSet = VMRuntime.getInstructionSet( 8046 scannedPackage.applicationInfo.primaryCpuAbi); 8047 } 8048 8049 PackageSetting requirer = null; 8050 for (PackageSetting ps : packagesForUser) { 8051 // If packagesForUser contains scannedPackage, we skip it. This will happen 8052 // when scannedPackage is an update of an existing package. Without this check, 8053 // we will never be able to change the ABI of any package belonging to a shared 8054 // user, even if it's compatible with other packages. 8055 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8056 if (ps.primaryCpuAbiString == null) { 8057 continue; 8058 } 8059 8060 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8061 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8062 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8063 // this but there's not much we can do. 8064 String errorMessage = "Instruction set mismatch, " 8065 + ((requirer == null) ? "[caller]" : requirer) 8066 + " requires " + requiredInstructionSet + " whereas " + ps 8067 + " requires " + instructionSet; 8068 Slog.w(TAG, errorMessage); 8069 } 8070 8071 if (requiredInstructionSet == null) { 8072 requiredInstructionSet = instructionSet; 8073 requirer = ps; 8074 } 8075 } 8076 } 8077 8078 if (requiredInstructionSet != null) { 8079 String adjustedAbi; 8080 if (requirer != null) { 8081 // requirer != null implies that either scannedPackage was null or that scannedPackage 8082 // did not require an ABI, in which case we have to adjust scannedPackage to match 8083 // the ABI of the set (which is the same as requirer's ABI) 8084 adjustedAbi = requirer.primaryCpuAbiString; 8085 if (scannedPackage != null) { 8086 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8087 } 8088 } else { 8089 // requirer == null implies that we're updating all ABIs in the set to 8090 // match scannedPackage. 8091 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8092 } 8093 8094 for (PackageSetting ps : packagesForUser) { 8095 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8096 if (ps.primaryCpuAbiString != null) { 8097 continue; 8098 } 8099 8100 ps.primaryCpuAbiString = adjustedAbi; 8101 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 8102 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8103 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi); 8104 try { 8105 mInstaller.rmdex(ps.codePathString, 8106 getDexCodeInstructionSet(getPreferredInstructionSet())); 8107 } catch (InstallerException ignored) { 8108 } 8109 } 8110 } 8111 } 8112 } 8113 } 8114 8115 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8116 synchronized (mPackages) { 8117 mResolverReplaced = true; 8118 // Set up information for custom user intent resolution activity. 8119 mResolveActivity.applicationInfo = pkg.applicationInfo; 8120 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8121 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8122 mResolveActivity.processName = pkg.applicationInfo.packageName; 8123 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8124 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8125 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8126 mResolveActivity.theme = 0; 8127 mResolveActivity.exported = true; 8128 mResolveActivity.enabled = true; 8129 mResolveInfo.activityInfo = mResolveActivity; 8130 mResolveInfo.priority = 0; 8131 mResolveInfo.preferredOrder = 0; 8132 mResolveInfo.match = 0; 8133 mResolveComponentName = mCustomResolverComponentName; 8134 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8135 mResolveComponentName); 8136 } 8137 } 8138 8139 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8140 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8141 8142 // Set up information for ephemeral installer activity 8143 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8144 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8145 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8146 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8147 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8148 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8149 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8150 mEphemeralInstallerActivity.theme = 0; 8151 mEphemeralInstallerActivity.exported = true; 8152 mEphemeralInstallerActivity.enabled = true; 8153 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8154 mEphemeralInstallerInfo.priority = 0; 8155 mEphemeralInstallerInfo.preferredOrder = 0; 8156 mEphemeralInstallerInfo.match = 0; 8157 8158 if (DEBUG_EPHEMERAL) { 8159 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8160 } 8161 } 8162 8163 private static String calculateBundledApkRoot(final String codePathString) { 8164 final File codePath = new File(codePathString); 8165 final File codeRoot; 8166 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8167 codeRoot = Environment.getRootDirectory(); 8168 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8169 codeRoot = Environment.getOemDirectory(); 8170 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8171 codeRoot = Environment.getVendorDirectory(); 8172 } else { 8173 // Unrecognized code path; take its top real segment as the apk root: 8174 // e.g. /something/app/blah.apk => /something 8175 try { 8176 File f = codePath.getCanonicalFile(); 8177 File parent = f.getParentFile(); // non-null because codePath is a file 8178 File tmp; 8179 while ((tmp = parent.getParentFile()) != null) { 8180 f = parent; 8181 parent = tmp; 8182 } 8183 codeRoot = f; 8184 Slog.w(TAG, "Unrecognized code path " 8185 + codePath + " - using " + codeRoot); 8186 } catch (IOException e) { 8187 // Can't canonicalize the code path -- shenanigans? 8188 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8189 return Environment.getRootDirectory().getPath(); 8190 } 8191 } 8192 return codeRoot.getPath(); 8193 } 8194 8195 /** 8196 * Derive and set the location of native libraries for the given package, 8197 * which varies depending on where and how the package was installed. 8198 */ 8199 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8200 final ApplicationInfo info = pkg.applicationInfo; 8201 final String codePath = pkg.codePath; 8202 final File codeFile = new File(codePath); 8203 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8204 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8205 8206 info.nativeLibraryRootDir = null; 8207 info.nativeLibraryRootRequiresIsa = false; 8208 info.nativeLibraryDir = null; 8209 info.secondaryNativeLibraryDir = null; 8210 8211 if (isApkFile(codeFile)) { 8212 // Monolithic install 8213 if (bundledApp) { 8214 // If "/system/lib64/apkname" exists, assume that is the per-package 8215 // native library directory to use; otherwise use "/system/lib/apkname". 8216 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8217 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8218 getPrimaryInstructionSet(info)); 8219 8220 // This is a bundled system app so choose the path based on the ABI. 8221 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8222 // is just the default path. 8223 final String apkName = deriveCodePathName(codePath); 8224 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8225 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8226 apkName).getAbsolutePath(); 8227 8228 if (info.secondaryCpuAbi != null) { 8229 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8230 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8231 secondaryLibDir, apkName).getAbsolutePath(); 8232 } 8233 } else if (asecApp) { 8234 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8235 .getAbsolutePath(); 8236 } else { 8237 final String apkName = deriveCodePathName(codePath); 8238 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8239 .getAbsolutePath(); 8240 } 8241 8242 info.nativeLibraryRootRequiresIsa = false; 8243 info.nativeLibraryDir = info.nativeLibraryRootDir; 8244 } else { 8245 // Cluster install 8246 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8247 info.nativeLibraryRootRequiresIsa = true; 8248 8249 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8250 getPrimaryInstructionSet(info)).getAbsolutePath(); 8251 8252 if (info.secondaryCpuAbi != null) { 8253 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8254 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8255 } 8256 } 8257 } 8258 8259 /** 8260 * Calculate the abis and roots for a bundled app. These can uniquely 8261 * be determined from the contents of the system partition, i.e whether 8262 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8263 * of this information, and instead assume that the system was built 8264 * sensibly. 8265 */ 8266 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8267 PackageSetting pkgSetting) { 8268 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8269 8270 // If "/system/lib64/apkname" exists, assume that is the per-package 8271 // native library directory to use; otherwise use "/system/lib/apkname". 8272 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8273 setBundledAppAbi(pkg, apkRoot, apkName); 8274 // pkgSetting might be null during rescan following uninstall of updates 8275 // to a bundled app, so accommodate that possibility. The settings in 8276 // that case will be established later from the parsed package. 8277 // 8278 // If the settings aren't null, sync them up with what we've just derived. 8279 // note that apkRoot isn't stored in the package settings. 8280 if (pkgSetting != null) { 8281 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8282 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8283 } 8284 } 8285 8286 /** 8287 * Deduces the ABI of a bundled app and sets the relevant fields on the 8288 * parsed pkg object. 8289 * 8290 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8291 * under which system libraries are installed. 8292 * @param apkName the name of the installed package. 8293 */ 8294 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8295 final File codeFile = new File(pkg.codePath); 8296 8297 final boolean has64BitLibs; 8298 final boolean has32BitLibs; 8299 if (isApkFile(codeFile)) { 8300 // Monolithic install 8301 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8302 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8303 } else { 8304 // Cluster install 8305 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8306 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8307 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8308 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8309 has64BitLibs = (new File(rootDir, isa)).exists(); 8310 } else { 8311 has64BitLibs = false; 8312 } 8313 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8314 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8315 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8316 has32BitLibs = (new File(rootDir, isa)).exists(); 8317 } else { 8318 has32BitLibs = false; 8319 } 8320 } 8321 8322 if (has64BitLibs && !has32BitLibs) { 8323 // The package has 64 bit libs, but not 32 bit libs. Its primary 8324 // ABI should be 64 bit. We can safely assume here that the bundled 8325 // native libraries correspond to the most preferred ABI in the list. 8326 8327 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8328 pkg.applicationInfo.secondaryCpuAbi = null; 8329 } else if (has32BitLibs && !has64BitLibs) { 8330 // The package has 32 bit libs but not 64 bit libs. Its primary 8331 // ABI should be 32 bit. 8332 8333 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8334 pkg.applicationInfo.secondaryCpuAbi = null; 8335 } else if (has32BitLibs && has64BitLibs) { 8336 // The application has both 64 and 32 bit bundled libraries. We check 8337 // here that the app declares multiArch support, and warn if it doesn't. 8338 // 8339 // We will be lenient here and record both ABIs. The primary will be the 8340 // ABI that's higher on the list, i.e, a device that's configured to prefer 8341 // 64 bit apps will see a 64 bit primary ABI, 8342 8343 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8344 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 8345 } 8346 8347 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8348 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8349 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8350 } else { 8351 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8352 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8353 } 8354 } else { 8355 pkg.applicationInfo.primaryCpuAbi = null; 8356 pkg.applicationInfo.secondaryCpuAbi = null; 8357 } 8358 } 8359 8360 private void killApplication(String pkgName, int appId, String reason) { 8361 // Request the ActivityManager to kill the process(only for existing packages) 8362 // so that we do not end up in a confused state while the user is still using the older 8363 // version of the application while the new one gets installed. 8364 IActivityManager am = ActivityManagerNative.getDefault(); 8365 if (am != null) { 8366 try { 8367 am.killApplicationWithAppId(pkgName, appId, reason); 8368 } catch (RemoteException e) { 8369 } 8370 } 8371 } 8372 8373 void removePackageLI(PackageSetting ps, boolean chatty) { 8374 if (DEBUG_INSTALL) { 8375 if (chatty) 8376 Log.d(TAG, "Removing package " + ps.name); 8377 } 8378 8379 // writer 8380 synchronized (mPackages) { 8381 mPackages.remove(ps.name); 8382 final PackageParser.Package pkg = ps.pkg; 8383 if (pkg != null) { 8384 cleanPackageDataStructuresLILPw(pkg, chatty); 8385 } 8386 } 8387 } 8388 8389 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8390 if (DEBUG_INSTALL) { 8391 if (chatty) 8392 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8393 } 8394 8395 // writer 8396 synchronized (mPackages) { 8397 mPackages.remove(pkg.applicationInfo.packageName); 8398 cleanPackageDataStructuresLILPw(pkg, chatty); 8399 } 8400 } 8401 8402 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8403 int N = pkg.providers.size(); 8404 StringBuilder r = null; 8405 int i; 8406 for (i=0; i<N; i++) { 8407 PackageParser.Provider p = pkg.providers.get(i); 8408 mProviders.removeProvider(p); 8409 if (p.info.authority == null) { 8410 8411 /* There was another ContentProvider with this authority when 8412 * this app was installed so this authority is null, 8413 * Ignore it as we don't have to unregister the provider. 8414 */ 8415 continue; 8416 } 8417 String names[] = p.info.authority.split(";"); 8418 for (int j = 0; j < names.length; j++) { 8419 if (mProvidersByAuthority.get(names[j]) == p) { 8420 mProvidersByAuthority.remove(names[j]); 8421 if (DEBUG_REMOVE) { 8422 if (chatty) 8423 Log.d(TAG, "Unregistered content provider: " + names[j] 8424 + ", className = " + p.info.name + ", isSyncable = " 8425 + p.info.isSyncable); 8426 } 8427 } 8428 } 8429 if (DEBUG_REMOVE && chatty) { 8430 if (r == null) { 8431 r = new StringBuilder(256); 8432 } else { 8433 r.append(' '); 8434 } 8435 r.append(p.info.name); 8436 } 8437 } 8438 if (r != null) { 8439 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8440 } 8441 8442 N = pkg.services.size(); 8443 r = null; 8444 for (i=0; i<N; i++) { 8445 PackageParser.Service s = pkg.services.get(i); 8446 mServices.removeService(s); 8447 if (chatty) { 8448 if (r == null) { 8449 r = new StringBuilder(256); 8450 } else { 8451 r.append(' '); 8452 } 8453 r.append(s.info.name); 8454 } 8455 } 8456 if (r != null) { 8457 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8458 } 8459 8460 N = pkg.receivers.size(); 8461 r = null; 8462 for (i=0; i<N; i++) { 8463 PackageParser.Activity a = pkg.receivers.get(i); 8464 mReceivers.removeActivity(a, "receiver"); 8465 if (DEBUG_REMOVE && chatty) { 8466 if (r == null) { 8467 r = new StringBuilder(256); 8468 } else { 8469 r.append(' '); 8470 } 8471 r.append(a.info.name); 8472 } 8473 } 8474 if (r != null) { 8475 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8476 } 8477 8478 N = pkg.activities.size(); 8479 r = null; 8480 for (i=0; i<N; i++) { 8481 PackageParser.Activity a = pkg.activities.get(i); 8482 mActivities.removeActivity(a, "activity"); 8483 if (DEBUG_REMOVE && chatty) { 8484 if (r == null) { 8485 r = new StringBuilder(256); 8486 } else { 8487 r.append(' '); 8488 } 8489 r.append(a.info.name); 8490 } 8491 } 8492 if (r != null) { 8493 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8494 } 8495 8496 N = pkg.permissions.size(); 8497 r = null; 8498 for (i=0; i<N; i++) { 8499 PackageParser.Permission p = pkg.permissions.get(i); 8500 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8501 if (bp == null) { 8502 bp = mSettings.mPermissionTrees.get(p.info.name); 8503 } 8504 if (bp != null && bp.perm == p) { 8505 bp.perm = null; 8506 if (DEBUG_REMOVE && chatty) { 8507 if (r == null) { 8508 r = new StringBuilder(256); 8509 } else { 8510 r.append(' '); 8511 } 8512 r.append(p.info.name); 8513 } 8514 } 8515 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8516 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 8517 if (appOpPkgs != null) { 8518 appOpPkgs.remove(pkg.packageName); 8519 } 8520 } 8521 } 8522 if (r != null) { 8523 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8524 } 8525 8526 N = pkg.requestedPermissions.size(); 8527 r = null; 8528 for (i=0; i<N; i++) { 8529 String perm = pkg.requestedPermissions.get(i); 8530 BasePermission bp = mSettings.mPermissions.get(perm); 8531 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8532 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 8533 if (appOpPkgs != null) { 8534 appOpPkgs.remove(pkg.packageName); 8535 if (appOpPkgs.isEmpty()) { 8536 mAppOpPermissionPackages.remove(perm); 8537 } 8538 } 8539 } 8540 } 8541 if (r != null) { 8542 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8543 } 8544 8545 N = pkg.instrumentation.size(); 8546 r = null; 8547 for (i=0; i<N; i++) { 8548 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8549 mInstrumentation.remove(a.getComponentName()); 8550 if (DEBUG_REMOVE && chatty) { 8551 if (r == null) { 8552 r = new StringBuilder(256); 8553 } else { 8554 r.append(' '); 8555 } 8556 r.append(a.info.name); 8557 } 8558 } 8559 if (r != null) { 8560 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8561 } 8562 8563 r = null; 8564 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8565 // Only system apps can hold shared libraries. 8566 if (pkg.libraryNames != null) { 8567 for (i=0; i<pkg.libraryNames.size(); i++) { 8568 String name = pkg.libraryNames.get(i); 8569 SharedLibraryEntry cur = mSharedLibraries.get(name); 8570 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8571 mSharedLibraries.remove(name); 8572 if (DEBUG_REMOVE && chatty) { 8573 if (r == null) { 8574 r = new StringBuilder(256); 8575 } else { 8576 r.append(' '); 8577 } 8578 r.append(name); 8579 } 8580 } 8581 } 8582 } 8583 } 8584 if (r != null) { 8585 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8586 } 8587 } 8588 8589 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8590 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8591 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8592 return true; 8593 } 8594 } 8595 return false; 8596 } 8597 8598 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8599 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8600 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8601 8602 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 8603 int flags) { 8604 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 8605 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 8606 } 8607 8608 private void updatePermissionsLPw(String changingPkg, 8609 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 8610 // Make sure there are no dangling permission trees. 8611 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8612 while (it.hasNext()) { 8613 final BasePermission bp = it.next(); 8614 if (bp.packageSetting == null) { 8615 // We may not yet have parsed the package, so just see if 8616 // we still know about its settings. 8617 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8618 } 8619 if (bp.packageSetting == null) { 8620 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8621 + " from package " + bp.sourcePackage); 8622 it.remove(); 8623 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8624 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8625 Slog.i(TAG, "Removing old permission tree: " + bp.name 8626 + " from package " + bp.sourcePackage); 8627 flags |= UPDATE_PERMISSIONS_ALL; 8628 it.remove(); 8629 } 8630 } 8631 } 8632 8633 // Make sure all dynamic permissions have been assigned to a package, 8634 // and make sure there are no dangling permissions. 8635 it = mSettings.mPermissions.values().iterator(); 8636 while (it.hasNext()) { 8637 final BasePermission bp = it.next(); 8638 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8639 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8640 + bp.name + " pkg=" + bp.sourcePackage 8641 + " info=" + bp.pendingInfo); 8642 if (bp.packageSetting == null && bp.pendingInfo != null) { 8643 final BasePermission tree = findPermissionTreeLP(bp.name); 8644 if (tree != null && tree.perm != null) { 8645 bp.packageSetting = tree.packageSetting; 8646 bp.perm = new PackageParser.Permission(tree.perm.owner, 8647 new PermissionInfo(bp.pendingInfo)); 8648 bp.perm.info.packageName = tree.perm.info.packageName; 8649 bp.perm.info.name = bp.name; 8650 bp.uid = tree.uid; 8651 } 8652 } 8653 } 8654 if (bp.packageSetting == null) { 8655 // We may not yet have parsed the package, so just see if 8656 // we still know about its settings. 8657 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8658 } 8659 if (bp.packageSetting == null) { 8660 Slog.w(TAG, "Removing dangling permission: " + bp.name 8661 + " from package " + bp.sourcePackage); 8662 it.remove(); 8663 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8664 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8665 Slog.i(TAG, "Removing old permission: " + bp.name 8666 + " from package " + bp.sourcePackage); 8667 flags |= UPDATE_PERMISSIONS_ALL; 8668 it.remove(); 8669 } 8670 } 8671 } 8672 8673 // Now update the permissions for all packages, in particular 8674 // replace the granted permissions of the system packages. 8675 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8676 for (PackageParser.Package pkg : mPackages.values()) { 8677 if (pkg != pkgInfo) { 8678 // Only replace for packages on requested volume 8679 final String volumeUuid = getVolumeUuidForPackage(pkg); 8680 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 8681 && Objects.equals(replaceVolumeUuid, volumeUuid); 8682 grantPermissionsLPw(pkg, replace, changingPkg); 8683 } 8684 } 8685 } 8686 8687 if (pkgInfo != null) { 8688 // Only replace for packages on requested volume 8689 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 8690 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 8691 && Objects.equals(replaceVolumeUuid, volumeUuid); 8692 grantPermissionsLPw(pkgInfo, replace, changingPkg); 8693 } 8694 } 8695 8696 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8697 String packageOfInterest) { 8698 // IMPORTANT: There are two types of permissions: install and runtime. 8699 // Install time permissions are granted when the app is installed to 8700 // all device users and users added in the future. Runtime permissions 8701 // are granted at runtime explicitly to specific users. Normal and signature 8702 // protected permissions are install time permissions. Dangerous permissions 8703 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8704 // otherwise they are runtime permissions. This function does not manage 8705 // runtime permissions except for the case an app targeting Lollipop MR1 8706 // being upgraded to target a newer SDK, in which case dangerous permissions 8707 // are transformed from install time to runtime ones. 8708 8709 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8710 if (ps == null) { 8711 return; 8712 } 8713 8714 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 8715 8716 PermissionsState permissionsState = ps.getPermissionsState(); 8717 PermissionsState origPermissions = permissionsState; 8718 8719 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8720 8721 boolean runtimePermissionsRevoked = false; 8722 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8723 8724 boolean changedInstallPermission = false; 8725 8726 if (replace) { 8727 ps.installPermissionsFixed = false; 8728 if (!ps.isSharedUser()) { 8729 origPermissions = new PermissionsState(permissionsState); 8730 permissionsState.reset(); 8731 } else { 8732 // We need to know only about runtime permission changes since the 8733 // calling code always writes the install permissions state but 8734 // the runtime ones are written only if changed. The only cases of 8735 // changed runtime permissions here are promotion of an install to 8736 // runtime and revocation of a runtime from a shared user. 8737 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 8738 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 8739 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 8740 runtimePermissionsRevoked = true; 8741 } 8742 } 8743 } 8744 8745 permissionsState.setGlobalGids(mGlobalGids); 8746 8747 final int N = pkg.requestedPermissions.size(); 8748 for (int i=0; i<N; i++) { 8749 final String name = pkg.requestedPermissions.get(i); 8750 final BasePermission bp = mSettings.mPermissions.get(name); 8751 8752 if (DEBUG_INSTALL) { 8753 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8754 } 8755 8756 if (bp == null || bp.packageSetting == null) { 8757 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8758 Slog.w(TAG, "Unknown permission " + name 8759 + " in package " + pkg.packageName); 8760 } 8761 continue; 8762 } 8763 8764 final String perm = bp.name; 8765 boolean allowedSig = false; 8766 int grant = GRANT_DENIED; 8767 8768 // Keep track of app op permissions. 8769 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8770 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8771 if (pkgs == null) { 8772 pkgs = new ArraySet<>(); 8773 mAppOpPermissionPackages.put(bp.name, pkgs); 8774 } 8775 pkgs.add(pkg.packageName); 8776 } 8777 8778 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8779 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 8780 >= Build.VERSION_CODES.M; 8781 switch (level) { 8782 case PermissionInfo.PROTECTION_NORMAL: { 8783 // For all apps normal permissions are install time ones. 8784 grant = GRANT_INSTALL; 8785 } break; 8786 8787 case PermissionInfo.PROTECTION_DANGEROUS: { 8788 // If a permission review is required for legacy apps we represent 8789 // their permissions as always granted runtime ones since we need 8790 // to keep the review required permission flag per user while an 8791 // install permission's state is shared across all users. 8792 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 8793 // For legacy apps dangerous permissions are install time ones. 8794 grant = GRANT_INSTALL; 8795 } else if (origPermissions.hasInstallPermission(bp.name)) { 8796 // For legacy apps that became modern, install becomes runtime. 8797 grant = GRANT_UPGRADE; 8798 } else if (mPromoteSystemApps 8799 && isSystemApp(ps) 8800 && mExistingSystemPackages.contains(ps.name)) { 8801 // For legacy system apps, install becomes runtime. 8802 // We cannot check hasInstallPermission() for system apps since those 8803 // permissions were granted implicitly and not persisted pre-M. 8804 grant = GRANT_UPGRADE; 8805 } else { 8806 // For modern apps keep runtime permissions unchanged. 8807 grant = GRANT_RUNTIME; 8808 } 8809 } break; 8810 8811 case PermissionInfo.PROTECTION_SIGNATURE: { 8812 // For all apps signature permissions are install time ones. 8813 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8814 if (allowedSig) { 8815 grant = GRANT_INSTALL; 8816 } 8817 } break; 8818 } 8819 8820 if (DEBUG_INSTALL) { 8821 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8822 } 8823 8824 if (grant != GRANT_DENIED) { 8825 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8826 // If this is an existing, non-system package, then 8827 // we can't add any new permissions to it. 8828 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8829 // Except... if this is a permission that was added 8830 // to the platform (note: need to only do this when 8831 // updating the platform). 8832 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8833 grant = GRANT_DENIED; 8834 } 8835 } 8836 } 8837 8838 switch (grant) { 8839 case GRANT_INSTALL: { 8840 // Revoke this as runtime permission to handle the case of 8841 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 8842 for (int userId : UserManagerService.getInstance().getUserIds()) { 8843 if (origPermissions.getRuntimePermissionState( 8844 bp.name, userId) != null) { 8845 // Revoke the runtime permission and clear the flags. 8846 origPermissions.revokeRuntimePermission(bp, userId); 8847 origPermissions.updatePermissionFlags(bp, userId, 8848 PackageManager.MASK_PERMISSION_FLAGS, 0); 8849 // If we revoked a permission permission, we have to write. 8850 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8851 changedRuntimePermissionUserIds, userId); 8852 } 8853 } 8854 // Grant an install permission. 8855 if (permissionsState.grantInstallPermission(bp) != 8856 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8857 changedInstallPermission = true; 8858 } 8859 } break; 8860 8861 case GRANT_RUNTIME: { 8862 // Grant previously granted runtime permissions. 8863 for (int userId : UserManagerService.getInstance().getUserIds()) { 8864 PermissionState permissionState = origPermissions 8865 .getRuntimePermissionState(bp.name, userId); 8866 int flags = permissionState != null 8867 ? permissionState.getFlags() : 0; 8868 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8869 if (permissionsState.grantRuntimePermission(bp, userId) == 8870 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8871 // If we cannot put the permission as it was, we have to write. 8872 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8873 changedRuntimePermissionUserIds, userId); 8874 } 8875 // If the app supports runtime permissions no need for a review. 8876 if (Build.PERMISSIONS_REVIEW_REQUIRED 8877 && appSupportsRuntimePermissions 8878 && (flags & PackageManager 8879 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 8880 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 8881 // Since we changed the flags, we have to write. 8882 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8883 changedRuntimePermissionUserIds, userId); 8884 } 8885 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 8886 && !appSupportsRuntimePermissions) { 8887 // For legacy apps that need a permission review, every new 8888 // runtime permission is granted but it is pending a review. 8889 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 8890 permissionsState.grantRuntimePermission(bp, userId); 8891 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 8892 // We changed the permission and flags, hence have to write. 8893 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8894 changedRuntimePermissionUserIds, userId); 8895 } 8896 } 8897 // Propagate the permission flags. 8898 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8899 } 8900 } break; 8901 8902 case GRANT_UPGRADE: { 8903 // Grant runtime permissions for a previously held install permission. 8904 PermissionState permissionState = origPermissions 8905 .getInstallPermissionState(bp.name); 8906 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8907 8908 if (origPermissions.revokeInstallPermission(bp) 8909 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8910 // We will be transferring the permission flags, so clear them. 8911 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8912 PackageManager.MASK_PERMISSION_FLAGS, 0); 8913 changedInstallPermission = true; 8914 } 8915 8916 // If the permission is not to be promoted to runtime we ignore it and 8917 // also its other flags as they are not applicable to install permissions. 8918 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8919 for (int userId : currentUserIds) { 8920 if (permissionsState.grantRuntimePermission(bp, userId) != 8921 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8922 // Transfer the permission flags. 8923 permissionsState.updatePermissionFlags(bp, userId, 8924 flags, flags); 8925 // If we granted the permission, we have to write. 8926 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8927 changedRuntimePermissionUserIds, userId); 8928 } 8929 } 8930 } 8931 } break; 8932 8933 default: { 8934 if (packageOfInterest == null 8935 || packageOfInterest.equals(pkg.packageName)) { 8936 Slog.w(TAG, "Not granting permission " + perm 8937 + " to package " + pkg.packageName 8938 + " because it was previously installed without"); 8939 } 8940 } break; 8941 } 8942 } else { 8943 if (permissionsState.revokeInstallPermission(bp) != 8944 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8945 // Also drop the permission flags. 8946 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8947 PackageManager.MASK_PERMISSION_FLAGS, 0); 8948 changedInstallPermission = true; 8949 Slog.i(TAG, "Un-granting permission " + perm 8950 + " from package " + pkg.packageName 8951 + " (protectionLevel=" + bp.protectionLevel 8952 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8953 + ")"); 8954 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8955 // Don't print warning for app op permissions, since it is fine for them 8956 // not to be granted, there is a UI for the user to decide. 8957 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8958 Slog.w(TAG, "Not granting permission " + perm 8959 + " to package " + pkg.packageName 8960 + " (protectionLevel=" + bp.protectionLevel 8961 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8962 + ")"); 8963 } 8964 } 8965 } 8966 } 8967 8968 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8969 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8970 // This is the first that we have heard about this package, so the 8971 // permissions we have now selected are fixed until explicitly 8972 // changed. 8973 ps.installPermissionsFixed = true; 8974 } 8975 8976 // Persist the runtime permissions state for users with changes. If permissions 8977 // were revoked because no app in the shared user declares them we have to 8978 // write synchronously to avoid losing runtime permissions state. 8979 for (int userId : changedRuntimePermissionUserIds) { 8980 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 8981 } 8982 8983 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8984 } 8985 8986 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8987 boolean allowed = false; 8988 final int NP = PackageParser.NEW_PERMISSIONS.length; 8989 for (int ip=0; ip<NP; ip++) { 8990 final PackageParser.NewPermissionInfo npi 8991 = PackageParser.NEW_PERMISSIONS[ip]; 8992 if (npi.name.equals(perm) 8993 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8994 allowed = true; 8995 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8996 + pkg.packageName); 8997 break; 8998 } 8999 } 9000 return allowed; 9001 } 9002 9003 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9004 BasePermission bp, PermissionsState origPermissions) { 9005 boolean allowed; 9006 allowed = (compareSignatures( 9007 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9008 == PackageManager.SIGNATURE_MATCH) 9009 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9010 == PackageManager.SIGNATURE_MATCH); 9011 if (!allowed && (bp.protectionLevel 9012 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9013 if (isSystemApp(pkg)) { 9014 // For updated system applications, a system permission 9015 // is granted only if it had been defined by the original application. 9016 if (pkg.isUpdatedSystemApp()) { 9017 final PackageSetting sysPs = mSettings 9018 .getDisabledSystemPkgLPr(pkg.packageName); 9019 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 9020 // If the original was granted this permission, we take 9021 // that grant decision as read and propagate it to the 9022 // update. 9023 if (sysPs.isPrivileged()) { 9024 allowed = true; 9025 } 9026 } else { 9027 // The system apk may have been updated with an older 9028 // version of the one on the data partition, but which 9029 // granted a new system permission that it didn't have 9030 // before. In this case we do want to allow the app to 9031 // now get the new permission if the ancestral apk is 9032 // privileged to get it. 9033 if (sysPs.pkg != null && sysPs.isPrivileged()) { 9034 for (int j=0; 9035 j<sysPs.pkg.requestedPermissions.size(); j++) { 9036 if (perm.equals( 9037 sysPs.pkg.requestedPermissions.get(j))) { 9038 allowed = true; 9039 break; 9040 } 9041 } 9042 } 9043 } 9044 } else { 9045 allowed = isPrivilegedApp(pkg); 9046 } 9047 } 9048 } 9049 if (!allowed) { 9050 if (!allowed && (bp.protectionLevel 9051 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9052 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9053 // If this was a previously normal/dangerous permission that got moved 9054 // to a system permission as part of the runtime permission redesign, then 9055 // we still want to blindly grant it to old apps. 9056 allowed = true; 9057 } 9058 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9059 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9060 // If this permission is to be granted to the system installer and 9061 // this app is an installer, then it gets the permission. 9062 allowed = true; 9063 } 9064 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9065 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9066 // If this permission is to be granted to the system verifier and 9067 // this app is a verifier, then it gets the permission. 9068 allowed = true; 9069 } 9070 if (!allowed && (bp.protectionLevel 9071 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9072 && isSystemApp(pkg)) { 9073 // Any pre-installed system app is allowed to get this permission. 9074 allowed = true; 9075 } 9076 if (!allowed && (bp.protectionLevel 9077 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9078 // For development permissions, a development permission 9079 // is granted only if it was already granted. 9080 allowed = origPermissions.hasInstallPermission(perm); 9081 } 9082 } 9083 return allowed; 9084 } 9085 9086 final class ActivityIntentResolver 9087 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9088 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9089 boolean defaultOnly, int userId) { 9090 if (!sUserManager.exists(userId)) return null; 9091 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9092 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9093 } 9094 9095 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9096 int userId) { 9097 if (!sUserManager.exists(userId)) return null; 9098 mFlags = flags; 9099 return super.queryIntent(intent, resolvedType, 9100 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9101 } 9102 9103 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9104 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9105 if (!sUserManager.exists(userId)) return null; 9106 if (packageActivities == null) { 9107 return null; 9108 } 9109 mFlags = flags; 9110 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9111 final int N = packageActivities.size(); 9112 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9113 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9114 9115 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9116 for (int i = 0; i < N; ++i) { 9117 intentFilters = packageActivities.get(i).intents; 9118 if (intentFilters != null && intentFilters.size() > 0) { 9119 PackageParser.ActivityIntentInfo[] array = 9120 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9121 intentFilters.toArray(array); 9122 listCut.add(array); 9123 } 9124 } 9125 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9126 } 9127 9128 public final void addActivity(PackageParser.Activity a, String type) { 9129 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 9130 mActivities.put(a.getComponentName(), a); 9131 if (DEBUG_SHOW_INFO) 9132 Log.v( 9133 TAG, " " + type + " " + 9134 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 9135 if (DEBUG_SHOW_INFO) 9136 Log.v(TAG, " Class=" + a.info.name); 9137 final int NI = a.intents.size(); 9138 for (int j=0; j<NI; j++) { 9139 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9140 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 9141 intent.setPriority(0); 9142 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 9143 + a.className + " with priority > 0, forcing to 0"); 9144 } 9145 if (DEBUG_SHOW_INFO) { 9146 Log.v(TAG, " IntentFilter:"); 9147 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9148 } 9149 if (!intent.debugCheck()) { 9150 Log.w(TAG, "==> For Activity " + a.info.name); 9151 } 9152 addFilter(intent); 9153 } 9154 } 9155 9156 public final void removeActivity(PackageParser.Activity a, String type) { 9157 mActivities.remove(a.getComponentName()); 9158 if (DEBUG_SHOW_INFO) { 9159 Log.v(TAG, " " + type + " " 9160 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 9161 : a.info.name) + ":"); 9162 Log.v(TAG, " Class=" + a.info.name); 9163 } 9164 final int NI = a.intents.size(); 9165 for (int j=0; j<NI; j++) { 9166 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9167 if (DEBUG_SHOW_INFO) { 9168 Log.v(TAG, " IntentFilter:"); 9169 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9170 } 9171 removeFilter(intent); 9172 } 9173 } 9174 9175 @Override 9176 protected boolean allowFilterResult( 9177 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 9178 ActivityInfo filterAi = filter.activity.info; 9179 for (int i=dest.size()-1; i>=0; i--) { 9180 ActivityInfo destAi = dest.get(i).activityInfo; 9181 if (destAi.name == filterAi.name 9182 && destAi.packageName == filterAi.packageName) { 9183 return false; 9184 } 9185 } 9186 return true; 9187 } 9188 9189 @Override 9190 protected ActivityIntentInfo[] newArray(int size) { 9191 return new ActivityIntentInfo[size]; 9192 } 9193 9194 @Override 9195 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 9196 if (!sUserManager.exists(userId)) return true; 9197 PackageParser.Package p = filter.activity.owner; 9198 if (p != null) { 9199 PackageSetting ps = (PackageSetting)p.mExtras; 9200 if (ps != null) { 9201 // System apps are never considered stopped for purposes of 9202 // filtering, because there may be no way for the user to 9203 // actually re-launch them. 9204 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 9205 && ps.getStopped(userId); 9206 } 9207 } 9208 return false; 9209 } 9210 9211 @Override 9212 protected boolean isPackageForFilter(String packageName, 9213 PackageParser.ActivityIntentInfo info) { 9214 return packageName.equals(info.activity.owner.packageName); 9215 } 9216 9217 @Override 9218 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 9219 int match, int userId) { 9220 if (!sUserManager.exists(userId)) return null; 9221 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 9222 return null; 9223 } 9224 final PackageParser.Activity activity = info.activity; 9225 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 9226 if (ps == null) { 9227 return null; 9228 } 9229 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 9230 ps.readUserState(userId), userId); 9231 if (ai == null) { 9232 return null; 9233 } 9234 final ResolveInfo res = new ResolveInfo(); 9235 res.activityInfo = ai; 9236 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9237 res.filter = info; 9238 } 9239 if (info != null) { 9240 res.handleAllWebDataURI = info.handleAllWebDataURI(); 9241 } 9242 res.priority = info.getPriority(); 9243 res.preferredOrder = activity.owner.mPreferredOrder; 9244 //System.out.println("Result: " + res.activityInfo.className + 9245 // " = " + res.priority); 9246 res.match = match; 9247 res.isDefault = info.hasDefault; 9248 res.labelRes = info.labelRes; 9249 res.nonLocalizedLabel = info.nonLocalizedLabel; 9250 if (userNeedsBadging(userId)) { 9251 res.noResourceId = true; 9252 } else { 9253 res.icon = info.icon; 9254 } 9255 res.iconResourceId = info.icon; 9256 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9257 return res; 9258 } 9259 9260 @Override 9261 protected void sortResults(List<ResolveInfo> results) { 9262 Collections.sort(results, mResolvePrioritySorter); 9263 } 9264 9265 @Override 9266 protected void dumpFilter(PrintWriter out, String prefix, 9267 PackageParser.ActivityIntentInfo filter) { 9268 out.print(prefix); out.print( 9269 Integer.toHexString(System.identityHashCode(filter.activity))); 9270 out.print(' '); 9271 filter.activity.printComponentShortName(out); 9272 out.print(" filter "); 9273 out.println(Integer.toHexString(System.identityHashCode(filter))); 9274 } 9275 9276 @Override 9277 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9278 return filter.activity; 9279 } 9280 9281 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9282 PackageParser.Activity activity = (PackageParser.Activity)label; 9283 out.print(prefix); out.print( 9284 Integer.toHexString(System.identityHashCode(activity))); 9285 out.print(' '); 9286 activity.printComponentShortName(out); 9287 if (count > 1) { 9288 out.print(" ("); out.print(count); out.print(" filters)"); 9289 } 9290 out.println(); 9291 } 9292 9293// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9294// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9295// final List<ResolveInfo> retList = Lists.newArrayList(); 9296// while (i.hasNext()) { 9297// final ResolveInfo resolveInfo = i.next(); 9298// if (isEnabledLP(resolveInfo.activityInfo)) { 9299// retList.add(resolveInfo); 9300// } 9301// } 9302// return retList; 9303// } 9304 9305 // Keys are String (activity class name), values are Activity. 9306 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9307 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9308 private int mFlags; 9309 } 9310 9311 private final class ServiceIntentResolver 9312 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9313 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9314 boolean defaultOnly, int userId) { 9315 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9316 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9317 } 9318 9319 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9320 int userId) { 9321 if (!sUserManager.exists(userId)) return null; 9322 mFlags = flags; 9323 return super.queryIntent(intent, resolvedType, 9324 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9325 } 9326 9327 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9328 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9329 if (!sUserManager.exists(userId)) return null; 9330 if (packageServices == null) { 9331 return null; 9332 } 9333 mFlags = flags; 9334 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9335 final int N = packageServices.size(); 9336 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9337 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9338 9339 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9340 for (int i = 0; i < N; ++i) { 9341 intentFilters = packageServices.get(i).intents; 9342 if (intentFilters != null && intentFilters.size() > 0) { 9343 PackageParser.ServiceIntentInfo[] array = 9344 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9345 intentFilters.toArray(array); 9346 listCut.add(array); 9347 } 9348 } 9349 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9350 } 9351 9352 public final void addService(PackageParser.Service s) { 9353 mServices.put(s.getComponentName(), s); 9354 if (DEBUG_SHOW_INFO) { 9355 Log.v(TAG, " " 9356 + (s.info.nonLocalizedLabel != null 9357 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9358 Log.v(TAG, " Class=" + s.info.name); 9359 } 9360 final int NI = s.intents.size(); 9361 int j; 9362 for (j=0; j<NI; j++) { 9363 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9364 if (DEBUG_SHOW_INFO) { 9365 Log.v(TAG, " IntentFilter:"); 9366 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9367 } 9368 if (!intent.debugCheck()) { 9369 Log.w(TAG, "==> For Service " + s.info.name); 9370 } 9371 addFilter(intent); 9372 } 9373 } 9374 9375 public final void removeService(PackageParser.Service s) { 9376 mServices.remove(s.getComponentName()); 9377 if (DEBUG_SHOW_INFO) { 9378 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9379 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9380 Log.v(TAG, " Class=" + s.info.name); 9381 } 9382 final int NI = s.intents.size(); 9383 int j; 9384 for (j=0; j<NI; j++) { 9385 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9386 if (DEBUG_SHOW_INFO) { 9387 Log.v(TAG, " IntentFilter:"); 9388 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9389 } 9390 removeFilter(intent); 9391 } 9392 } 9393 9394 @Override 9395 protected boolean allowFilterResult( 9396 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9397 ServiceInfo filterSi = filter.service.info; 9398 for (int i=dest.size()-1; i>=0; i--) { 9399 ServiceInfo destAi = dest.get(i).serviceInfo; 9400 if (destAi.name == filterSi.name 9401 && destAi.packageName == filterSi.packageName) { 9402 return false; 9403 } 9404 } 9405 return true; 9406 } 9407 9408 @Override 9409 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9410 return new PackageParser.ServiceIntentInfo[size]; 9411 } 9412 9413 @Override 9414 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9415 if (!sUserManager.exists(userId)) return true; 9416 PackageParser.Package p = filter.service.owner; 9417 if (p != null) { 9418 PackageSetting ps = (PackageSetting)p.mExtras; 9419 if (ps != null) { 9420 // System apps are never considered stopped for purposes of 9421 // filtering, because there may be no way for the user to 9422 // actually re-launch them. 9423 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9424 && ps.getStopped(userId); 9425 } 9426 } 9427 return false; 9428 } 9429 9430 @Override 9431 protected boolean isPackageForFilter(String packageName, 9432 PackageParser.ServiceIntentInfo info) { 9433 return packageName.equals(info.service.owner.packageName); 9434 } 9435 9436 @Override 9437 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9438 int match, int userId) { 9439 if (!sUserManager.exists(userId)) return null; 9440 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9441 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 9442 return null; 9443 } 9444 final PackageParser.Service service = info.service; 9445 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9446 if (ps == null) { 9447 return null; 9448 } 9449 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9450 ps.readUserState(userId), userId); 9451 if (si == null) { 9452 return null; 9453 } 9454 final ResolveInfo res = new ResolveInfo(); 9455 res.serviceInfo = si; 9456 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9457 res.filter = filter; 9458 } 9459 res.priority = info.getPriority(); 9460 res.preferredOrder = service.owner.mPreferredOrder; 9461 res.match = match; 9462 res.isDefault = info.hasDefault; 9463 res.labelRes = info.labelRes; 9464 res.nonLocalizedLabel = info.nonLocalizedLabel; 9465 res.icon = info.icon; 9466 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9467 return res; 9468 } 9469 9470 @Override 9471 protected void sortResults(List<ResolveInfo> results) { 9472 Collections.sort(results, mResolvePrioritySorter); 9473 } 9474 9475 @Override 9476 protected void dumpFilter(PrintWriter out, String prefix, 9477 PackageParser.ServiceIntentInfo filter) { 9478 out.print(prefix); out.print( 9479 Integer.toHexString(System.identityHashCode(filter.service))); 9480 out.print(' '); 9481 filter.service.printComponentShortName(out); 9482 out.print(" filter "); 9483 out.println(Integer.toHexString(System.identityHashCode(filter))); 9484 } 9485 9486 @Override 9487 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9488 return filter.service; 9489 } 9490 9491 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9492 PackageParser.Service service = (PackageParser.Service)label; 9493 out.print(prefix); out.print( 9494 Integer.toHexString(System.identityHashCode(service))); 9495 out.print(' '); 9496 service.printComponentShortName(out); 9497 if (count > 1) { 9498 out.print(" ("); out.print(count); out.print(" filters)"); 9499 } 9500 out.println(); 9501 } 9502 9503// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9504// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9505// final List<ResolveInfo> retList = Lists.newArrayList(); 9506// while (i.hasNext()) { 9507// final ResolveInfo resolveInfo = (ResolveInfo) i; 9508// if (isEnabledLP(resolveInfo.serviceInfo)) { 9509// retList.add(resolveInfo); 9510// } 9511// } 9512// return retList; 9513// } 9514 9515 // Keys are String (activity class name), values are Activity. 9516 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9517 = new ArrayMap<ComponentName, PackageParser.Service>(); 9518 private int mFlags; 9519 }; 9520 9521 private final class ProviderIntentResolver 9522 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9523 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9524 boolean defaultOnly, int userId) { 9525 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9526 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9527 } 9528 9529 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9530 int userId) { 9531 if (!sUserManager.exists(userId)) 9532 return null; 9533 mFlags = flags; 9534 return super.queryIntent(intent, resolvedType, 9535 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9536 } 9537 9538 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9539 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9540 if (!sUserManager.exists(userId)) 9541 return null; 9542 if (packageProviders == null) { 9543 return null; 9544 } 9545 mFlags = flags; 9546 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9547 final int N = packageProviders.size(); 9548 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9549 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9550 9551 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9552 for (int i = 0; i < N; ++i) { 9553 intentFilters = packageProviders.get(i).intents; 9554 if (intentFilters != null && intentFilters.size() > 0) { 9555 PackageParser.ProviderIntentInfo[] array = 9556 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9557 intentFilters.toArray(array); 9558 listCut.add(array); 9559 } 9560 } 9561 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9562 } 9563 9564 public final void addProvider(PackageParser.Provider p) { 9565 if (mProviders.containsKey(p.getComponentName())) { 9566 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9567 return; 9568 } 9569 9570 mProviders.put(p.getComponentName(), p); 9571 if (DEBUG_SHOW_INFO) { 9572 Log.v(TAG, " " 9573 + (p.info.nonLocalizedLabel != null 9574 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9575 Log.v(TAG, " Class=" + p.info.name); 9576 } 9577 final int NI = p.intents.size(); 9578 int j; 9579 for (j = 0; j < NI; j++) { 9580 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9581 if (DEBUG_SHOW_INFO) { 9582 Log.v(TAG, " IntentFilter:"); 9583 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9584 } 9585 if (!intent.debugCheck()) { 9586 Log.w(TAG, "==> For Provider " + p.info.name); 9587 } 9588 addFilter(intent); 9589 } 9590 } 9591 9592 public final void removeProvider(PackageParser.Provider p) { 9593 mProviders.remove(p.getComponentName()); 9594 if (DEBUG_SHOW_INFO) { 9595 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9596 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9597 Log.v(TAG, " Class=" + p.info.name); 9598 } 9599 final int NI = p.intents.size(); 9600 int j; 9601 for (j = 0; j < NI; j++) { 9602 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9603 if (DEBUG_SHOW_INFO) { 9604 Log.v(TAG, " IntentFilter:"); 9605 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9606 } 9607 removeFilter(intent); 9608 } 9609 } 9610 9611 @Override 9612 protected boolean allowFilterResult( 9613 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9614 ProviderInfo filterPi = filter.provider.info; 9615 for (int i = dest.size() - 1; i >= 0; i--) { 9616 ProviderInfo destPi = dest.get(i).providerInfo; 9617 if (destPi.name == filterPi.name 9618 && destPi.packageName == filterPi.packageName) { 9619 return false; 9620 } 9621 } 9622 return true; 9623 } 9624 9625 @Override 9626 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9627 return new PackageParser.ProviderIntentInfo[size]; 9628 } 9629 9630 @Override 9631 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9632 if (!sUserManager.exists(userId)) 9633 return true; 9634 PackageParser.Package p = filter.provider.owner; 9635 if (p != null) { 9636 PackageSetting ps = (PackageSetting) p.mExtras; 9637 if (ps != null) { 9638 // System apps are never considered stopped for purposes of 9639 // filtering, because there may be no way for the user to 9640 // actually re-launch them. 9641 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9642 && ps.getStopped(userId); 9643 } 9644 } 9645 return false; 9646 } 9647 9648 @Override 9649 protected boolean isPackageForFilter(String packageName, 9650 PackageParser.ProviderIntentInfo info) { 9651 return packageName.equals(info.provider.owner.packageName); 9652 } 9653 9654 @Override 9655 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9656 int match, int userId) { 9657 if (!sUserManager.exists(userId)) 9658 return null; 9659 final PackageParser.ProviderIntentInfo info = filter; 9660 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 9661 return null; 9662 } 9663 final PackageParser.Provider provider = info.provider; 9664 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9665 if (ps == null) { 9666 return null; 9667 } 9668 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9669 ps.readUserState(userId), userId); 9670 if (pi == null) { 9671 return null; 9672 } 9673 final ResolveInfo res = new ResolveInfo(); 9674 res.providerInfo = pi; 9675 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9676 res.filter = filter; 9677 } 9678 res.priority = info.getPriority(); 9679 res.preferredOrder = provider.owner.mPreferredOrder; 9680 res.match = match; 9681 res.isDefault = info.hasDefault; 9682 res.labelRes = info.labelRes; 9683 res.nonLocalizedLabel = info.nonLocalizedLabel; 9684 res.icon = info.icon; 9685 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9686 return res; 9687 } 9688 9689 @Override 9690 protected void sortResults(List<ResolveInfo> results) { 9691 Collections.sort(results, mResolvePrioritySorter); 9692 } 9693 9694 @Override 9695 protected void dumpFilter(PrintWriter out, String prefix, 9696 PackageParser.ProviderIntentInfo filter) { 9697 out.print(prefix); 9698 out.print( 9699 Integer.toHexString(System.identityHashCode(filter.provider))); 9700 out.print(' '); 9701 filter.provider.printComponentShortName(out); 9702 out.print(" filter "); 9703 out.println(Integer.toHexString(System.identityHashCode(filter))); 9704 } 9705 9706 @Override 9707 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9708 return filter.provider; 9709 } 9710 9711 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9712 PackageParser.Provider provider = (PackageParser.Provider)label; 9713 out.print(prefix); out.print( 9714 Integer.toHexString(System.identityHashCode(provider))); 9715 out.print(' '); 9716 provider.printComponentShortName(out); 9717 if (count > 1) { 9718 out.print(" ("); out.print(count); out.print(" filters)"); 9719 } 9720 out.println(); 9721 } 9722 9723 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9724 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9725 private int mFlags; 9726 } 9727 9728 private static final class EphemeralIntentResolver 9729 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 9730 @Override 9731 protected EphemeralResolveIntentInfo[] newArray(int size) { 9732 return new EphemeralResolveIntentInfo[size]; 9733 } 9734 9735 @Override 9736 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 9737 return true; 9738 } 9739 9740 @Override 9741 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 9742 int userId) { 9743 if (!sUserManager.exists(userId)) { 9744 return null; 9745 } 9746 return info.getEphemeralResolveInfo(); 9747 } 9748 } 9749 9750 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9751 new Comparator<ResolveInfo>() { 9752 public int compare(ResolveInfo r1, ResolveInfo r2) { 9753 int v1 = r1.priority; 9754 int v2 = r2.priority; 9755 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9756 if (v1 != v2) { 9757 return (v1 > v2) ? -1 : 1; 9758 } 9759 v1 = r1.preferredOrder; 9760 v2 = r2.preferredOrder; 9761 if (v1 != v2) { 9762 return (v1 > v2) ? -1 : 1; 9763 } 9764 if (r1.isDefault != r2.isDefault) { 9765 return r1.isDefault ? -1 : 1; 9766 } 9767 v1 = r1.match; 9768 v2 = r2.match; 9769 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9770 if (v1 != v2) { 9771 return (v1 > v2) ? -1 : 1; 9772 } 9773 if (r1.system != r2.system) { 9774 return r1.system ? -1 : 1; 9775 } 9776 if (r1.activityInfo != null) { 9777 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 9778 } 9779 if (r1.serviceInfo != null) { 9780 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 9781 } 9782 if (r1.providerInfo != null) { 9783 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 9784 } 9785 return 0; 9786 } 9787 }; 9788 9789 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9790 new Comparator<ProviderInfo>() { 9791 public int compare(ProviderInfo p1, ProviderInfo p2) { 9792 final int v1 = p1.initOrder; 9793 final int v2 = p2.initOrder; 9794 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9795 } 9796 }; 9797 9798 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 9799 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 9800 final int[] userIds) { 9801 mHandler.post(new Runnable() { 9802 @Override 9803 public void run() { 9804 try { 9805 final IActivityManager am = ActivityManagerNative.getDefault(); 9806 if (am == null) return; 9807 final int[] resolvedUserIds; 9808 if (userIds == null) { 9809 resolvedUserIds = am.getRunningUserIds(); 9810 } else { 9811 resolvedUserIds = userIds; 9812 } 9813 for (int id : resolvedUserIds) { 9814 final Intent intent = new Intent(action, 9815 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9816 if (extras != null) { 9817 intent.putExtras(extras); 9818 } 9819 if (targetPkg != null) { 9820 intent.setPackage(targetPkg); 9821 } 9822 // Modify the UID when posting to other users 9823 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9824 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9825 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9826 intent.putExtra(Intent.EXTRA_UID, uid); 9827 } 9828 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9829 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 9830 if (DEBUG_BROADCASTS) { 9831 RuntimeException here = new RuntimeException("here"); 9832 here.fillInStackTrace(); 9833 Slog.d(TAG, "Sending to user " + id + ": " 9834 + intent.toShortString(false, true, false, false) 9835 + " " + intent.getExtras(), here); 9836 } 9837 am.broadcastIntent(null, intent, null, finishedReceiver, 9838 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9839 null, finishedReceiver != null, false, id); 9840 } 9841 } catch (RemoteException ex) { 9842 } 9843 } 9844 }); 9845 } 9846 9847 /** 9848 * Check if the external storage media is available. This is true if there 9849 * is a mounted external storage medium or if the external storage is 9850 * emulated. 9851 */ 9852 private boolean isExternalMediaAvailable() { 9853 return mMediaMounted || Environment.isExternalStorageEmulated(); 9854 } 9855 9856 @Override 9857 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9858 // writer 9859 synchronized (mPackages) { 9860 if (!isExternalMediaAvailable()) { 9861 // If the external storage is no longer mounted at this point, 9862 // the caller may not have been able to delete all of this 9863 // packages files and can not delete any more. Bail. 9864 return null; 9865 } 9866 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9867 if (lastPackage != null) { 9868 pkgs.remove(lastPackage); 9869 } 9870 if (pkgs.size() > 0) { 9871 return pkgs.get(0); 9872 } 9873 } 9874 return null; 9875 } 9876 9877 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9878 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9879 userId, andCode ? 1 : 0, packageName); 9880 if (mSystemReady) { 9881 msg.sendToTarget(); 9882 } else { 9883 if (mPostSystemReadyMessages == null) { 9884 mPostSystemReadyMessages = new ArrayList<>(); 9885 } 9886 mPostSystemReadyMessages.add(msg); 9887 } 9888 } 9889 9890 void startCleaningPackages() { 9891 // reader 9892 synchronized (mPackages) { 9893 if (!isExternalMediaAvailable()) { 9894 return; 9895 } 9896 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9897 return; 9898 } 9899 } 9900 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9901 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9902 IActivityManager am = ActivityManagerNative.getDefault(); 9903 if (am != null) { 9904 try { 9905 am.startService(null, intent, null, mContext.getOpPackageName(), 9906 UserHandle.USER_SYSTEM); 9907 } catch (RemoteException e) { 9908 } 9909 } 9910 } 9911 9912 @Override 9913 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9914 int installFlags, String installerPackageName, VerificationParams verificationParams, 9915 String packageAbiOverride) { 9916 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9917 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9918 } 9919 9920 @Override 9921 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9922 int installFlags, String installerPackageName, VerificationParams verificationParams, 9923 String packageAbiOverride, int userId) { 9924 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9925 9926 final int callingUid = Binder.getCallingUid(); 9927 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9928 9929 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9930 try { 9931 if (observer != null) { 9932 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9933 } 9934 } catch (RemoteException re) { 9935 } 9936 return; 9937 } 9938 9939 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9940 installFlags |= PackageManager.INSTALL_FROM_ADB; 9941 9942 } else { 9943 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9944 // about installerPackageName. 9945 9946 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9947 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9948 } 9949 9950 UserHandle user; 9951 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9952 user = UserHandle.ALL; 9953 } else { 9954 user = new UserHandle(userId); 9955 } 9956 9957 // Only system components can circumvent runtime permissions when installing. 9958 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9959 && mContext.checkCallingOrSelfPermission(Manifest.permission 9960 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9961 throw new SecurityException("You need the " 9962 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9963 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9964 } 9965 9966 verificationParams.setInstallerUid(callingUid); 9967 9968 final File originFile = new File(originPath); 9969 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9970 9971 final Message msg = mHandler.obtainMessage(INIT_COPY); 9972 final InstallParams params = new InstallParams(origin, null, observer, installFlags, 9973 installerPackageName, null, verificationParams, user, packageAbiOverride, null); 9974 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 9975 msg.obj = params; 9976 9977 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 9978 System.identityHashCode(msg.obj)); 9979 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9980 System.identityHashCode(msg.obj)); 9981 9982 mHandler.sendMessage(msg); 9983 } 9984 9985 void installStage(String packageName, File stagedDir, String stagedCid, 9986 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 9987 String installerPackageName, int installerUid, UserHandle user) { 9988 if (DEBUG_EPHEMERAL) { 9989 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 9990 Slog.d(TAG, "Ephemeral install of " + packageName); 9991 } 9992 } 9993 final VerificationParams verifParams = new VerificationParams( 9994 null, sessionParams.originatingUri, sessionParams.referrerUri, 9995 sessionParams.originatingUid); 9996 verifParams.setInstallerUid(installerUid); 9997 9998 final OriginInfo origin; 9999 if (stagedDir != null) { 10000 origin = OriginInfo.fromStagedFile(stagedDir); 10001 } else { 10002 origin = OriginInfo.fromStagedContainer(stagedCid); 10003 } 10004 10005 final Message msg = mHandler.obtainMessage(INIT_COPY); 10006 final InstallParams params = new InstallParams(origin, null, observer, 10007 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 10008 verifParams, user, sessionParams.abiOverride, 10009 sessionParams.grantedRuntimePermissions); 10010 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 10011 msg.obj = params; 10012 10013 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 10014 System.identityHashCode(msg.obj)); 10015 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10016 System.identityHashCode(msg.obj)); 10017 10018 mHandler.sendMessage(msg); 10019 } 10020 10021 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 10022 Bundle extras = new Bundle(1); 10023 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 10024 10025 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 10026 packageName, extras, 0, null, null, new int[] {userId}); 10027 try { 10028 IActivityManager am = ActivityManagerNative.getDefault(); 10029 final boolean isSystem = 10030 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 10031 if (isSystem && am.isUserRunning(userId, 0)) { 10032 // The just-installed/enabled app is bundled on the system, so presumed 10033 // to be able to run automatically without needing an explicit launch. 10034 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 10035 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 10036 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 10037 .setPackage(packageName); 10038 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 10039 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 10040 } 10041 } catch (RemoteException e) { 10042 // shouldn't happen 10043 Slog.w(TAG, "Unable to bootstrap installed package", e); 10044 } 10045 } 10046 10047 @Override 10048 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 10049 int userId) { 10050 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10051 PackageSetting pkgSetting; 10052 final int uid = Binder.getCallingUid(); 10053 enforceCrossUserPermission(uid, userId, true, true, 10054 "setApplicationHiddenSetting for user " + userId); 10055 10056 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 10057 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 10058 return false; 10059 } 10060 10061 long callingId = Binder.clearCallingIdentity(); 10062 try { 10063 boolean sendAdded = false; 10064 boolean sendRemoved = false; 10065 // writer 10066 synchronized (mPackages) { 10067 pkgSetting = mSettings.mPackages.get(packageName); 10068 if (pkgSetting == null) { 10069 return false; 10070 } 10071 if (pkgSetting.getHidden(userId) != hidden) { 10072 pkgSetting.setHidden(hidden, userId); 10073 mSettings.writePackageRestrictionsLPr(userId); 10074 if (hidden) { 10075 sendRemoved = true; 10076 } else { 10077 sendAdded = true; 10078 } 10079 } 10080 } 10081 if (sendAdded) { 10082 sendPackageAddedForUser(packageName, pkgSetting, userId); 10083 return true; 10084 } 10085 if (sendRemoved) { 10086 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 10087 "hiding pkg"); 10088 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 10089 return true; 10090 } 10091 } finally { 10092 Binder.restoreCallingIdentity(callingId); 10093 } 10094 return false; 10095 } 10096 10097 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 10098 int userId) { 10099 final PackageRemovedInfo info = new PackageRemovedInfo(); 10100 info.removedPackage = packageName; 10101 info.removedUsers = new int[] {userId}; 10102 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 10103 info.sendBroadcast(false, false, false); 10104 } 10105 10106 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 10107 if (pkgList.length > 0) { 10108 Bundle extras = new Bundle(1); 10109 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 10110 10111 sendPackageBroadcast( 10112 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 10113 : Intent.ACTION_PACKAGES_UNSUSPENDED, 10114 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 10115 new int[] {userId}); 10116 } 10117 } 10118 10119 /** 10120 * Returns true if application is not found or there was an error. Otherwise it returns 10121 * the hidden state of the package for the given user. 10122 */ 10123 @Override 10124 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 10125 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10126 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 10127 false, "getApplicationHidden for user " + userId); 10128 PackageSetting pkgSetting; 10129 long callingId = Binder.clearCallingIdentity(); 10130 try { 10131 // writer 10132 synchronized (mPackages) { 10133 pkgSetting = mSettings.mPackages.get(packageName); 10134 if (pkgSetting == null) { 10135 return true; 10136 } 10137 return pkgSetting.getHidden(userId); 10138 } 10139 } finally { 10140 Binder.restoreCallingIdentity(callingId); 10141 } 10142 } 10143 10144 /** 10145 * @hide 10146 */ 10147 @Override 10148 public int installExistingPackageAsUser(String packageName, int userId) { 10149 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 10150 null); 10151 PackageSetting pkgSetting; 10152 final int uid = Binder.getCallingUid(); 10153 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 10154 + userId); 10155 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10156 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 10157 } 10158 10159 long callingId = Binder.clearCallingIdentity(); 10160 try { 10161 boolean installed = false; 10162 10163 // writer 10164 synchronized (mPackages) { 10165 pkgSetting = mSettings.mPackages.get(packageName); 10166 if (pkgSetting == null) { 10167 return PackageManager.INSTALL_FAILED_INVALID_URI; 10168 } 10169 if (!pkgSetting.getInstalled(userId)) { 10170 pkgSetting.setInstalled(true, userId); 10171 pkgSetting.setHidden(false, userId); 10172 mSettings.writePackageRestrictionsLPr(userId); 10173 if (pkgSetting.pkg != null) { 10174 prepareAppDataAfterInstall(pkgSetting.pkg); 10175 } 10176 installed = true; 10177 } 10178 } 10179 10180 if (installed) { 10181 sendPackageAddedForUser(packageName, pkgSetting, userId); 10182 } 10183 } finally { 10184 Binder.restoreCallingIdentity(callingId); 10185 } 10186 10187 return PackageManager.INSTALL_SUCCEEDED; 10188 } 10189 10190 boolean isUserRestricted(int userId, String restrictionKey) { 10191 Bundle restrictions = sUserManager.getUserRestrictions(userId); 10192 if (restrictions.getBoolean(restrictionKey, false)) { 10193 Log.w(TAG, "User is restricted: " + restrictionKey); 10194 return true; 10195 } 10196 return false; 10197 } 10198 10199 @Override 10200 public boolean setPackageSuspendedAsUser(String packageName, boolean suspended, int userId) { 10201 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10202 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true, 10203 "setPackageSuspended for user " + userId); 10204 10205 // TODO: investigate and add more restrictions for suspending crucial packages. 10206 if (isPackageDeviceAdmin(packageName, userId)) { 10207 Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName 10208 + "\": has active device admin"); 10209 return false; 10210 } 10211 10212 long callingId = Binder.clearCallingIdentity(); 10213 try { 10214 boolean changed = false; 10215 boolean success = false; 10216 int appId = -1; 10217 synchronized (mPackages) { 10218 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10219 if (pkgSetting != null) { 10220 if (pkgSetting.getSuspended(userId) != suspended) { 10221 pkgSetting.setSuspended(suspended, userId); 10222 mSettings.writePackageRestrictionsLPr(userId); 10223 appId = pkgSetting.appId; 10224 changed = true; 10225 } 10226 success = true; 10227 } 10228 } 10229 10230 if (changed) { 10231 sendPackagesSuspendedForUser(new String[]{packageName}, userId, suspended); 10232 if (suspended) { 10233 killApplication(packageName, UserHandle.getUid(userId, appId), 10234 "suspending package"); 10235 } 10236 } 10237 return success; 10238 } finally { 10239 Binder.restoreCallingIdentity(callingId); 10240 } 10241 } 10242 10243 @Override 10244 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 10245 mContext.enforceCallingOrSelfPermission( 10246 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10247 "Only package verification agents can verify applications"); 10248 10249 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10250 final PackageVerificationResponse response = new PackageVerificationResponse( 10251 verificationCode, Binder.getCallingUid()); 10252 msg.arg1 = id; 10253 msg.obj = response; 10254 mHandler.sendMessage(msg); 10255 } 10256 10257 @Override 10258 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 10259 long millisecondsToDelay) { 10260 mContext.enforceCallingOrSelfPermission( 10261 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10262 "Only package verification agents can extend verification timeouts"); 10263 10264 final PackageVerificationState state = mPendingVerification.get(id); 10265 final PackageVerificationResponse response = new PackageVerificationResponse( 10266 verificationCodeAtTimeout, Binder.getCallingUid()); 10267 10268 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 10269 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 10270 } 10271 if (millisecondsToDelay < 0) { 10272 millisecondsToDelay = 0; 10273 } 10274 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 10275 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 10276 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 10277 } 10278 10279 if ((state != null) && !state.timeoutExtended()) { 10280 state.extendTimeout(); 10281 10282 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10283 msg.arg1 = id; 10284 msg.obj = response; 10285 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 10286 } 10287 } 10288 10289 private void broadcastPackageVerified(int verificationId, Uri packageUri, 10290 int verificationCode, UserHandle user) { 10291 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 10292 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 10293 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10294 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10295 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 10296 10297 mContext.sendBroadcastAsUser(intent, user, 10298 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 10299 } 10300 10301 private ComponentName matchComponentForVerifier(String packageName, 10302 List<ResolveInfo> receivers) { 10303 ActivityInfo targetReceiver = null; 10304 10305 final int NR = receivers.size(); 10306 for (int i = 0; i < NR; i++) { 10307 final ResolveInfo info = receivers.get(i); 10308 if (info.activityInfo == null) { 10309 continue; 10310 } 10311 10312 if (packageName.equals(info.activityInfo.packageName)) { 10313 targetReceiver = info.activityInfo; 10314 break; 10315 } 10316 } 10317 10318 if (targetReceiver == null) { 10319 return null; 10320 } 10321 10322 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 10323 } 10324 10325 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 10326 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 10327 if (pkgInfo.verifiers.length == 0) { 10328 return null; 10329 } 10330 10331 final int N = pkgInfo.verifiers.length; 10332 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 10333 for (int i = 0; i < N; i++) { 10334 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 10335 10336 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 10337 receivers); 10338 if (comp == null) { 10339 continue; 10340 } 10341 10342 final int verifierUid = getUidForVerifier(verifierInfo); 10343 if (verifierUid == -1) { 10344 continue; 10345 } 10346 10347 if (DEBUG_VERIFY) { 10348 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 10349 + " with the correct signature"); 10350 } 10351 sufficientVerifiers.add(comp); 10352 verificationState.addSufficientVerifier(verifierUid); 10353 } 10354 10355 return sufficientVerifiers; 10356 } 10357 10358 private int getUidForVerifier(VerifierInfo verifierInfo) { 10359 synchronized (mPackages) { 10360 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 10361 if (pkg == null) { 10362 return -1; 10363 } else if (pkg.mSignatures.length != 1) { 10364 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10365 + " has more than one signature; ignoring"); 10366 return -1; 10367 } 10368 10369 /* 10370 * If the public key of the package's signature does not match 10371 * our expected public key, then this is a different package and 10372 * we should skip. 10373 */ 10374 10375 final byte[] expectedPublicKey; 10376 try { 10377 final Signature verifierSig = pkg.mSignatures[0]; 10378 final PublicKey publicKey = verifierSig.getPublicKey(); 10379 expectedPublicKey = publicKey.getEncoded(); 10380 } catch (CertificateException e) { 10381 return -1; 10382 } 10383 10384 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 10385 10386 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 10387 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10388 + " does not have the expected public key; ignoring"); 10389 return -1; 10390 } 10391 10392 return pkg.applicationInfo.uid; 10393 } 10394 } 10395 10396 @Override 10397 public void finishPackageInstall(int token) { 10398 enforceSystemOrRoot("Only the system is allowed to finish installs"); 10399 10400 if (DEBUG_INSTALL) { 10401 Slog.v(TAG, "BM finishing package install for " + token); 10402 } 10403 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10404 10405 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10406 mHandler.sendMessage(msg); 10407 } 10408 10409 /** 10410 * Get the verification agent timeout. 10411 * 10412 * @return verification timeout in milliseconds 10413 */ 10414 private long getVerificationTimeout() { 10415 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 10416 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 10417 DEFAULT_VERIFICATION_TIMEOUT); 10418 } 10419 10420 /** 10421 * Get the default verification agent response code. 10422 * 10423 * @return default verification response code 10424 */ 10425 private int getDefaultVerificationResponse() { 10426 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10427 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 10428 DEFAULT_VERIFICATION_RESPONSE); 10429 } 10430 10431 /** 10432 * Check whether or not package verification has been enabled. 10433 * 10434 * @return true if verification should be performed 10435 */ 10436 private boolean isVerificationEnabled(int userId, int installFlags) { 10437 if (!DEFAULT_VERIFY_ENABLE) { 10438 return false; 10439 } 10440 // Ephemeral apps don't get the full verification treatment 10441 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10442 if (DEBUG_EPHEMERAL) { 10443 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 10444 } 10445 return false; 10446 } 10447 10448 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 10449 10450 // Check if installing from ADB 10451 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 10452 // Do not run verification in a test harness environment 10453 if (ActivityManager.isRunningInTestHarness()) { 10454 return false; 10455 } 10456 if (ensureVerifyAppsEnabled) { 10457 return true; 10458 } 10459 // Check if the developer does not want package verification for ADB installs 10460 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10461 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 10462 return false; 10463 } 10464 } 10465 10466 if (ensureVerifyAppsEnabled) { 10467 return true; 10468 } 10469 10470 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10471 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 10472 } 10473 10474 @Override 10475 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 10476 throws RemoteException { 10477 mContext.enforceCallingOrSelfPermission( 10478 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 10479 "Only intentfilter verification agents can verify applications"); 10480 10481 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 10482 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 10483 Binder.getCallingUid(), verificationCode, failedDomains); 10484 msg.arg1 = id; 10485 msg.obj = response; 10486 mHandler.sendMessage(msg); 10487 } 10488 10489 @Override 10490 public int getIntentVerificationStatus(String packageName, int userId) { 10491 synchronized (mPackages) { 10492 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10493 } 10494 } 10495 10496 @Override 10497 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10498 mContext.enforceCallingOrSelfPermission( 10499 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10500 10501 boolean result = false; 10502 synchronized (mPackages) { 10503 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10504 } 10505 if (result) { 10506 scheduleWritePackageRestrictionsLocked(userId); 10507 } 10508 return result; 10509 } 10510 10511 @Override 10512 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10513 synchronized (mPackages) { 10514 return mSettings.getIntentFilterVerificationsLPr(packageName); 10515 } 10516 } 10517 10518 @Override 10519 public List<IntentFilter> getAllIntentFilters(String packageName) { 10520 if (TextUtils.isEmpty(packageName)) { 10521 return Collections.<IntentFilter>emptyList(); 10522 } 10523 synchronized (mPackages) { 10524 PackageParser.Package pkg = mPackages.get(packageName); 10525 if (pkg == null || pkg.activities == null) { 10526 return Collections.<IntentFilter>emptyList(); 10527 } 10528 final int count = pkg.activities.size(); 10529 ArrayList<IntentFilter> result = new ArrayList<>(); 10530 for (int n=0; n<count; n++) { 10531 PackageParser.Activity activity = pkg.activities.get(n); 10532 if (activity.intents != null && activity.intents.size() > 0) { 10533 result.addAll(activity.intents); 10534 } 10535 } 10536 return result; 10537 } 10538 } 10539 10540 @Override 10541 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10542 mContext.enforceCallingOrSelfPermission( 10543 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10544 10545 synchronized (mPackages) { 10546 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10547 if (packageName != null) { 10548 result |= updateIntentVerificationStatus(packageName, 10549 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10550 userId); 10551 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10552 packageName, userId); 10553 } 10554 return result; 10555 } 10556 } 10557 10558 @Override 10559 public String getDefaultBrowserPackageName(int userId) { 10560 synchronized (mPackages) { 10561 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10562 } 10563 } 10564 10565 /** 10566 * Get the "allow unknown sources" setting. 10567 * 10568 * @return the current "allow unknown sources" setting 10569 */ 10570 private int getUnknownSourcesSettings() { 10571 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10572 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10573 -1); 10574 } 10575 10576 @Override 10577 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10578 final int uid = Binder.getCallingUid(); 10579 // writer 10580 synchronized (mPackages) { 10581 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10582 if (targetPackageSetting == null) { 10583 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10584 } 10585 10586 PackageSetting installerPackageSetting; 10587 if (installerPackageName != null) { 10588 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10589 if (installerPackageSetting == null) { 10590 throw new IllegalArgumentException("Unknown installer package: " 10591 + installerPackageName); 10592 } 10593 } else { 10594 installerPackageSetting = null; 10595 } 10596 10597 Signature[] callerSignature; 10598 Object obj = mSettings.getUserIdLPr(uid); 10599 if (obj != null) { 10600 if (obj instanceof SharedUserSetting) { 10601 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10602 } else if (obj instanceof PackageSetting) { 10603 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10604 } else { 10605 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10606 } 10607 } else { 10608 throw new SecurityException("Unknown calling UID: " + uid); 10609 } 10610 10611 // Verify: can't set installerPackageName to a package that is 10612 // not signed with the same cert as the caller. 10613 if (installerPackageSetting != null) { 10614 if (compareSignatures(callerSignature, 10615 installerPackageSetting.signatures.mSignatures) 10616 != PackageManager.SIGNATURE_MATCH) { 10617 throw new SecurityException( 10618 "Caller does not have same cert as new installer package " 10619 + installerPackageName); 10620 } 10621 } 10622 10623 // Verify: if target already has an installer package, it must 10624 // be signed with the same cert as the caller. 10625 if (targetPackageSetting.installerPackageName != null) { 10626 PackageSetting setting = mSettings.mPackages.get( 10627 targetPackageSetting.installerPackageName); 10628 // If the currently set package isn't valid, then it's always 10629 // okay to change it. 10630 if (setting != null) { 10631 if (compareSignatures(callerSignature, 10632 setting.signatures.mSignatures) 10633 != PackageManager.SIGNATURE_MATCH) { 10634 throw new SecurityException( 10635 "Caller does not have same cert as old installer package " 10636 + targetPackageSetting.installerPackageName); 10637 } 10638 } 10639 } 10640 10641 // Okay! 10642 targetPackageSetting.installerPackageName = installerPackageName; 10643 scheduleWriteSettingsLocked(); 10644 } 10645 } 10646 10647 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10648 // Queue up an async operation since the package installation may take a little while. 10649 mHandler.post(new Runnable() { 10650 public void run() { 10651 mHandler.removeCallbacks(this); 10652 // Result object to be returned 10653 PackageInstalledInfo res = new PackageInstalledInfo(); 10654 res.returnCode = currentStatus; 10655 res.uid = -1; 10656 res.pkg = null; 10657 res.removedInfo = new PackageRemovedInfo(); 10658 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10659 args.doPreInstall(res.returnCode); 10660 synchronized (mInstallLock) { 10661 installPackageTracedLI(args, res); 10662 } 10663 args.doPostInstall(res.returnCode, res.uid); 10664 } 10665 10666 // A restore should be performed at this point if (a) the install 10667 // succeeded, (b) the operation is not an update, and (c) the new 10668 // package has not opted out of backup participation. 10669 final boolean update = res.removedInfo.removedPackage != null; 10670 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10671 boolean doRestore = !update 10672 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10673 10674 // Set up the post-install work request bookkeeping. This will be used 10675 // and cleaned up by the post-install event handling regardless of whether 10676 // there's a restore pass performed. Token values are >= 1. 10677 int token; 10678 if (mNextInstallToken < 0) mNextInstallToken = 1; 10679 token = mNextInstallToken++; 10680 10681 PostInstallData data = new PostInstallData(args, res); 10682 mRunningInstalls.put(token, data); 10683 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10684 10685 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10686 // Pass responsibility to the Backup Manager. It will perform a 10687 // restore if appropriate, then pass responsibility back to the 10688 // Package Manager to run the post-install observer callbacks 10689 // and broadcasts. 10690 IBackupManager bm = IBackupManager.Stub.asInterface( 10691 ServiceManager.getService(Context.BACKUP_SERVICE)); 10692 if (bm != null) { 10693 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10694 + " to BM for possible restore"); 10695 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10696 try { 10697 // TODO: http://b/22388012 10698 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 10699 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10700 } else { 10701 doRestore = false; 10702 } 10703 } catch (RemoteException e) { 10704 // can't happen; the backup manager is local 10705 } catch (Exception e) { 10706 Slog.e(TAG, "Exception trying to enqueue restore", e); 10707 doRestore = false; 10708 } 10709 } else { 10710 Slog.e(TAG, "Backup Manager not found!"); 10711 doRestore = false; 10712 } 10713 } 10714 10715 if (!doRestore) { 10716 // No restore possible, or the Backup Manager was mysteriously not 10717 // available -- just fire the post-install work request directly. 10718 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10719 10720 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 10721 10722 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10723 mHandler.sendMessage(msg); 10724 } 10725 } 10726 }); 10727 } 10728 10729 private abstract class HandlerParams { 10730 private static final int MAX_RETRIES = 4; 10731 10732 /** 10733 * Number of times startCopy() has been attempted and had a non-fatal 10734 * error. 10735 */ 10736 private int mRetries = 0; 10737 10738 /** User handle for the user requesting the information or installation. */ 10739 private final UserHandle mUser; 10740 String traceMethod; 10741 int traceCookie; 10742 10743 HandlerParams(UserHandle user) { 10744 mUser = user; 10745 } 10746 10747 UserHandle getUser() { 10748 return mUser; 10749 } 10750 10751 HandlerParams setTraceMethod(String traceMethod) { 10752 this.traceMethod = traceMethod; 10753 return this; 10754 } 10755 10756 HandlerParams setTraceCookie(int traceCookie) { 10757 this.traceCookie = traceCookie; 10758 return this; 10759 } 10760 10761 final boolean startCopy() { 10762 boolean res; 10763 try { 10764 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10765 10766 if (++mRetries > MAX_RETRIES) { 10767 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10768 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10769 handleServiceError(); 10770 return false; 10771 } else { 10772 handleStartCopy(); 10773 res = true; 10774 } 10775 } catch (RemoteException e) { 10776 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10777 mHandler.sendEmptyMessage(MCS_RECONNECT); 10778 res = false; 10779 } 10780 handleReturnCode(); 10781 return res; 10782 } 10783 10784 final void serviceError() { 10785 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10786 handleServiceError(); 10787 handleReturnCode(); 10788 } 10789 10790 abstract void handleStartCopy() throws RemoteException; 10791 abstract void handleServiceError(); 10792 abstract void handleReturnCode(); 10793 } 10794 10795 class MeasureParams extends HandlerParams { 10796 private final PackageStats mStats; 10797 private boolean mSuccess; 10798 10799 private final IPackageStatsObserver mObserver; 10800 10801 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10802 super(new UserHandle(stats.userHandle)); 10803 mObserver = observer; 10804 mStats = stats; 10805 } 10806 10807 @Override 10808 public String toString() { 10809 return "MeasureParams{" 10810 + Integer.toHexString(System.identityHashCode(this)) 10811 + " " + mStats.packageName + "}"; 10812 } 10813 10814 @Override 10815 void handleStartCopy() throws RemoteException { 10816 synchronized (mInstallLock) { 10817 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10818 } 10819 10820 if (mSuccess) { 10821 final boolean mounted; 10822 if (Environment.isExternalStorageEmulated()) { 10823 mounted = true; 10824 } else { 10825 final String status = Environment.getExternalStorageState(); 10826 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10827 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10828 } 10829 10830 if (mounted) { 10831 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10832 10833 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10834 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10835 10836 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10837 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10838 10839 // Always subtract cache size, since it's a subdirectory 10840 mStats.externalDataSize -= mStats.externalCacheSize; 10841 10842 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10843 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10844 10845 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10846 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10847 } 10848 } 10849 } 10850 10851 @Override 10852 void handleReturnCode() { 10853 if (mObserver != null) { 10854 try { 10855 mObserver.onGetStatsCompleted(mStats, mSuccess); 10856 } catch (RemoteException e) { 10857 Slog.i(TAG, "Observer no longer exists."); 10858 } 10859 } 10860 } 10861 10862 @Override 10863 void handleServiceError() { 10864 Slog.e(TAG, "Could not measure application " + mStats.packageName 10865 + " external storage"); 10866 } 10867 } 10868 10869 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10870 throws RemoteException { 10871 long result = 0; 10872 for (File path : paths) { 10873 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10874 } 10875 return result; 10876 } 10877 10878 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10879 for (File path : paths) { 10880 try { 10881 mcs.clearDirectory(path.getAbsolutePath()); 10882 } catch (RemoteException e) { 10883 } 10884 } 10885 } 10886 10887 static class OriginInfo { 10888 /** 10889 * Location where install is coming from, before it has been 10890 * copied/renamed into place. This could be a single monolithic APK 10891 * file, or a cluster directory. This location may be untrusted. 10892 */ 10893 final File file; 10894 final String cid; 10895 10896 /** 10897 * Flag indicating that {@link #file} or {@link #cid} has already been 10898 * staged, meaning downstream users don't need to defensively copy the 10899 * contents. 10900 */ 10901 final boolean staged; 10902 10903 /** 10904 * Flag indicating that {@link #file} or {@link #cid} is an already 10905 * installed app that is being moved. 10906 */ 10907 final boolean existing; 10908 10909 final String resolvedPath; 10910 final File resolvedFile; 10911 10912 static OriginInfo fromNothing() { 10913 return new OriginInfo(null, null, false, false); 10914 } 10915 10916 static OriginInfo fromUntrustedFile(File file) { 10917 return new OriginInfo(file, null, false, false); 10918 } 10919 10920 static OriginInfo fromExistingFile(File file) { 10921 return new OriginInfo(file, null, false, true); 10922 } 10923 10924 static OriginInfo fromStagedFile(File file) { 10925 return new OriginInfo(file, null, true, false); 10926 } 10927 10928 static OriginInfo fromStagedContainer(String cid) { 10929 return new OriginInfo(null, cid, true, false); 10930 } 10931 10932 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10933 this.file = file; 10934 this.cid = cid; 10935 this.staged = staged; 10936 this.existing = existing; 10937 10938 if (cid != null) { 10939 resolvedPath = PackageHelper.getSdDir(cid); 10940 resolvedFile = new File(resolvedPath); 10941 } else if (file != null) { 10942 resolvedPath = file.getAbsolutePath(); 10943 resolvedFile = file; 10944 } else { 10945 resolvedPath = null; 10946 resolvedFile = null; 10947 } 10948 } 10949 } 10950 10951 static class MoveInfo { 10952 final int moveId; 10953 final String fromUuid; 10954 final String toUuid; 10955 final String packageName; 10956 final String dataAppName; 10957 final int appId; 10958 final String seinfo; 10959 final int targetSdkVersion; 10960 10961 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10962 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 10963 this.moveId = moveId; 10964 this.fromUuid = fromUuid; 10965 this.toUuid = toUuid; 10966 this.packageName = packageName; 10967 this.dataAppName = dataAppName; 10968 this.appId = appId; 10969 this.seinfo = seinfo; 10970 this.targetSdkVersion = targetSdkVersion; 10971 } 10972 } 10973 10974 class InstallParams extends HandlerParams { 10975 final OriginInfo origin; 10976 final MoveInfo move; 10977 final IPackageInstallObserver2 observer; 10978 int installFlags; 10979 final String installerPackageName; 10980 final String volumeUuid; 10981 final VerificationParams verificationParams; 10982 private InstallArgs mArgs; 10983 private int mRet; 10984 final String packageAbiOverride; 10985 final String[] grantedRuntimePermissions; 10986 10987 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10988 int installFlags, String installerPackageName, String volumeUuid, 10989 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10990 String[] grantedPermissions) { 10991 super(user); 10992 this.origin = origin; 10993 this.move = move; 10994 this.observer = observer; 10995 this.installFlags = installFlags; 10996 this.installerPackageName = installerPackageName; 10997 this.volumeUuid = volumeUuid; 10998 this.verificationParams = verificationParams; 10999 this.packageAbiOverride = packageAbiOverride; 11000 this.grantedRuntimePermissions = grantedPermissions; 11001 } 11002 11003 @Override 11004 public String toString() { 11005 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 11006 + " file=" + origin.file + " cid=" + origin.cid + "}"; 11007 } 11008 11009 private int installLocationPolicy(PackageInfoLite pkgLite) { 11010 String packageName = pkgLite.packageName; 11011 int installLocation = pkgLite.installLocation; 11012 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11013 // reader 11014 synchronized (mPackages) { 11015 PackageParser.Package pkg = mPackages.get(packageName); 11016 if (pkg != null) { 11017 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11018 // Check for downgrading. 11019 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 11020 try { 11021 checkDowngrade(pkg, pkgLite); 11022 } catch (PackageManagerException e) { 11023 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 11024 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 11025 } 11026 } 11027 // Check for updated system application. 11028 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11029 if (onSd) { 11030 Slog.w(TAG, "Cannot install update to system app on sdcard"); 11031 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 11032 } 11033 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11034 } else { 11035 if (onSd) { 11036 // Install flag overrides everything. 11037 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11038 } 11039 // If current upgrade specifies particular preference 11040 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 11041 // Application explicitly specified internal. 11042 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11043 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 11044 // App explictly prefers external. Let policy decide 11045 } else { 11046 // Prefer previous location 11047 if (isExternal(pkg)) { 11048 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11049 } 11050 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11051 } 11052 } 11053 } else { 11054 // Invalid install. Return error code 11055 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 11056 } 11057 } 11058 } 11059 // All the special cases have been taken care of. 11060 // Return result based on recommended install location. 11061 if (onSd) { 11062 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11063 } 11064 return pkgLite.recommendedInstallLocation; 11065 } 11066 11067 /* 11068 * Invoke remote method to get package information and install 11069 * location values. Override install location based on default 11070 * policy if needed and then create install arguments based 11071 * on the install location. 11072 */ 11073 public void handleStartCopy() throws RemoteException { 11074 int ret = PackageManager.INSTALL_SUCCEEDED; 11075 11076 // If we're already staged, we've firmly committed to an install location 11077 if (origin.staged) { 11078 if (origin.file != null) { 11079 installFlags |= PackageManager.INSTALL_INTERNAL; 11080 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11081 } else if (origin.cid != null) { 11082 installFlags |= PackageManager.INSTALL_EXTERNAL; 11083 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11084 } else { 11085 throw new IllegalStateException("Invalid stage location"); 11086 } 11087 } 11088 11089 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11090 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 11091 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11092 PackageInfoLite pkgLite = null; 11093 11094 if (onInt && onSd) { 11095 // Check if both bits are set. 11096 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 11097 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11098 } else if (onSd && ephemeral) { 11099 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 11100 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11101 } else { 11102 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 11103 packageAbiOverride); 11104 11105 if (DEBUG_EPHEMERAL && ephemeral) { 11106 Slog.v(TAG, "pkgLite for install: " + pkgLite); 11107 } 11108 11109 /* 11110 * If we have too little free space, try to free cache 11111 * before giving up. 11112 */ 11113 if (!origin.staged && pkgLite.recommendedInstallLocation 11114 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11115 // TODO: focus freeing disk space on the target device 11116 final StorageManager storage = StorageManager.from(mContext); 11117 final long lowThreshold = storage.getStorageLowBytes( 11118 Environment.getDataDirectory()); 11119 11120 final long sizeBytes = mContainerService.calculateInstalledSize( 11121 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 11122 11123 try { 11124 mInstaller.freeCache(null, sizeBytes + lowThreshold); 11125 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 11126 installFlags, packageAbiOverride); 11127 } catch (InstallerException e) { 11128 Slog.w(TAG, "Failed to free cache", e); 11129 } 11130 11131 /* 11132 * The cache free must have deleted the file we 11133 * downloaded to install. 11134 * 11135 * TODO: fix the "freeCache" call to not delete 11136 * the file we care about. 11137 */ 11138 if (pkgLite.recommendedInstallLocation 11139 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11140 pkgLite.recommendedInstallLocation 11141 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 11142 } 11143 } 11144 } 11145 11146 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11147 int loc = pkgLite.recommendedInstallLocation; 11148 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 11149 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11150 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 11151 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 11152 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11153 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11154 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 11155 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 11156 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11157 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 11158 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 11159 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 11160 } else { 11161 // Override with defaults if needed. 11162 loc = installLocationPolicy(pkgLite); 11163 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 11164 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 11165 } else if (!onSd && !onInt) { 11166 // Override install location with flags 11167 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 11168 // Set the flag to install on external media. 11169 installFlags |= PackageManager.INSTALL_EXTERNAL; 11170 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11171 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 11172 if (DEBUG_EPHEMERAL) { 11173 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 11174 } 11175 installFlags |= PackageManager.INSTALL_EPHEMERAL; 11176 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 11177 |PackageManager.INSTALL_INTERNAL); 11178 } else { 11179 // Make sure the flag for installing on external 11180 // media is unset 11181 installFlags |= PackageManager.INSTALL_INTERNAL; 11182 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11183 } 11184 } 11185 } 11186 } 11187 11188 final InstallArgs args = createInstallArgs(this); 11189 mArgs = args; 11190 11191 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11192 // TODO: http://b/22976637 11193 // Apps installed for "all" users use the device owner to verify the app 11194 UserHandle verifierUser = getUser(); 11195 if (verifierUser == UserHandle.ALL) { 11196 verifierUser = UserHandle.SYSTEM; 11197 } 11198 11199 /* 11200 * Determine if we have any installed package verifiers. If we 11201 * do, then we'll defer to them to verify the packages. 11202 */ 11203 final int requiredUid = mRequiredVerifierPackage == null ? -1 11204 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 11205 verifierUser.getIdentifier()); 11206 if (!origin.existing && requiredUid != -1 11207 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 11208 final Intent verification = new Intent( 11209 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 11210 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 11211 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 11212 PACKAGE_MIME_TYPE); 11213 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11214 11215 // Query all live verifiers based on current user state 11216 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 11217 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 11218 11219 if (DEBUG_VERIFY) { 11220 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 11221 + verification.toString() + " with " + pkgLite.verifiers.length 11222 + " optional verifiers"); 11223 } 11224 11225 final int verificationId = mPendingVerificationToken++; 11226 11227 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11228 11229 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 11230 installerPackageName); 11231 11232 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 11233 installFlags); 11234 11235 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 11236 pkgLite.packageName); 11237 11238 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 11239 pkgLite.versionCode); 11240 11241 if (verificationParams != null) { 11242 if (verificationParams.getVerificationURI() != null) { 11243 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 11244 verificationParams.getVerificationURI()); 11245 } 11246 if (verificationParams.getOriginatingURI() != null) { 11247 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 11248 verificationParams.getOriginatingURI()); 11249 } 11250 if (verificationParams.getReferrer() != null) { 11251 verification.putExtra(Intent.EXTRA_REFERRER, 11252 verificationParams.getReferrer()); 11253 } 11254 if (verificationParams.getOriginatingUid() >= 0) { 11255 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 11256 verificationParams.getOriginatingUid()); 11257 } 11258 if (verificationParams.getInstallerUid() >= 0) { 11259 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 11260 verificationParams.getInstallerUid()); 11261 } 11262 } 11263 11264 final PackageVerificationState verificationState = new PackageVerificationState( 11265 requiredUid, args); 11266 11267 mPendingVerification.append(verificationId, verificationState); 11268 11269 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 11270 receivers, verificationState); 11271 11272 /* 11273 * If any sufficient verifiers were listed in the package 11274 * manifest, attempt to ask them. 11275 */ 11276 if (sufficientVerifiers != null) { 11277 final int N = sufficientVerifiers.size(); 11278 if (N == 0) { 11279 Slog.i(TAG, "Additional verifiers required, but none installed."); 11280 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 11281 } else { 11282 for (int i = 0; i < N; i++) { 11283 final ComponentName verifierComponent = sufficientVerifiers.get(i); 11284 11285 final Intent sufficientIntent = new Intent(verification); 11286 sufficientIntent.setComponent(verifierComponent); 11287 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 11288 } 11289 } 11290 } 11291 11292 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 11293 mRequiredVerifierPackage, receivers); 11294 if (ret == PackageManager.INSTALL_SUCCEEDED 11295 && mRequiredVerifierPackage != null) { 11296 Trace.asyncTraceBegin( 11297 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 11298 /* 11299 * Send the intent to the required verification agent, 11300 * but only start the verification timeout after the 11301 * target BroadcastReceivers have run. 11302 */ 11303 verification.setComponent(requiredVerifierComponent); 11304 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 11305 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11306 new BroadcastReceiver() { 11307 @Override 11308 public void onReceive(Context context, Intent intent) { 11309 final Message msg = mHandler 11310 .obtainMessage(CHECK_PENDING_VERIFICATION); 11311 msg.arg1 = verificationId; 11312 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 11313 } 11314 }, null, 0, null, null); 11315 11316 /* 11317 * We don't want the copy to proceed until verification 11318 * succeeds, so null out this field. 11319 */ 11320 mArgs = null; 11321 } 11322 } else { 11323 /* 11324 * No package verification is enabled, so immediately start 11325 * the remote call to initiate copy using temporary file. 11326 */ 11327 ret = args.copyApk(mContainerService, true); 11328 } 11329 } 11330 11331 mRet = ret; 11332 } 11333 11334 @Override 11335 void handleReturnCode() { 11336 // If mArgs is null, then MCS couldn't be reached. When it 11337 // reconnects, it will try again to install. At that point, this 11338 // will succeed. 11339 if (mArgs != null) { 11340 processPendingInstall(mArgs, mRet); 11341 } 11342 } 11343 11344 @Override 11345 void handleServiceError() { 11346 mArgs = createInstallArgs(this); 11347 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11348 } 11349 11350 public boolean isForwardLocked() { 11351 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11352 } 11353 } 11354 11355 /** 11356 * Used during creation of InstallArgs 11357 * 11358 * @param installFlags package installation flags 11359 * @return true if should be installed on external storage 11360 */ 11361 private static boolean installOnExternalAsec(int installFlags) { 11362 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 11363 return false; 11364 } 11365 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 11366 return true; 11367 } 11368 return false; 11369 } 11370 11371 /** 11372 * Used during creation of InstallArgs 11373 * 11374 * @param installFlags package installation flags 11375 * @return true if should be installed as forward locked 11376 */ 11377 private static boolean installForwardLocked(int installFlags) { 11378 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11379 } 11380 11381 private InstallArgs createInstallArgs(InstallParams params) { 11382 if (params.move != null) { 11383 return new MoveInstallArgs(params); 11384 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 11385 return new AsecInstallArgs(params); 11386 } else { 11387 return new FileInstallArgs(params); 11388 } 11389 } 11390 11391 /** 11392 * Create args that describe an existing installed package. Typically used 11393 * when cleaning up old installs, or used as a move source. 11394 */ 11395 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 11396 String resourcePath, String[] instructionSets) { 11397 final boolean isInAsec; 11398 if (installOnExternalAsec(installFlags)) { 11399 /* Apps on SD card are always in ASEC containers. */ 11400 isInAsec = true; 11401 } else if (installForwardLocked(installFlags) 11402 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 11403 /* 11404 * Forward-locked apps are only in ASEC containers if they're the 11405 * new style 11406 */ 11407 isInAsec = true; 11408 } else { 11409 isInAsec = false; 11410 } 11411 11412 if (isInAsec) { 11413 return new AsecInstallArgs(codePath, instructionSets, 11414 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 11415 } else { 11416 return new FileInstallArgs(codePath, resourcePath, instructionSets); 11417 } 11418 } 11419 11420 static abstract class InstallArgs { 11421 /** @see InstallParams#origin */ 11422 final OriginInfo origin; 11423 /** @see InstallParams#move */ 11424 final MoveInfo move; 11425 11426 final IPackageInstallObserver2 observer; 11427 // Always refers to PackageManager flags only 11428 final int installFlags; 11429 final String installerPackageName; 11430 final String volumeUuid; 11431 final UserHandle user; 11432 final String abiOverride; 11433 final String[] installGrantPermissions; 11434 /** If non-null, drop an async trace when the install completes */ 11435 final String traceMethod; 11436 final int traceCookie; 11437 11438 // The list of instruction sets supported by this app. This is currently 11439 // only used during the rmdex() phase to clean up resources. We can get rid of this 11440 // if we move dex files under the common app path. 11441 /* nullable */ String[] instructionSets; 11442 11443 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11444 int installFlags, String installerPackageName, String volumeUuid, 11445 UserHandle user, String[] instructionSets, 11446 String abiOverride, String[] installGrantPermissions, 11447 String traceMethod, int traceCookie) { 11448 this.origin = origin; 11449 this.move = move; 11450 this.installFlags = installFlags; 11451 this.observer = observer; 11452 this.installerPackageName = installerPackageName; 11453 this.volumeUuid = volumeUuid; 11454 this.user = user; 11455 this.instructionSets = instructionSets; 11456 this.abiOverride = abiOverride; 11457 this.installGrantPermissions = installGrantPermissions; 11458 this.traceMethod = traceMethod; 11459 this.traceCookie = traceCookie; 11460 } 11461 11462 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 11463 abstract int doPreInstall(int status); 11464 11465 /** 11466 * Rename package into final resting place. All paths on the given 11467 * scanned package should be updated to reflect the rename. 11468 */ 11469 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 11470 abstract int doPostInstall(int status, int uid); 11471 11472 /** @see PackageSettingBase#codePathString */ 11473 abstract String getCodePath(); 11474 /** @see PackageSettingBase#resourcePathString */ 11475 abstract String getResourcePath(); 11476 11477 // Need installer lock especially for dex file removal. 11478 abstract void cleanUpResourcesLI(); 11479 abstract boolean doPostDeleteLI(boolean delete); 11480 11481 /** 11482 * Called before the source arguments are copied. This is used mostly 11483 * for MoveParams when it needs to read the source file to put it in the 11484 * destination. 11485 */ 11486 int doPreCopy() { 11487 return PackageManager.INSTALL_SUCCEEDED; 11488 } 11489 11490 /** 11491 * Called after the source arguments are copied. This is used mostly for 11492 * MoveParams when it needs to read the source file to put it in the 11493 * destination. 11494 * 11495 * @return 11496 */ 11497 int doPostCopy(int uid) { 11498 return PackageManager.INSTALL_SUCCEEDED; 11499 } 11500 11501 protected boolean isFwdLocked() { 11502 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11503 } 11504 11505 protected boolean isExternalAsec() { 11506 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11507 } 11508 11509 protected boolean isEphemeral() { 11510 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11511 } 11512 11513 UserHandle getUser() { 11514 return user; 11515 } 11516 } 11517 11518 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 11519 if (!allCodePaths.isEmpty()) { 11520 if (instructionSets == null) { 11521 throw new IllegalStateException("instructionSet == null"); 11522 } 11523 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11524 for (String codePath : allCodePaths) { 11525 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11526 try { 11527 mInstaller.rmdex(codePath, dexCodeInstructionSet); 11528 } catch (InstallerException ignored) { 11529 } 11530 } 11531 } 11532 } 11533 } 11534 11535 /** 11536 * Logic to handle installation of non-ASEC applications, including copying 11537 * and renaming logic. 11538 */ 11539 class FileInstallArgs extends InstallArgs { 11540 private File codeFile; 11541 private File resourceFile; 11542 11543 // Example topology: 11544 // /data/app/com.example/base.apk 11545 // /data/app/com.example/split_foo.apk 11546 // /data/app/com.example/lib/arm/libfoo.so 11547 // /data/app/com.example/lib/arm64/libfoo.so 11548 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11549 11550 /** New install */ 11551 FileInstallArgs(InstallParams params) { 11552 super(params.origin, params.move, params.observer, params.installFlags, 11553 params.installerPackageName, params.volumeUuid, 11554 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11555 params.grantedRuntimePermissions, 11556 params.traceMethod, params.traceCookie); 11557 if (isFwdLocked()) { 11558 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11559 } 11560 } 11561 11562 /** Existing install */ 11563 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11564 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 11565 null, null, null, 0); 11566 this.codeFile = (codePath != null) ? new File(codePath) : null; 11567 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11568 } 11569 11570 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11571 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 11572 try { 11573 return doCopyApk(imcs, temp); 11574 } finally { 11575 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11576 } 11577 } 11578 11579 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11580 if (origin.staged) { 11581 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11582 codeFile = origin.file; 11583 resourceFile = origin.file; 11584 return PackageManager.INSTALL_SUCCEEDED; 11585 } 11586 11587 try { 11588 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11589 final File tempDir = 11590 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 11591 codeFile = tempDir; 11592 resourceFile = tempDir; 11593 } catch (IOException e) { 11594 Slog.w(TAG, "Failed to create copy file: " + e); 11595 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11596 } 11597 11598 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11599 @Override 11600 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11601 if (!FileUtils.isValidExtFilename(name)) { 11602 throw new IllegalArgumentException("Invalid filename: " + name); 11603 } 11604 try { 11605 final File file = new File(codeFile, name); 11606 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11607 O_RDWR | O_CREAT, 0644); 11608 Os.chmod(file.getAbsolutePath(), 0644); 11609 return new ParcelFileDescriptor(fd); 11610 } catch (ErrnoException e) { 11611 throw new RemoteException("Failed to open: " + e.getMessage()); 11612 } 11613 } 11614 }; 11615 11616 int ret = PackageManager.INSTALL_SUCCEEDED; 11617 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11618 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11619 Slog.e(TAG, "Failed to copy package"); 11620 return ret; 11621 } 11622 11623 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11624 NativeLibraryHelper.Handle handle = null; 11625 try { 11626 handle = NativeLibraryHelper.Handle.create(codeFile); 11627 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11628 abiOverride); 11629 } catch (IOException e) { 11630 Slog.e(TAG, "Copying native libraries failed", e); 11631 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11632 } finally { 11633 IoUtils.closeQuietly(handle); 11634 } 11635 11636 return ret; 11637 } 11638 11639 int doPreInstall(int status) { 11640 if (status != PackageManager.INSTALL_SUCCEEDED) { 11641 cleanUp(); 11642 } 11643 return status; 11644 } 11645 11646 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11647 if (status != PackageManager.INSTALL_SUCCEEDED) { 11648 cleanUp(); 11649 return false; 11650 } 11651 11652 final File targetDir = codeFile.getParentFile(); 11653 final File beforeCodeFile = codeFile; 11654 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11655 11656 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11657 try { 11658 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11659 } catch (ErrnoException e) { 11660 Slog.w(TAG, "Failed to rename", e); 11661 return false; 11662 } 11663 11664 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11665 Slog.w(TAG, "Failed to restorecon"); 11666 return false; 11667 } 11668 11669 // Reflect the rename internally 11670 codeFile = afterCodeFile; 11671 resourceFile = afterCodeFile; 11672 11673 // Reflect the rename in scanned details 11674 pkg.codePath = afterCodeFile.getAbsolutePath(); 11675 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11676 pkg.baseCodePath); 11677 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11678 pkg.splitCodePaths); 11679 11680 // Reflect the rename in app info 11681 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11682 pkg.applicationInfo.setCodePath(pkg.codePath); 11683 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11684 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11685 pkg.applicationInfo.setResourcePath(pkg.codePath); 11686 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11687 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11688 11689 return true; 11690 } 11691 11692 int doPostInstall(int status, int uid) { 11693 if (status != PackageManager.INSTALL_SUCCEEDED) { 11694 cleanUp(); 11695 } 11696 return status; 11697 } 11698 11699 @Override 11700 String getCodePath() { 11701 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11702 } 11703 11704 @Override 11705 String getResourcePath() { 11706 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11707 } 11708 11709 private boolean cleanUp() { 11710 if (codeFile == null || !codeFile.exists()) { 11711 return false; 11712 } 11713 11714 removeCodePathLI(codeFile); 11715 11716 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11717 resourceFile.delete(); 11718 } 11719 11720 return true; 11721 } 11722 11723 void cleanUpResourcesLI() { 11724 // Try enumerating all code paths before deleting 11725 List<String> allCodePaths = Collections.EMPTY_LIST; 11726 if (codeFile != null && codeFile.exists()) { 11727 try { 11728 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11729 allCodePaths = pkg.getAllCodePaths(); 11730 } catch (PackageParserException e) { 11731 // Ignored; we tried our best 11732 } 11733 } 11734 11735 cleanUp(); 11736 removeDexFiles(allCodePaths, instructionSets); 11737 } 11738 11739 boolean doPostDeleteLI(boolean delete) { 11740 // XXX err, shouldn't we respect the delete flag? 11741 cleanUpResourcesLI(); 11742 return true; 11743 } 11744 } 11745 11746 private boolean isAsecExternal(String cid) { 11747 final String asecPath = PackageHelper.getSdFilesystem(cid); 11748 return !asecPath.startsWith(mAsecInternalPath); 11749 } 11750 11751 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11752 PackageManagerException { 11753 if (copyRet < 0) { 11754 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11755 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11756 throw new PackageManagerException(copyRet, message); 11757 } 11758 } 11759 } 11760 11761 /** 11762 * Extract the MountService "container ID" from the full code path of an 11763 * .apk. 11764 */ 11765 static String cidFromCodePath(String fullCodePath) { 11766 int eidx = fullCodePath.lastIndexOf("/"); 11767 String subStr1 = fullCodePath.substring(0, eidx); 11768 int sidx = subStr1.lastIndexOf("/"); 11769 return subStr1.substring(sidx+1, eidx); 11770 } 11771 11772 /** 11773 * Logic to handle installation of ASEC applications, including copying and 11774 * renaming logic. 11775 */ 11776 class AsecInstallArgs extends InstallArgs { 11777 static final String RES_FILE_NAME = "pkg.apk"; 11778 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11779 11780 String cid; 11781 String packagePath; 11782 String resourcePath; 11783 11784 /** New install */ 11785 AsecInstallArgs(InstallParams params) { 11786 super(params.origin, params.move, params.observer, params.installFlags, 11787 params.installerPackageName, params.volumeUuid, 11788 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11789 params.grantedRuntimePermissions, 11790 params.traceMethod, params.traceCookie); 11791 } 11792 11793 /** Existing install */ 11794 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11795 boolean isExternal, boolean isForwardLocked) { 11796 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11797 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 11798 instructionSets, null, null, null, 0); 11799 // Hackily pretend we're still looking at a full code path 11800 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11801 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11802 } 11803 11804 // Extract cid from fullCodePath 11805 int eidx = fullCodePath.lastIndexOf("/"); 11806 String subStr1 = fullCodePath.substring(0, eidx); 11807 int sidx = subStr1.lastIndexOf("/"); 11808 cid = subStr1.substring(sidx+1, eidx); 11809 setMountPath(subStr1); 11810 } 11811 11812 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11813 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11814 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 11815 instructionSets, null, null, null, 0); 11816 this.cid = cid; 11817 setMountPath(PackageHelper.getSdDir(cid)); 11818 } 11819 11820 void createCopyFile() { 11821 cid = mInstallerService.allocateExternalStageCidLegacy(); 11822 } 11823 11824 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11825 if (origin.staged && origin.cid != null) { 11826 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11827 cid = origin.cid; 11828 setMountPath(PackageHelper.getSdDir(cid)); 11829 return PackageManager.INSTALL_SUCCEEDED; 11830 } 11831 11832 if (temp) { 11833 createCopyFile(); 11834 } else { 11835 /* 11836 * Pre-emptively destroy the container since it's destroyed if 11837 * copying fails due to it existing anyway. 11838 */ 11839 PackageHelper.destroySdDir(cid); 11840 } 11841 11842 final String newMountPath = imcs.copyPackageToContainer( 11843 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11844 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11845 11846 if (newMountPath != null) { 11847 setMountPath(newMountPath); 11848 return PackageManager.INSTALL_SUCCEEDED; 11849 } else { 11850 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11851 } 11852 } 11853 11854 @Override 11855 String getCodePath() { 11856 return packagePath; 11857 } 11858 11859 @Override 11860 String getResourcePath() { 11861 return resourcePath; 11862 } 11863 11864 int doPreInstall(int status) { 11865 if (status != PackageManager.INSTALL_SUCCEEDED) { 11866 // Destroy container 11867 PackageHelper.destroySdDir(cid); 11868 } else { 11869 boolean mounted = PackageHelper.isContainerMounted(cid); 11870 if (!mounted) { 11871 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11872 Process.SYSTEM_UID); 11873 if (newMountPath != null) { 11874 setMountPath(newMountPath); 11875 } else { 11876 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11877 } 11878 } 11879 } 11880 return status; 11881 } 11882 11883 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11884 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11885 String newMountPath = null; 11886 if (PackageHelper.isContainerMounted(cid)) { 11887 // Unmount the container 11888 if (!PackageHelper.unMountSdDir(cid)) { 11889 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11890 return false; 11891 } 11892 } 11893 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11894 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11895 " which might be stale. Will try to clean up."); 11896 // Clean up the stale container and proceed to recreate. 11897 if (!PackageHelper.destroySdDir(newCacheId)) { 11898 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11899 return false; 11900 } 11901 // Successfully cleaned up stale container. Try to rename again. 11902 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11903 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11904 + " inspite of cleaning it up."); 11905 return false; 11906 } 11907 } 11908 if (!PackageHelper.isContainerMounted(newCacheId)) { 11909 Slog.w(TAG, "Mounting container " + newCacheId); 11910 newMountPath = PackageHelper.mountSdDir(newCacheId, 11911 getEncryptKey(), Process.SYSTEM_UID); 11912 } else { 11913 newMountPath = PackageHelper.getSdDir(newCacheId); 11914 } 11915 if (newMountPath == null) { 11916 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11917 return false; 11918 } 11919 Log.i(TAG, "Succesfully renamed " + cid + 11920 " to " + newCacheId + 11921 " at new path: " + newMountPath); 11922 cid = newCacheId; 11923 11924 final File beforeCodeFile = new File(packagePath); 11925 setMountPath(newMountPath); 11926 final File afterCodeFile = new File(packagePath); 11927 11928 // Reflect the rename in scanned details 11929 pkg.codePath = afterCodeFile.getAbsolutePath(); 11930 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11931 pkg.baseCodePath); 11932 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11933 pkg.splitCodePaths); 11934 11935 // Reflect the rename in app info 11936 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11937 pkg.applicationInfo.setCodePath(pkg.codePath); 11938 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11939 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11940 pkg.applicationInfo.setResourcePath(pkg.codePath); 11941 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11942 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11943 11944 return true; 11945 } 11946 11947 private void setMountPath(String mountPath) { 11948 final File mountFile = new File(mountPath); 11949 11950 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11951 if (monolithicFile.exists()) { 11952 packagePath = monolithicFile.getAbsolutePath(); 11953 if (isFwdLocked()) { 11954 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11955 } else { 11956 resourcePath = packagePath; 11957 } 11958 } else { 11959 packagePath = mountFile.getAbsolutePath(); 11960 resourcePath = packagePath; 11961 } 11962 } 11963 11964 int doPostInstall(int status, int uid) { 11965 if (status != PackageManager.INSTALL_SUCCEEDED) { 11966 cleanUp(); 11967 } else { 11968 final int groupOwner; 11969 final String protectedFile; 11970 if (isFwdLocked()) { 11971 groupOwner = UserHandle.getSharedAppGid(uid); 11972 protectedFile = RES_FILE_NAME; 11973 } else { 11974 groupOwner = -1; 11975 protectedFile = null; 11976 } 11977 11978 if (uid < Process.FIRST_APPLICATION_UID 11979 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11980 Slog.e(TAG, "Failed to finalize " + cid); 11981 PackageHelper.destroySdDir(cid); 11982 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11983 } 11984 11985 boolean mounted = PackageHelper.isContainerMounted(cid); 11986 if (!mounted) { 11987 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11988 } 11989 } 11990 return status; 11991 } 11992 11993 private void cleanUp() { 11994 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11995 11996 // Destroy secure container 11997 PackageHelper.destroySdDir(cid); 11998 } 11999 12000 private List<String> getAllCodePaths() { 12001 final File codeFile = new File(getCodePath()); 12002 if (codeFile != null && codeFile.exists()) { 12003 try { 12004 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12005 return pkg.getAllCodePaths(); 12006 } catch (PackageParserException e) { 12007 // Ignored; we tried our best 12008 } 12009 } 12010 return Collections.EMPTY_LIST; 12011 } 12012 12013 void cleanUpResourcesLI() { 12014 // Enumerate all code paths before deleting 12015 cleanUpResourcesLI(getAllCodePaths()); 12016 } 12017 12018 private void cleanUpResourcesLI(List<String> allCodePaths) { 12019 cleanUp(); 12020 removeDexFiles(allCodePaths, instructionSets); 12021 } 12022 12023 String getPackageName() { 12024 return getAsecPackageName(cid); 12025 } 12026 12027 boolean doPostDeleteLI(boolean delete) { 12028 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 12029 final List<String> allCodePaths = getAllCodePaths(); 12030 boolean mounted = PackageHelper.isContainerMounted(cid); 12031 if (mounted) { 12032 // Unmount first 12033 if (PackageHelper.unMountSdDir(cid)) { 12034 mounted = false; 12035 } 12036 } 12037 if (!mounted && delete) { 12038 cleanUpResourcesLI(allCodePaths); 12039 } 12040 return !mounted; 12041 } 12042 12043 @Override 12044 int doPreCopy() { 12045 if (isFwdLocked()) { 12046 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 12047 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 12048 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12049 } 12050 } 12051 12052 return PackageManager.INSTALL_SUCCEEDED; 12053 } 12054 12055 @Override 12056 int doPostCopy(int uid) { 12057 if (isFwdLocked()) { 12058 if (uid < Process.FIRST_APPLICATION_UID 12059 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 12060 RES_FILE_NAME)) { 12061 Slog.e(TAG, "Failed to finalize " + cid); 12062 PackageHelper.destroySdDir(cid); 12063 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12064 } 12065 } 12066 12067 return PackageManager.INSTALL_SUCCEEDED; 12068 } 12069 } 12070 12071 /** 12072 * Logic to handle movement of existing installed applications. 12073 */ 12074 class MoveInstallArgs extends InstallArgs { 12075 private File codeFile; 12076 private File resourceFile; 12077 12078 /** New install */ 12079 MoveInstallArgs(InstallParams params) { 12080 super(params.origin, params.move, params.observer, params.installFlags, 12081 params.installerPackageName, params.volumeUuid, 12082 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12083 params.grantedRuntimePermissions, 12084 params.traceMethod, params.traceCookie); 12085 } 12086 12087 int copyApk(IMediaContainerService imcs, boolean temp) { 12088 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 12089 + move.fromUuid + " to " + move.toUuid); 12090 synchronized (mInstaller) { 12091 try { 12092 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 12093 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 12094 } catch (InstallerException e) { 12095 Slog.w(TAG, "Failed to move app", e); 12096 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12097 } 12098 } 12099 12100 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 12101 resourceFile = codeFile; 12102 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 12103 12104 return PackageManager.INSTALL_SUCCEEDED; 12105 } 12106 12107 int doPreInstall(int status) { 12108 if (status != PackageManager.INSTALL_SUCCEEDED) { 12109 cleanUp(move.toUuid); 12110 } 12111 return status; 12112 } 12113 12114 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12115 if (status != PackageManager.INSTALL_SUCCEEDED) { 12116 cleanUp(move.toUuid); 12117 return false; 12118 } 12119 12120 // Reflect the move in app info 12121 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 12122 pkg.applicationInfo.setCodePath(pkg.codePath); 12123 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 12124 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 12125 pkg.applicationInfo.setResourcePath(pkg.codePath); 12126 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 12127 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 12128 12129 return true; 12130 } 12131 12132 int doPostInstall(int status, int uid) { 12133 if (status == PackageManager.INSTALL_SUCCEEDED) { 12134 cleanUp(move.fromUuid); 12135 } else { 12136 cleanUp(move.toUuid); 12137 } 12138 return status; 12139 } 12140 12141 @Override 12142 String getCodePath() { 12143 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12144 } 12145 12146 @Override 12147 String getResourcePath() { 12148 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12149 } 12150 12151 private boolean cleanUp(String volumeUuid) { 12152 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 12153 move.dataAppName); 12154 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 12155 synchronized (mInstallLock) { 12156 // Clean up both app data and code 12157 removeDataDirsLI(volumeUuid, move.packageName); 12158 removeCodePathLI(codeFile); 12159 } 12160 return true; 12161 } 12162 12163 void cleanUpResourcesLI() { 12164 throw new UnsupportedOperationException(); 12165 } 12166 12167 boolean doPostDeleteLI(boolean delete) { 12168 throw new UnsupportedOperationException(); 12169 } 12170 } 12171 12172 static String getAsecPackageName(String packageCid) { 12173 int idx = packageCid.lastIndexOf("-"); 12174 if (idx == -1) { 12175 return packageCid; 12176 } 12177 return packageCid.substring(0, idx); 12178 } 12179 12180 // Utility method used to create code paths based on package name and available index. 12181 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 12182 String idxStr = ""; 12183 int idx = 1; 12184 // Fall back to default value of idx=1 if prefix is not 12185 // part of oldCodePath 12186 if (oldCodePath != null) { 12187 String subStr = oldCodePath; 12188 // Drop the suffix right away 12189 if (suffix != null && subStr.endsWith(suffix)) { 12190 subStr = subStr.substring(0, subStr.length() - suffix.length()); 12191 } 12192 // If oldCodePath already contains prefix find out the 12193 // ending index to either increment or decrement. 12194 int sidx = subStr.lastIndexOf(prefix); 12195 if (sidx != -1) { 12196 subStr = subStr.substring(sidx + prefix.length()); 12197 if (subStr != null) { 12198 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 12199 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 12200 } 12201 try { 12202 idx = Integer.parseInt(subStr); 12203 if (idx <= 1) { 12204 idx++; 12205 } else { 12206 idx--; 12207 } 12208 } catch(NumberFormatException e) { 12209 } 12210 } 12211 } 12212 } 12213 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 12214 return prefix + idxStr; 12215 } 12216 12217 private File getNextCodePath(File targetDir, String packageName) { 12218 int suffix = 1; 12219 File result; 12220 do { 12221 result = new File(targetDir, packageName + "-" + suffix); 12222 suffix++; 12223 } while (result.exists()); 12224 return result; 12225 } 12226 12227 // Utility method that returns the relative package path with respect 12228 // to the installation directory. Like say for /data/data/com.test-1.apk 12229 // string com.test-1 is returned. 12230 static String deriveCodePathName(String codePath) { 12231 if (codePath == null) { 12232 return null; 12233 } 12234 final File codeFile = new File(codePath); 12235 final String name = codeFile.getName(); 12236 if (codeFile.isDirectory()) { 12237 return name; 12238 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 12239 final int lastDot = name.lastIndexOf('.'); 12240 return name.substring(0, lastDot); 12241 } else { 12242 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 12243 return null; 12244 } 12245 } 12246 12247 static class PackageInstalledInfo { 12248 String name; 12249 int uid; 12250 // The set of users that originally had this package installed. 12251 int[] origUsers; 12252 // The set of users that now have this package installed. 12253 int[] newUsers; 12254 PackageParser.Package pkg; 12255 int returnCode; 12256 String returnMsg; 12257 PackageRemovedInfo removedInfo; 12258 12259 public void setError(int code, String msg) { 12260 returnCode = code; 12261 returnMsg = msg; 12262 Slog.w(TAG, msg); 12263 } 12264 12265 public void setError(String msg, PackageParserException e) { 12266 returnCode = e.error; 12267 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12268 Slog.w(TAG, msg, e); 12269 } 12270 12271 public void setError(String msg, PackageManagerException e) { 12272 returnCode = e.error; 12273 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12274 Slog.w(TAG, msg, e); 12275 } 12276 12277 // In some error cases we want to convey more info back to the observer 12278 String origPackage; 12279 String origPermission; 12280 } 12281 12282 /* 12283 * Install a non-existing package. 12284 */ 12285 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12286 UserHandle user, String installerPackageName, String volumeUuid, 12287 PackageInstalledInfo res) { 12288 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 12289 12290 // Remember this for later, in case we need to rollback this install 12291 String pkgName = pkg.packageName; 12292 12293 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 12294 // TODO: b/23350563 12295 final boolean dataDirExists = Environment 12296 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists(); 12297 12298 synchronized(mPackages) { 12299 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 12300 // A package with the same name is already installed, though 12301 // it has been renamed to an older name. The package we 12302 // are trying to install should be installed as an update to 12303 // the existing one, but that has not been requested, so bail. 12304 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12305 + " without first uninstalling package running as " 12306 + mSettings.mRenamedPackages.get(pkgName)); 12307 return; 12308 } 12309 if (mPackages.containsKey(pkgName)) { 12310 // Don't allow installation over an existing package with the same name. 12311 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12312 + " without first uninstalling."); 12313 return; 12314 } 12315 } 12316 12317 try { 12318 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 12319 System.currentTimeMillis(), user); 12320 12321 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 12322 prepareAppDataAfterInstall(newPackage); 12323 12324 // delete the partially installed application. the data directory will have to be 12325 // restored if it was already existing 12326 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12327 // remove package from internal structures. Note that we want deletePackageX to 12328 // delete the package data and cache directories that it created in 12329 // scanPackageLocked, unless those directories existed before we even tried to 12330 // install. 12331 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 12332 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 12333 res.removedInfo, true); 12334 } 12335 12336 } catch (PackageManagerException e) { 12337 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12338 } 12339 12340 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12341 } 12342 12343 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 12344 // Can't rotate keys during boot or if sharedUser. 12345 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 12346 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 12347 return false; 12348 } 12349 // app is using upgradeKeySets; make sure all are valid 12350 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12351 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 12352 for (int i = 0; i < upgradeKeySets.length; i++) { 12353 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 12354 Slog.wtf(TAG, "Package " 12355 + (oldPs.name != null ? oldPs.name : "<null>") 12356 + " contains upgrade-key-set reference to unknown key-set: " 12357 + upgradeKeySets[i] 12358 + " reverting to signatures check."); 12359 return false; 12360 } 12361 } 12362 return true; 12363 } 12364 12365 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 12366 // Upgrade keysets are being used. Determine if new package has a superset of the 12367 // required keys. 12368 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 12369 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12370 for (int i = 0; i < upgradeKeySets.length; i++) { 12371 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 12372 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 12373 return true; 12374 } 12375 } 12376 return false; 12377 } 12378 12379 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12380 UserHandle user, String installerPackageName, String volumeUuid, 12381 PackageInstalledInfo res) { 12382 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 12383 12384 final PackageParser.Package oldPackage; 12385 final String pkgName = pkg.packageName; 12386 final int[] allUsers; 12387 final boolean[] perUserInstalled; 12388 12389 // First find the old package info and check signatures 12390 synchronized(mPackages) { 12391 oldPackage = mPackages.get(pkgName); 12392 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 12393 if (isEphemeral && !oldIsEphemeral) { 12394 // can't downgrade from full to ephemeral 12395 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 12396 res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 12397 return; 12398 } 12399 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 12400 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12401 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12402 if(!checkUpgradeKeySetLP(ps, pkg)) { 12403 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12404 "New package not signed by keys specified by upgrade-keysets: " 12405 + pkgName); 12406 return; 12407 } 12408 } else { 12409 // default to original signature matching 12410 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 12411 != PackageManager.SIGNATURE_MATCH) { 12412 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12413 "New package has a different signature: " + pkgName); 12414 return; 12415 } 12416 } 12417 12418 // In case of rollback, remember per-user/profile install state 12419 allUsers = sUserManager.getUserIds(); 12420 perUserInstalled = new boolean[allUsers.length]; 12421 for (int i = 0; i < allUsers.length; i++) { 12422 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12423 } 12424 } 12425 12426 boolean sysPkg = (isSystemApp(oldPackage)); 12427 if (sysPkg) { 12428 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12429 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12430 } else { 12431 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12432 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12433 } 12434 } 12435 12436 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 12437 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12438 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12439 String volumeUuid, PackageInstalledInfo res) { 12440 String pkgName = deletedPackage.packageName; 12441 boolean deletedPkg = true; 12442 boolean updatedSettings = false; 12443 12444 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 12445 + deletedPackage); 12446 long origUpdateTime; 12447 if (pkg.mExtras != null) { 12448 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 12449 } else { 12450 origUpdateTime = 0; 12451 } 12452 12453 // First delete the existing package while retaining the data directory 12454 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 12455 res.removedInfo, true)) { 12456 // If the existing package wasn't successfully deleted 12457 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 12458 deletedPkg = false; 12459 } else { 12460 // Successfully deleted the old package; proceed with replace. 12461 12462 // If deleted package lived in a container, give users a chance to 12463 // relinquish resources before killing. 12464 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 12465 if (DEBUG_INSTALL) { 12466 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 12467 } 12468 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 12469 final ArrayList<String> pkgList = new ArrayList<String>(1); 12470 pkgList.add(deletedPackage.applicationInfo.packageName); 12471 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 12472 } 12473 12474 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 12475 try { 12476 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 12477 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 12478 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12479 perUserInstalled, res, user); 12480 prepareAppDataAfterInstall(newPackage); 12481 updatedSettings = true; 12482 } catch (PackageManagerException e) { 12483 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12484 } 12485 } 12486 12487 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12488 // remove package from internal structures. Note that we want deletePackageX to 12489 // delete the package data and cache directories that it created in 12490 // scanPackageLocked, unless those directories existed before we even tried to 12491 // install. 12492 if(updatedSettings) { 12493 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 12494 deletePackageLI( 12495 pkgName, null, true, allUsers, perUserInstalled, 12496 PackageManager.DELETE_KEEP_DATA, 12497 res.removedInfo, true); 12498 } 12499 // Since we failed to install the new package we need to restore the old 12500 // package that we deleted. 12501 if (deletedPkg) { 12502 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 12503 File restoreFile = new File(deletedPackage.codePath); 12504 // Parse old package 12505 boolean oldExternal = isExternal(deletedPackage); 12506 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 12507 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 12508 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12509 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 12510 try { 12511 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 12512 null); 12513 } catch (PackageManagerException e) { 12514 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 12515 + e.getMessage()); 12516 return; 12517 } 12518 // Restore of old package succeeded. Update permissions. 12519 // writer 12520 synchronized (mPackages) { 12521 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 12522 UPDATE_PERMISSIONS_ALL); 12523 // can downgrade to reader 12524 mSettings.writeLPr(); 12525 } 12526 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 12527 } 12528 } 12529 } 12530 12531 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 12532 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12533 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12534 String volumeUuid, PackageInstalledInfo res) { 12535 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 12536 + ", old=" + deletedPackage); 12537 boolean disabledSystem = false; 12538 boolean updatedSettings = false; 12539 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 12540 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 12541 != 0) { 12542 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12543 } 12544 String packageName = deletedPackage.packageName; 12545 if (packageName == null) { 12546 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12547 "Attempt to delete null packageName."); 12548 return; 12549 } 12550 PackageParser.Package oldPkg; 12551 PackageSetting oldPkgSetting; 12552 // reader 12553 synchronized (mPackages) { 12554 oldPkg = mPackages.get(packageName); 12555 oldPkgSetting = mSettings.mPackages.get(packageName); 12556 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 12557 (oldPkgSetting == null)) { 12558 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12559 "Couldn't find package " + packageName + " information"); 12560 return; 12561 } 12562 } 12563 12564 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12565 12566 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12567 res.removedInfo.removedPackage = packageName; 12568 // Remove existing system package 12569 removePackageLI(oldPkgSetting, true); 12570 // writer 12571 synchronized (mPackages) { 12572 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12573 if (!disabledSystem && deletedPackage != null) { 12574 // We didn't need to disable the .apk as a current system package, 12575 // which means we are replacing another update that is already 12576 // installed. We need to make sure to delete the older one's .apk. 12577 res.removedInfo.args = createInstallArgsForExisting(0, 12578 deletedPackage.applicationInfo.getCodePath(), 12579 deletedPackage.applicationInfo.getResourcePath(), 12580 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12581 } else { 12582 res.removedInfo.args = null; 12583 } 12584 } 12585 12586 // Successfully disabled the old package. Now proceed with re-installation 12587 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12588 12589 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12590 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12591 12592 PackageParser.Package newPackage = null; 12593 try { 12594 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 12595 if (newPackage.mExtras != null) { 12596 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12597 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12598 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12599 12600 // is the update attempting to change shared user? that isn't going to work... 12601 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12602 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12603 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12604 + " to " + newPkgSetting.sharedUser); 12605 updatedSettings = true; 12606 } 12607 } 12608 12609 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12610 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12611 perUserInstalled, res, user); 12612 prepareAppDataAfterInstall(newPackage); 12613 updatedSettings = true; 12614 } 12615 12616 } catch (PackageManagerException e) { 12617 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12618 } 12619 12620 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12621 // Re installation failed. Restore old information 12622 // Remove new pkg information 12623 if (newPackage != null) { 12624 removeInstalledPackageLI(newPackage, true); 12625 } 12626 // Add back the old system package 12627 try { 12628 scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12629 } catch (PackageManagerException e) { 12630 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12631 } 12632 // Restore the old system information in Settings 12633 synchronized (mPackages) { 12634 if (disabledSystem) { 12635 mSettings.enableSystemPackageLPw(packageName); 12636 } 12637 if (updatedSettings) { 12638 mSettings.setInstallerPackageName(packageName, 12639 oldPkgSetting.installerPackageName); 12640 } 12641 mSettings.writeLPr(); 12642 } 12643 } 12644 } 12645 12646 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 12647 // Collect all used permissions in the UID 12648 ArraySet<String> usedPermissions = new ArraySet<>(); 12649 final int packageCount = su.packages.size(); 12650 for (int i = 0; i < packageCount; i++) { 12651 PackageSetting ps = su.packages.valueAt(i); 12652 if (ps.pkg == null) { 12653 continue; 12654 } 12655 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 12656 for (int j = 0; j < requestedPermCount; j++) { 12657 String permission = ps.pkg.requestedPermissions.get(j); 12658 BasePermission bp = mSettings.mPermissions.get(permission); 12659 if (bp != null) { 12660 usedPermissions.add(permission); 12661 } 12662 } 12663 } 12664 12665 PermissionsState permissionsState = su.getPermissionsState(); 12666 // Prune install permissions 12667 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 12668 final int installPermCount = installPermStates.size(); 12669 for (int i = installPermCount - 1; i >= 0; i--) { 12670 PermissionState permissionState = installPermStates.get(i); 12671 if (!usedPermissions.contains(permissionState.getName())) { 12672 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12673 if (bp != null) { 12674 permissionsState.revokeInstallPermission(bp); 12675 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 12676 PackageManager.MASK_PERMISSION_FLAGS, 0); 12677 } 12678 } 12679 } 12680 12681 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 12682 12683 // Prune runtime permissions 12684 for (int userId : allUserIds) { 12685 List<PermissionState> runtimePermStates = permissionsState 12686 .getRuntimePermissionStates(userId); 12687 final int runtimePermCount = runtimePermStates.size(); 12688 for (int i = runtimePermCount - 1; i >= 0; i--) { 12689 PermissionState permissionState = runtimePermStates.get(i); 12690 if (!usedPermissions.contains(permissionState.getName())) { 12691 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12692 if (bp != null) { 12693 permissionsState.revokeRuntimePermission(bp, userId); 12694 permissionsState.updatePermissionFlags(bp, userId, 12695 PackageManager.MASK_PERMISSION_FLAGS, 0); 12696 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 12697 runtimePermissionChangedUserIds, userId); 12698 } 12699 } 12700 } 12701 } 12702 12703 return runtimePermissionChangedUserIds; 12704 } 12705 12706 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12707 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12708 UserHandle user) { 12709 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 12710 12711 String pkgName = newPackage.packageName; 12712 synchronized (mPackages) { 12713 //write settings. the installStatus will be incomplete at this stage. 12714 //note that the new package setting would have already been 12715 //added to mPackages. It hasn't been persisted yet. 12716 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12717 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12718 mSettings.writeLPr(); 12719 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12720 } 12721 12722 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12723 synchronized (mPackages) { 12724 updatePermissionsLPw(newPackage.packageName, newPackage, 12725 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12726 ? UPDATE_PERMISSIONS_ALL : 0)); 12727 // For system-bundled packages, we assume that installing an upgraded version 12728 // of the package implies that the user actually wants to run that new code, 12729 // so we enable the package. 12730 PackageSetting ps = mSettings.mPackages.get(pkgName); 12731 if (ps != null) { 12732 if (isSystemApp(newPackage)) { 12733 // NB: implicit assumption that system package upgrades apply to all users 12734 if (DEBUG_INSTALL) { 12735 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12736 } 12737 if (res.origUsers != null) { 12738 for (int userHandle : res.origUsers) { 12739 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12740 userHandle, installerPackageName); 12741 } 12742 } 12743 // Also convey the prior install/uninstall state 12744 if (allUsers != null && perUserInstalled != null) { 12745 for (int i = 0; i < allUsers.length; i++) { 12746 if (DEBUG_INSTALL) { 12747 Slog.d(TAG, " user " + allUsers[i] 12748 + " => " + perUserInstalled[i]); 12749 } 12750 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12751 } 12752 // these install state changes will be persisted in the 12753 // upcoming call to mSettings.writeLPr(). 12754 } 12755 } 12756 // It's implied that when a user requests installation, they want the app to be 12757 // installed and enabled. 12758 int userId = user.getIdentifier(); 12759 if (userId != UserHandle.USER_ALL) { 12760 ps.setInstalled(true, userId); 12761 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12762 } 12763 } 12764 res.name = pkgName; 12765 res.uid = newPackage.applicationInfo.uid; 12766 res.pkg = newPackage; 12767 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12768 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12769 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12770 //to update install status 12771 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12772 mSettings.writeLPr(); 12773 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12774 } 12775 12776 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12777 } 12778 12779 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 12780 try { 12781 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 12782 installPackageLI(args, res); 12783 } finally { 12784 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12785 } 12786 } 12787 12788 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12789 final int installFlags = args.installFlags; 12790 final String installerPackageName = args.installerPackageName; 12791 final String volumeUuid = args.volumeUuid; 12792 final File tmpPackageFile = new File(args.getCodePath()); 12793 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12794 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12795 || (args.volumeUuid != null)); 12796 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 12797 boolean replace = false; 12798 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12799 if (args.move != null) { 12800 // moving a complete application; perfom an initial scan on the new install location 12801 scanFlags |= SCAN_INITIAL; 12802 } 12803 // Result object to be returned 12804 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12805 12806 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12807 12808 // Sanity check 12809 if (ephemeral && (forwardLocked || onExternal)) { 12810 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 12811 + " external=" + onExternal); 12812 res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 12813 return; 12814 } 12815 12816 // Retrieve PackageSettings and parse package 12817 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12818 | PackageParser.PARSE_ENFORCE_CODE 12819 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12820 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 12821 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 12822 PackageParser pp = new PackageParser(); 12823 pp.setSeparateProcesses(mSeparateProcesses); 12824 pp.setDisplayMetrics(mMetrics); 12825 12826 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 12827 final PackageParser.Package pkg; 12828 try { 12829 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12830 } catch (PackageParserException e) { 12831 res.setError("Failed parse during installPackageLI", e); 12832 return; 12833 } finally { 12834 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12835 } 12836 12837 // Mark that we have an install time CPU ABI override. 12838 pkg.cpuAbiOverride = args.abiOverride; 12839 12840 String pkgName = res.name = pkg.packageName; 12841 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12842 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12843 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12844 return; 12845 } 12846 } 12847 12848 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 12849 try { 12850 pp.collectCertificates(pkg, parseFlags); 12851 } catch (PackageParserException e) { 12852 res.setError("Failed collect during installPackageLI", e); 12853 return; 12854 } finally { 12855 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12856 } 12857 12858 // Get rid of all references to package scan path via parser. 12859 pp = null; 12860 String oldCodePath = null; 12861 boolean systemApp = false; 12862 synchronized (mPackages) { 12863 // Check if installing already existing package 12864 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12865 String oldName = mSettings.mRenamedPackages.get(pkgName); 12866 if (pkg.mOriginalPackages != null 12867 && pkg.mOriginalPackages.contains(oldName) 12868 && mPackages.containsKey(oldName)) { 12869 // This package is derived from an original package, 12870 // and this device has been updating from that original 12871 // name. We must continue using the original name, so 12872 // rename the new package here. 12873 pkg.setPackageName(oldName); 12874 pkgName = pkg.packageName; 12875 replace = true; 12876 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12877 + oldName + " pkgName=" + pkgName); 12878 } else if (mPackages.containsKey(pkgName)) { 12879 // This package, under its official name, already exists 12880 // on the device; we should replace it. 12881 replace = true; 12882 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12883 } 12884 12885 // Prevent apps opting out from runtime permissions 12886 if (replace) { 12887 PackageParser.Package oldPackage = mPackages.get(pkgName); 12888 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12889 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12890 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12891 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12892 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12893 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12894 + " doesn't support runtime permissions but the old" 12895 + " target SDK " + oldTargetSdk + " does."); 12896 return; 12897 } 12898 } 12899 } 12900 12901 PackageSetting ps = mSettings.mPackages.get(pkgName); 12902 if (ps != null) { 12903 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12904 12905 // Quick sanity check that we're signed correctly if updating; 12906 // we'll check this again later when scanning, but we want to 12907 // bail early here before tripping over redefined permissions. 12908 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12909 if (!checkUpgradeKeySetLP(ps, pkg)) { 12910 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12911 + pkg.packageName + " upgrade keys do not match the " 12912 + "previously installed version"); 12913 return; 12914 } 12915 } else { 12916 try { 12917 verifySignaturesLP(ps, pkg); 12918 } catch (PackageManagerException e) { 12919 res.setError(e.error, e.getMessage()); 12920 return; 12921 } 12922 } 12923 12924 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12925 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12926 systemApp = (ps.pkg.applicationInfo.flags & 12927 ApplicationInfo.FLAG_SYSTEM) != 0; 12928 } 12929 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12930 } 12931 12932 // Check whether the newly-scanned package wants to define an already-defined perm 12933 int N = pkg.permissions.size(); 12934 for (int i = N-1; i >= 0; i--) { 12935 PackageParser.Permission perm = pkg.permissions.get(i); 12936 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12937 if (bp != null) { 12938 // If the defining package is signed with our cert, it's okay. This 12939 // also includes the "updating the same package" case, of course. 12940 // "updating same package" could also involve key-rotation. 12941 final boolean sigsOk; 12942 if (bp.sourcePackage.equals(pkg.packageName) 12943 && (bp.packageSetting instanceof PackageSetting) 12944 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12945 scanFlags))) { 12946 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12947 } else { 12948 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12949 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12950 } 12951 if (!sigsOk) { 12952 // If the owning package is the system itself, we log but allow 12953 // install to proceed; we fail the install on all other permission 12954 // redefinitions. 12955 if (!bp.sourcePackage.equals("android")) { 12956 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12957 + pkg.packageName + " attempting to redeclare permission " 12958 + perm.info.name + " already owned by " + bp.sourcePackage); 12959 res.origPermission = perm.info.name; 12960 res.origPackage = bp.sourcePackage; 12961 return; 12962 } else { 12963 Slog.w(TAG, "Package " + pkg.packageName 12964 + " attempting to redeclare system permission " 12965 + perm.info.name + "; ignoring new declaration"); 12966 pkg.permissions.remove(i); 12967 } 12968 } 12969 } 12970 } 12971 12972 } 12973 12974 if (systemApp) { 12975 if (onExternal) { 12976 // Abort update; system app can't be replaced with app on sdcard 12977 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12978 "Cannot install updates to system apps on sdcard"); 12979 return; 12980 } else if (ephemeral) { 12981 // Abort update; system app can't be replaced with an ephemeral app 12982 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 12983 "Cannot update a system app with an ephemeral app"); 12984 return; 12985 } 12986 } 12987 12988 if (args.move != null) { 12989 // We did an in-place move, so dex is ready to roll 12990 scanFlags |= SCAN_NO_DEX; 12991 scanFlags |= SCAN_MOVE; 12992 12993 synchronized (mPackages) { 12994 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12995 if (ps == null) { 12996 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12997 "Missing settings for moved package " + pkgName); 12998 } 12999 13000 // We moved the entire application as-is, so bring over the 13001 // previously derived ABI information. 13002 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 13003 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 13004 } 13005 13006 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 13007 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 13008 scanFlags |= SCAN_NO_DEX; 13009 13010 try { 13011 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 13012 true /* extract libs */); 13013 } catch (PackageManagerException pme) { 13014 Slog.e(TAG, "Error deriving application ABI", pme); 13015 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 13016 return; 13017 } 13018 13019 // Extract package to save the VM unzipping the APK in memory during 13020 // launch. Only do this if profile-guided compilation is enabled because 13021 // otherwise BackgroundDexOptService will not dexopt the package later. 13022 if (mUseJitProfiles) { 13023 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 13024 // Do not run PackageDexOptimizer through the local performDexOpt 13025 // method because `pkg` is not in `mPackages` yet. 13026 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 13027 false /* inclDependencies */, volumeUuid, false /* useProfiles */, 13028 true /* extractOnly */); 13029 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13030 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 13031 String msg = "Extracking package failed for " + pkgName; 13032 res.setError(INSTALL_FAILED_DEXOPT, msg); 13033 return; 13034 } 13035 } 13036 } 13037 13038 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 13039 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 13040 return; 13041 } 13042 13043 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 13044 13045 if (replace) { 13046 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 13047 installerPackageName, volumeUuid, res); 13048 } else { 13049 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 13050 args.user, installerPackageName, volumeUuid, res); 13051 } 13052 synchronized (mPackages) { 13053 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13054 if (ps != null) { 13055 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13056 } 13057 } 13058 } 13059 13060 private void startIntentFilterVerifications(int userId, boolean replacing, 13061 PackageParser.Package pkg) { 13062 if (mIntentFilterVerifierComponent == null) { 13063 Slog.w(TAG, "No IntentFilter verification will not be done as " 13064 + "there is no IntentFilterVerifier available!"); 13065 return; 13066 } 13067 13068 final int verifierUid = getPackageUid( 13069 mIntentFilterVerifierComponent.getPackageName(), 13070 MATCH_DEBUG_TRIAGED_MISSING, 13071 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 13072 13073 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 13074 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 13075 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 13076 mHandler.sendMessage(msg); 13077 } 13078 13079 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 13080 PackageParser.Package pkg) { 13081 int size = pkg.activities.size(); 13082 if (size == 0) { 13083 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13084 "No activity, so no need to verify any IntentFilter!"); 13085 return; 13086 } 13087 13088 final boolean hasDomainURLs = hasDomainURLs(pkg); 13089 if (!hasDomainURLs) { 13090 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13091 "No domain URLs, so no need to verify any IntentFilter!"); 13092 return; 13093 } 13094 13095 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 13096 + " if any IntentFilter from the " + size 13097 + " Activities needs verification ..."); 13098 13099 int count = 0; 13100 final String packageName = pkg.packageName; 13101 13102 synchronized (mPackages) { 13103 // If this is a new install and we see that we've already run verification for this 13104 // package, we have nothing to do: it means the state was restored from backup. 13105 if (!replacing) { 13106 IntentFilterVerificationInfo ivi = 13107 mSettings.getIntentFilterVerificationLPr(packageName); 13108 if (ivi != null) { 13109 if (DEBUG_DOMAIN_VERIFICATION) { 13110 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 13111 + ivi.getStatusString()); 13112 } 13113 return; 13114 } 13115 } 13116 13117 // If any filters need to be verified, then all need to be. 13118 boolean needToVerify = false; 13119 for (PackageParser.Activity a : pkg.activities) { 13120 for (ActivityIntentInfo filter : a.intents) { 13121 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 13122 if (DEBUG_DOMAIN_VERIFICATION) { 13123 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 13124 } 13125 needToVerify = true; 13126 break; 13127 } 13128 } 13129 } 13130 13131 if (needToVerify) { 13132 final int verificationId = mIntentFilterVerificationToken++; 13133 for (PackageParser.Activity a : pkg.activities) { 13134 for (ActivityIntentInfo filter : a.intents) { 13135 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 13136 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13137 "Verification needed for IntentFilter:" + filter.toString()); 13138 mIntentFilterVerifier.addOneIntentFilterVerification( 13139 verifierUid, userId, verificationId, filter, packageName); 13140 count++; 13141 } 13142 } 13143 } 13144 } 13145 } 13146 13147 if (count > 0) { 13148 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 13149 + " IntentFilter verification" + (count > 1 ? "s" : "") 13150 + " for userId:" + userId); 13151 mIntentFilterVerifier.startVerifications(userId); 13152 } else { 13153 if (DEBUG_DOMAIN_VERIFICATION) { 13154 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 13155 } 13156 } 13157 } 13158 13159 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 13160 final ComponentName cn = filter.activity.getComponentName(); 13161 final String packageName = cn.getPackageName(); 13162 13163 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 13164 packageName); 13165 if (ivi == null) { 13166 return true; 13167 } 13168 int status = ivi.getStatus(); 13169 switch (status) { 13170 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 13171 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 13172 return true; 13173 13174 default: 13175 // Nothing to do 13176 return false; 13177 } 13178 } 13179 13180 private static boolean isMultiArch(ApplicationInfo info) { 13181 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 13182 } 13183 13184 private static boolean isExternal(PackageParser.Package pkg) { 13185 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13186 } 13187 13188 private static boolean isExternal(PackageSetting ps) { 13189 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13190 } 13191 13192 private static boolean isEphemeral(PackageParser.Package pkg) { 13193 return pkg.applicationInfo.isEphemeralApp(); 13194 } 13195 13196 private static boolean isEphemeral(PackageSetting ps) { 13197 return ps.pkg != null && isEphemeral(ps.pkg); 13198 } 13199 13200 private static boolean isSystemApp(PackageParser.Package pkg) { 13201 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 13202 } 13203 13204 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 13205 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 13206 } 13207 13208 private static boolean hasDomainURLs(PackageParser.Package pkg) { 13209 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 13210 } 13211 13212 private static boolean isSystemApp(PackageSetting ps) { 13213 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 13214 } 13215 13216 private static boolean isUpdatedSystemApp(PackageSetting ps) { 13217 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 13218 } 13219 13220 private int packageFlagsToInstallFlags(PackageSetting ps) { 13221 int installFlags = 0; 13222 if (isEphemeral(ps)) { 13223 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13224 } 13225 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 13226 // This existing package was an external ASEC install when we have 13227 // the external flag without a UUID 13228 installFlags |= PackageManager.INSTALL_EXTERNAL; 13229 } 13230 if (ps.isForwardLocked()) { 13231 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13232 } 13233 return installFlags; 13234 } 13235 13236 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 13237 if (isExternal(pkg)) { 13238 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13239 return StorageManager.UUID_PRIMARY_PHYSICAL; 13240 } else { 13241 return pkg.volumeUuid; 13242 } 13243 } else { 13244 return StorageManager.UUID_PRIVATE_INTERNAL; 13245 } 13246 } 13247 13248 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 13249 if (isExternal(pkg)) { 13250 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13251 return mSettings.getExternalVersion(); 13252 } else { 13253 return mSettings.findOrCreateVersion(pkg.volumeUuid); 13254 } 13255 } else { 13256 return mSettings.getInternalVersion(); 13257 } 13258 } 13259 13260 private void deleteTempPackageFiles() { 13261 final FilenameFilter filter = new FilenameFilter() { 13262 public boolean accept(File dir, String name) { 13263 return name.startsWith("vmdl") && name.endsWith(".tmp"); 13264 } 13265 }; 13266 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 13267 file.delete(); 13268 } 13269 } 13270 13271 @Override 13272 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 13273 int flags) { 13274 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 13275 flags); 13276 } 13277 13278 @Override 13279 public void deletePackage(final String packageName, 13280 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 13281 mContext.enforceCallingOrSelfPermission( 13282 android.Manifest.permission.DELETE_PACKAGES, null); 13283 Preconditions.checkNotNull(packageName); 13284 Preconditions.checkNotNull(observer); 13285 final int uid = Binder.getCallingUid(); 13286 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 13287 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 13288 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 13289 mContext.enforceCallingOrSelfPermission( 13290 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 13291 "deletePackage for user " + userId); 13292 } 13293 13294 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 13295 try { 13296 observer.onPackageDeleted(packageName, 13297 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 13298 } catch (RemoteException re) { 13299 } 13300 return; 13301 } 13302 13303 for (int currentUserId : users) { 13304 if (getBlockUninstallForUser(packageName, currentUserId)) { 13305 try { 13306 observer.onPackageDeleted(packageName, 13307 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 13308 } catch (RemoteException re) { 13309 } 13310 return; 13311 } 13312 } 13313 13314 if (DEBUG_REMOVE) { 13315 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 13316 } 13317 // Queue up an async operation since the package deletion may take a little while. 13318 mHandler.post(new Runnable() { 13319 public void run() { 13320 mHandler.removeCallbacks(this); 13321 final int returnCode = deletePackageX(packageName, userId, flags); 13322 try { 13323 observer.onPackageDeleted(packageName, returnCode, null); 13324 } catch (RemoteException e) { 13325 Log.i(TAG, "Observer no longer exists."); 13326 } //end catch 13327 } //end run 13328 }); 13329 } 13330 13331 private boolean isPackageDeviceAdmin(String packageName, int userId) { 13332 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13333 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13334 try { 13335 if (dpm != null) { 13336 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 13337 /* callingUserOnly =*/ false); 13338 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 13339 : deviceOwnerComponentName.getPackageName(); 13340 // Does the package contains the device owner? 13341 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 13342 // this check is probably not needed, since DO should be registered as a device 13343 // admin on some user too. (Original bug for this: b/17657954) 13344 if (packageName.equals(deviceOwnerPackageName)) { 13345 return true; 13346 } 13347 // Does it contain a device admin for any user? 13348 int[] users; 13349 if (userId == UserHandle.USER_ALL) { 13350 users = sUserManager.getUserIds(); 13351 } else { 13352 users = new int[]{userId}; 13353 } 13354 for (int i = 0; i < users.length; ++i) { 13355 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 13356 return true; 13357 } 13358 } 13359 } 13360 } catch (RemoteException e) { 13361 } 13362 return false; 13363 } 13364 13365 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 13366 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 13367 } 13368 13369 /** 13370 * This method is an internal method that could be get invoked either 13371 * to delete an installed package or to clean up a failed installation. 13372 * After deleting an installed package, a broadcast is sent to notify any 13373 * listeners that the package has been installed. For cleaning up a failed 13374 * installation, the broadcast is not necessary since the package's 13375 * installation wouldn't have sent the initial broadcast either 13376 * The key steps in deleting a package are 13377 * deleting the package information in internal structures like mPackages, 13378 * deleting the packages base directories through installd 13379 * updating mSettings to reflect current status 13380 * persisting settings for later use 13381 * sending a broadcast if necessary 13382 */ 13383 private int deletePackageX(String packageName, int userId, int flags) { 13384 final PackageRemovedInfo info = new PackageRemovedInfo(); 13385 final boolean res; 13386 13387 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 13388 ? UserHandle.ALL : new UserHandle(userId); 13389 13390 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 13391 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 13392 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 13393 } 13394 13395 boolean removedForAllUsers = false; 13396 boolean systemUpdate = false; 13397 13398 PackageParser.Package uninstalledPkg; 13399 13400 // for the uninstall-updates case and restricted profiles, remember the per- 13401 // userhandle installed state 13402 int[] allUsers; 13403 boolean[] perUserInstalled; 13404 synchronized (mPackages) { 13405 uninstalledPkg = mPackages.get(packageName); 13406 PackageSetting ps = mSettings.mPackages.get(packageName); 13407 allUsers = sUserManager.getUserIds(); 13408 perUserInstalled = new boolean[allUsers.length]; 13409 for (int i = 0; i < allUsers.length; i++) { 13410 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 13411 } 13412 } 13413 13414 synchronized (mInstallLock) { 13415 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 13416 res = deletePackageLI(packageName, removeForUser, 13417 true, allUsers, perUserInstalled, 13418 flags | REMOVE_CHATTY, info, true); 13419 systemUpdate = info.isRemovedPackageSystemUpdate; 13420 synchronized (mPackages) { 13421 if (res) { 13422 if (!systemUpdate && mPackages.get(packageName) == null) { 13423 removedForAllUsers = true; 13424 } 13425 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg); 13426 } 13427 } 13428 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 13429 + " removedForAllUsers=" + removedForAllUsers); 13430 } 13431 13432 if (res) { 13433 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 13434 13435 // If the removed package was a system update, the old system package 13436 // was re-enabled; we need to broadcast this information 13437 if (systemUpdate) { 13438 Bundle extras = new Bundle(1); 13439 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 13440 ? info.removedAppId : info.uid); 13441 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13442 13443 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 13444 extras, 0, null, null, null); 13445 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 13446 extras, 0, null, null, null); 13447 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 13448 null, 0, packageName, null, null); 13449 } 13450 } 13451 // Force a gc here. 13452 Runtime.getRuntime().gc(); 13453 // Delete the resources here after sending the broadcast to let 13454 // other processes clean up before deleting resources. 13455 if (info.args != null) { 13456 synchronized (mInstallLock) { 13457 info.args.doPostDeleteLI(true); 13458 } 13459 } 13460 13461 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 13462 } 13463 13464 class PackageRemovedInfo { 13465 String removedPackage; 13466 int uid = -1; 13467 int removedAppId = -1; 13468 int[] removedUsers = null; 13469 boolean isRemovedPackageSystemUpdate = false; 13470 // Clean up resources deleted packages. 13471 InstallArgs args = null; 13472 13473 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 13474 Bundle extras = new Bundle(1); 13475 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 13476 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 13477 if (replacing) { 13478 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13479 } 13480 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 13481 if (removedPackage != null) { 13482 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 13483 extras, 0, null, null, removedUsers); 13484 if (fullRemove && !replacing) { 13485 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 13486 extras, 0, null, null, removedUsers); 13487 } 13488 } 13489 if (removedAppId >= 0) { 13490 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 13491 removedUsers); 13492 } 13493 } 13494 } 13495 13496 /* 13497 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 13498 * flag is not set, the data directory is removed as well. 13499 * make sure this flag is set for partially installed apps. If not its meaningless to 13500 * delete a partially installed application. 13501 */ 13502 private void removePackageDataLI(PackageSetting ps, 13503 int[] allUserHandles, boolean[] perUserInstalled, 13504 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 13505 String packageName = ps.name; 13506 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 13507 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 13508 // Retrieve object to delete permissions for shared user later on 13509 final PackageSetting deletedPs; 13510 // reader 13511 synchronized (mPackages) { 13512 deletedPs = mSettings.mPackages.get(packageName); 13513 if (outInfo != null) { 13514 outInfo.removedPackage = packageName; 13515 outInfo.removedUsers = deletedPs != null 13516 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 13517 : null; 13518 } 13519 } 13520 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13521 removeDataDirsLI(ps.volumeUuid, packageName); 13522 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 13523 } 13524 // writer 13525 synchronized (mPackages) { 13526 if (deletedPs != null) { 13527 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13528 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 13529 clearDefaultBrowserIfNeeded(packageName); 13530 if (outInfo != null) { 13531 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 13532 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 13533 } 13534 updatePermissionsLPw(deletedPs.name, null, 0); 13535 if (deletedPs.sharedUser != null) { 13536 // Remove permissions associated with package. Since runtime 13537 // permissions are per user we have to kill the removed package 13538 // or packages running under the shared user of the removed 13539 // package if revoking the permissions requested only by the removed 13540 // package is successful and this causes a change in gids. 13541 for (int userId : UserManagerService.getInstance().getUserIds()) { 13542 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 13543 userId); 13544 if (userIdToKill == UserHandle.USER_ALL 13545 || userIdToKill >= UserHandle.USER_SYSTEM) { 13546 // If gids changed for this user, kill all affected packages. 13547 mHandler.post(new Runnable() { 13548 @Override 13549 public void run() { 13550 // This has to happen with no lock held. 13551 killApplication(deletedPs.name, deletedPs.appId, 13552 KILL_APP_REASON_GIDS_CHANGED); 13553 } 13554 }); 13555 break; 13556 } 13557 } 13558 } 13559 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 13560 } 13561 // make sure to preserve per-user disabled state if this removal was just 13562 // a downgrade of a system app to the factory package 13563 if (allUserHandles != null && perUserInstalled != null) { 13564 if (DEBUG_REMOVE) { 13565 Slog.d(TAG, "Propagating install state across downgrade"); 13566 } 13567 for (int i = 0; i < allUserHandles.length; i++) { 13568 if (DEBUG_REMOVE) { 13569 Slog.d(TAG, " user " + allUserHandles[i] 13570 + " => " + perUserInstalled[i]); 13571 } 13572 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13573 } 13574 } 13575 } 13576 // can downgrade to reader 13577 if (writeSettings) { 13578 // Save settings now 13579 mSettings.writeLPr(); 13580 } 13581 } 13582 if (outInfo != null) { 13583 // A user ID was deleted here. Go through all users and remove it 13584 // from KeyStore. 13585 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 13586 } 13587 } 13588 13589 static boolean locationIsPrivileged(File path) { 13590 try { 13591 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 13592 .getCanonicalPath(); 13593 return path.getCanonicalPath().startsWith(privilegedAppDir); 13594 } catch (IOException e) { 13595 Slog.e(TAG, "Unable to access code path " + path); 13596 } 13597 return false; 13598 } 13599 13600 /* 13601 * Tries to delete system package. 13602 */ 13603 private boolean deleteSystemPackageLI(PackageSetting newPs, 13604 int[] allUserHandles, boolean[] perUserInstalled, 13605 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 13606 final boolean applyUserRestrictions 13607 = (allUserHandles != null) && (perUserInstalled != null); 13608 PackageSetting disabledPs = null; 13609 // Confirm if the system package has been updated 13610 // An updated system app can be deleted. This will also have to restore 13611 // the system pkg from system partition 13612 // reader 13613 synchronized (mPackages) { 13614 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13615 } 13616 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13617 + " disabledPs=" + disabledPs); 13618 if (disabledPs == null) { 13619 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13620 return false; 13621 } else if (DEBUG_REMOVE) { 13622 Slog.d(TAG, "Deleting system pkg from data partition"); 13623 } 13624 if (DEBUG_REMOVE) { 13625 if (applyUserRestrictions) { 13626 Slog.d(TAG, "Remembering install states:"); 13627 for (int i = 0; i < allUserHandles.length; i++) { 13628 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13629 } 13630 } 13631 } 13632 // Delete the updated package 13633 outInfo.isRemovedPackageSystemUpdate = true; 13634 if (disabledPs.versionCode < newPs.versionCode) { 13635 // Delete data for downgrades 13636 flags &= ~PackageManager.DELETE_KEEP_DATA; 13637 } else { 13638 // Preserve data by setting flag 13639 flags |= PackageManager.DELETE_KEEP_DATA; 13640 } 13641 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13642 allUserHandles, perUserInstalled, outInfo, writeSettings); 13643 if (!ret) { 13644 return false; 13645 } 13646 // writer 13647 synchronized (mPackages) { 13648 // Reinstate the old system package 13649 mSettings.enableSystemPackageLPw(newPs.name); 13650 // Remove any native libraries from the upgraded package. 13651 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13652 } 13653 // Install the system package 13654 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13655 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13656 if (locationIsPrivileged(disabledPs.codePath)) { 13657 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13658 } 13659 13660 final PackageParser.Package newPkg; 13661 try { 13662 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 13663 } catch (PackageManagerException e) { 13664 Slog.w(TAG, "Failed to restore system package " + newPs.name + ": " + e.getMessage()); 13665 return false; 13666 } 13667 13668 prepareAppDataAfterInstall(newPkg); 13669 13670 // writer 13671 synchronized (mPackages) { 13672 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13673 13674 // Propagate the permissions state as we do not want to drop on the floor 13675 // runtime permissions. The update permissions method below will take 13676 // care of removing obsolete permissions and grant install permissions. 13677 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13678 updatePermissionsLPw(newPkg.packageName, newPkg, 13679 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13680 13681 if (applyUserRestrictions) { 13682 if (DEBUG_REMOVE) { 13683 Slog.d(TAG, "Propagating install state across reinstall"); 13684 } 13685 for (int i = 0; i < allUserHandles.length; i++) { 13686 if (DEBUG_REMOVE) { 13687 Slog.d(TAG, " user " + allUserHandles[i] 13688 + " => " + perUserInstalled[i]); 13689 } 13690 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13691 13692 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13693 } 13694 // Regardless of writeSettings we need to ensure that this restriction 13695 // state propagation is persisted 13696 mSettings.writeAllUsersPackageRestrictionsLPr(); 13697 } 13698 // can downgrade to reader here 13699 if (writeSettings) { 13700 mSettings.writeLPr(); 13701 } 13702 } 13703 return true; 13704 } 13705 13706 private boolean deleteInstalledPackageLI(PackageSetting ps, 13707 boolean deleteCodeAndResources, int flags, 13708 int[] allUserHandles, boolean[] perUserInstalled, 13709 PackageRemovedInfo outInfo, boolean writeSettings) { 13710 if (outInfo != null) { 13711 outInfo.uid = ps.appId; 13712 } 13713 13714 // Delete package data from internal structures and also remove data if flag is set 13715 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13716 13717 // Delete application code and resources 13718 if (deleteCodeAndResources && (outInfo != null)) { 13719 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13720 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13721 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13722 } 13723 return true; 13724 } 13725 13726 @Override 13727 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13728 int userId) { 13729 mContext.enforceCallingOrSelfPermission( 13730 android.Manifest.permission.DELETE_PACKAGES, null); 13731 synchronized (mPackages) { 13732 PackageSetting ps = mSettings.mPackages.get(packageName); 13733 if (ps == null) { 13734 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13735 return false; 13736 } 13737 if (!ps.getInstalled(userId)) { 13738 // Can't block uninstall for an app that is not installed or enabled. 13739 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13740 return false; 13741 } 13742 ps.setBlockUninstall(blockUninstall, userId); 13743 mSettings.writePackageRestrictionsLPr(userId); 13744 } 13745 return true; 13746 } 13747 13748 @Override 13749 public boolean getBlockUninstallForUser(String packageName, int userId) { 13750 synchronized (mPackages) { 13751 PackageSetting ps = mSettings.mPackages.get(packageName); 13752 if (ps == null) { 13753 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13754 return false; 13755 } 13756 return ps.getBlockUninstall(userId); 13757 } 13758 } 13759 13760 @Override 13761 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 13762 int callingUid = Binder.getCallingUid(); 13763 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 13764 throw new SecurityException( 13765 "setRequiredForSystemUser can only be run by the system or root"); 13766 } 13767 synchronized (mPackages) { 13768 PackageSetting ps = mSettings.mPackages.get(packageName); 13769 if (ps == null) { 13770 Log.w(TAG, "Package doesn't exist: " + packageName); 13771 return false; 13772 } 13773 if (systemUserApp) { 13774 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 13775 } else { 13776 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 13777 } 13778 mSettings.writeLPr(); 13779 } 13780 return true; 13781 } 13782 13783 /* 13784 * This method handles package deletion in general 13785 */ 13786 private boolean deletePackageLI(String packageName, UserHandle user, 13787 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13788 int flags, PackageRemovedInfo outInfo, 13789 boolean writeSettings) { 13790 if (packageName == null) { 13791 Slog.w(TAG, "Attempt to delete null packageName."); 13792 return false; 13793 } 13794 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13795 PackageSetting ps; 13796 boolean dataOnly = false; 13797 int removeUser = -1; 13798 int appId = -1; 13799 synchronized (mPackages) { 13800 ps = mSettings.mPackages.get(packageName); 13801 if (ps == null) { 13802 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13803 return false; 13804 } 13805 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13806 && user.getIdentifier() != UserHandle.USER_ALL) { 13807 // The caller is asking that the package only be deleted for a single 13808 // user. To do this, we just mark its uninstalled state and delete 13809 // its data. If this is a system app, we only allow this to happen if 13810 // they have set the special DELETE_SYSTEM_APP which requests different 13811 // semantics than normal for uninstalling system apps. 13812 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13813 final int userId = user.getIdentifier(); 13814 ps.setUserState(userId, 13815 COMPONENT_ENABLED_STATE_DEFAULT, 13816 false, //installed 13817 true, //stopped 13818 true, //notLaunched 13819 false, //hidden 13820 false, //suspended 13821 null, null, null, 13822 false, // blockUninstall 13823 ps.readUserState(userId).domainVerificationStatus, 0); 13824 if (!isSystemApp(ps)) { 13825 // Do not uninstall the APK if an app should be cached 13826 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 13827 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 13828 // Other user still have this package installed, so all 13829 // we need to do is clear this user's data and save that 13830 // it is uninstalled. 13831 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13832 removeUser = user.getIdentifier(); 13833 appId = ps.appId; 13834 scheduleWritePackageRestrictionsLocked(removeUser); 13835 } else { 13836 // We need to set it back to 'installed' so the uninstall 13837 // broadcasts will be sent correctly. 13838 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13839 ps.setInstalled(true, user.getIdentifier()); 13840 } 13841 } else { 13842 // This is a system app, so we assume that the 13843 // other users still have this package installed, so all 13844 // we need to do is clear this user's data and save that 13845 // it is uninstalled. 13846 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13847 removeUser = user.getIdentifier(); 13848 appId = ps.appId; 13849 scheduleWritePackageRestrictionsLocked(removeUser); 13850 } 13851 } 13852 } 13853 13854 if (removeUser >= 0) { 13855 // From above, we determined that we are deleting this only 13856 // for a single user. Continue the work here. 13857 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13858 if (outInfo != null) { 13859 outInfo.removedPackage = packageName; 13860 outInfo.removedAppId = appId; 13861 outInfo.removedUsers = new int[] {removeUser}; 13862 } 13863 // TODO: triage flags as part of 26466827 13864 final int installerFlags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 13865 try { 13866 mInstaller.destroyAppData(ps.volumeUuid, packageName, removeUser, installerFlags); 13867 } catch (InstallerException e) { 13868 Slog.w(TAG, "Failed to delete app data", e); 13869 } 13870 removeKeystoreDataIfNeeded(removeUser, appId); 13871 schedulePackageCleaning(packageName, removeUser, false); 13872 synchronized (mPackages) { 13873 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13874 scheduleWritePackageRestrictionsLocked(removeUser); 13875 } 13876 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13877 } 13878 return true; 13879 } 13880 13881 if (dataOnly) { 13882 // Delete application data first 13883 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13884 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13885 return true; 13886 } 13887 13888 boolean ret = false; 13889 if (isSystemApp(ps)) { 13890 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 13891 // When an updated system application is deleted we delete the existing resources as well and 13892 // fall back to existing code in system partition 13893 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13894 flags, outInfo, writeSettings); 13895 } else { 13896 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 13897 // Kill application pre-emptively especially for apps on sd. 13898 killApplication(packageName, ps.appId, "uninstall pkg"); 13899 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13900 allUserHandles, perUserInstalled, 13901 outInfo, writeSettings); 13902 } 13903 13904 return ret; 13905 } 13906 13907 private final static class ClearStorageConnection implements ServiceConnection { 13908 IMediaContainerService mContainerService; 13909 13910 @Override 13911 public void onServiceConnected(ComponentName name, IBinder service) { 13912 synchronized (this) { 13913 mContainerService = IMediaContainerService.Stub.asInterface(service); 13914 notifyAll(); 13915 } 13916 } 13917 13918 @Override 13919 public void onServiceDisconnected(ComponentName name) { 13920 } 13921 } 13922 13923 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13924 final boolean mounted; 13925 if (Environment.isExternalStorageEmulated()) { 13926 mounted = true; 13927 } else { 13928 final String status = Environment.getExternalStorageState(); 13929 13930 mounted = status.equals(Environment.MEDIA_MOUNTED) 13931 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13932 } 13933 13934 if (!mounted) { 13935 return; 13936 } 13937 13938 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13939 int[] users; 13940 if (userId == UserHandle.USER_ALL) { 13941 users = sUserManager.getUserIds(); 13942 } else { 13943 users = new int[] { userId }; 13944 } 13945 final ClearStorageConnection conn = new ClearStorageConnection(); 13946 if (mContext.bindServiceAsUser( 13947 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 13948 try { 13949 for (int curUser : users) { 13950 long timeout = SystemClock.uptimeMillis() + 5000; 13951 synchronized (conn) { 13952 long now = SystemClock.uptimeMillis(); 13953 while (conn.mContainerService == null && now < timeout) { 13954 try { 13955 conn.wait(timeout - now); 13956 } catch (InterruptedException e) { 13957 } 13958 } 13959 } 13960 if (conn.mContainerService == null) { 13961 return; 13962 } 13963 13964 final UserEnvironment userEnv = new UserEnvironment(curUser); 13965 clearDirectory(conn.mContainerService, 13966 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13967 if (allData) { 13968 clearDirectory(conn.mContainerService, 13969 userEnv.buildExternalStorageAppDataDirs(packageName)); 13970 clearDirectory(conn.mContainerService, 13971 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13972 } 13973 } 13974 } finally { 13975 mContext.unbindService(conn); 13976 } 13977 } 13978 } 13979 13980 @Override 13981 public void clearApplicationUserData(final String packageName, 13982 final IPackageDataObserver observer, final int userId) { 13983 mContext.enforceCallingOrSelfPermission( 13984 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13985 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13986 // Queue up an async operation since the package deletion may take a little while. 13987 mHandler.post(new Runnable() { 13988 public void run() { 13989 mHandler.removeCallbacks(this); 13990 final boolean succeeded; 13991 synchronized (mInstallLock) { 13992 succeeded = clearApplicationUserDataLI(packageName, userId); 13993 } 13994 clearExternalStorageDataSync(packageName, userId, true); 13995 if (succeeded) { 13996 // invoke DeviceStorageMonitor's update method to clear any notifications 13997 DeviceStorageMonitorInternal 13998 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13999 if (dsm != null) { 14000 dsm.checkMemory(); 14001 } 14002 } 14003 if(observer != null) { 14004 try { 14005 observer.onRemoveCompleted(packageName, succeeded); 14006 } catch (RemoteException e) { 14007 Log.i(TAG, "Observer no longer exists."); 14008 } 14009 } //end if observer 14010 } //end run 14011 }); 14012 } 14013 14014 private boolean clearApplicationUserDataLI(String packageName, int userId) { 14015 if (packageName == null) { 14016 Slog.w(TAG, "Attempt to delete null packageName."); 14017 return false; 14018 } 14019 14020 // Try finding details about the requested package 14021 PackageParser.Package pkg; 14022 synchronized (mPackages) { 14023 pkg = mPackages.get(packageName); 14024 if (pkg == null) { 14025 final PackageSetting ps = mSettings.mPackages.get(packageName); 14026 if (ps != null) { 14027 pkg = ps.pkg; 14028 } 14029 } 14030 14031 if (pkg == null) { 14032 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 14033 return false; 14034 } 14035 14036 PackageSetting ps = (PackageSetting) pkg.mExtras; 14037 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 14038 } 14039 14040 // Always delete data directories for package, even if we found no other 14041 // record of app. This helps users recover from UID mismatches without 14042 // resorting to a full data wipe. 14043 // TODO: triage flags as part of 26466827 14044 final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 14045 try { 14046 mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags); 14047 } catch (InstallerException e) { 14048 Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e); 14049 return false; 14050 } 14051 14052 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 14053 removeKeystoreDataIfNeeded(userId, appId); 14054 14055 // Create a native library symlink only if we have native libraries 14056 // and if the native libraries are 32 bit libraries. We do not provide 14057 // this symlink for 64 bit libraries. 14058 if (pkg.applicationInfo.primaryCpuAbi != null && 14059 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 14060 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 14061 try { 14062 mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 14063 nativeLibPath, userId); 14064 } catch (InstallerException e) { 14065 Slog.w(TAG, "Failed linking native library dir", e); 14066 return false; 14067 } 14068 } 14069 14070 return true; 14071 } 14072 14073 /** 14074 * Reverts user permission state changes (permissions and flags) in 14075 * all packages for a given user. 14076 * 14077 * @param userId The device user for which to do a reset. 14078 */ 14079 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 14080 final int packageCount = mPackages.size(); 14081 for (int i = 0; i < packageCount; i++) { 14082 PackageParser.Package pkg = mPackages.valueAt(i); 14083 PackageSetting ps = (PackageSetting) pkg.mExtras; 14084 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 14085 } 14086 } 14087 14088 /** 14089 * Reverts user permission state changes (permissions and flags). 14090 * 14091 * @param ps The package for which to reset. 14092 * @param userId The device user for which to do a reset. 14093 */ 14094 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 14095 final PackageSetting ps, final int userId) { 14096 if (ps.pkg == null) { 14097 return; 14098 } 14099 14100 // These are flags that can change base on user actions. 14101 final int userSettableMask = FLAG_PERMISSION_USER_SET 14102 | FLAG_PERMISSION_USER_FIXED 14103 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 14104 | FLAG_PERMISSION_REVIEW_REQUIRED; 14105 14106 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 14107 | FLAG_PERMISSION_POLICY_FIXED; 14108 14109 boolean writeInstallPermissions = false; 14110 boolean writeRuntimePermissions = false; 14111 14112 final int permissionCount = ps.pkg.requestedPermissions.size(); 14113 for (int i = 0; i < permissionCount; i++) { 14114 String permission = ps.pkg.requestedPermissions.get(i); 14115 14116 BasePermission bp = mSettings.mPermissions.get(permission); 14117 if (bp == null) { 14118 continue; 14119 } 14120 14121 // If shared user we just reset the state to which only this app contributed. 14122 if (ps.sharedUser != null) { 14123 boolean used = false; 14124 final int packageCount = ps.sharedUser.packages.size(); 14125 for (int j = 0; j < packageCount; j++) { 14126 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 14127 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 14128 && pkg.pkg.requestedPermissions.contains(permission)) { 14129 used = true; 14130 break; 14131 } 14132 } 14133 if (used) { 14134 continue; 14135 } 14136 } 14137 14138 PermissionsState permissionsState = ps.getPermissionsState(); 14139 14140 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 14141 14142 // Always clear the user settable flags. 14143 final boolean hasInstallState = permissionsState.getInstallPermissionState( 14144 bp.name) != null; 14145 // If permission review is enabled and this is a legacy app, mark the 14146 // permission as requiring a review as this is the initial state. 14147 int flags = 0; 14148 if (Build.PERMISSIONS_REVIEW_REQUIRED 14149 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 14150 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 14151 } 14152 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 14153 if (hasInstallState) { 14154 writeInstallPermissions = true; 14155 } else { 14156 writeRuntimePermissions = true; 14157 } 14158 } 14159 14160 // Below is only runtime permission handling. 14161 if (!bp.isRuntime()) { 14162 continue; 14163 } 14164 14165 // Never clobber system or policy. 14166 if ((oldFlags & policyOrSystemFlags) != 0) { 14167 continue; 14168 } 14169 14170 // If this permission was granted by default, make sure it is. 14171 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 14172 if (permissionsState.grantRuntimePermission(bp, userId) 14173 != PERMISSION_OPERATION_FAILURE) { 14174 writeRuntimePermissions = true; 14175 } 14176 // If permission review is enabled the permissions for a legacy apps 14177 // are represented as constantly granted runtime ones, so don't revoke. 14178 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 14179 // Otherwise, reset the permission. 14180 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 14181 switch (revokeResult) { 14182 case PERMISSION_OPERATION_SUCCESS: { 14183 writeRuntimePermissions = true; 14184 } break; 14185 14186 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 14187 writeRuntimePermissions = true; 14188 final int appId = ps.appId; 14189 mHandler.post(new Runnable() { 14190 @Override 14191 public void run() { 14192 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 14193 } 14194 }); 14195 } break; 14196 } 14197 } 14198 } 14199 14200 // Synchronously write as we are taking permissions away. 14201 if (writeRuntimePermissions) { 14202 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 14203 } 14204 14205 // Synchronously write as we are taking permissions away. 14206 if (writeInstallPermissions) { 14207 mSettings.writeLPr(); 14208 } 14209 } 14210 14211 /** 14212 * Remove entries from the keystore daemon. Will only remove it if the 14213 * {@code appId} is valid. 14214 */ 14215 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 14216 if (appId < 0) { 14217 return; 14218 } 14219 14220 final KeyStore keyStore = KeyStore.getInstance(); 14221 if (keyStore != null) { 14222 if (userId == UserHandle.USER_ALL) { 14223 for (final int individual : sUserManager.getUserIds()) { 14224 keyStore.clearUid(UserHandle.getUid(individual, appId)); 14225 } 14226 } else { 14227 keyStore.clearUid(UserHandle.getUid(userId, appId)); 14228 } 14229 } else { 14230 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 14231 } 14232 } 14233 14234 @Override 14235 public void deleteApplicationCacheFiles(final String packageName, 14236 final IPackageDataObserver observer) { 14237 mContext.enforceCallingOrSelfPermission( 14238 android.Manifest.permission.DELETE_CACHE_FILES, null); 14239 // Queue up an async operation since the package deletion may take a little while. 14240 final int userId = UserHandle.getCallingUserId(); 14241 mHandler.post(new Runnable() { 14242 public void run() { 14243 mHandler.removeCallbacks(this); 14244 final boolean succeded; 14245 synchronized (mInstallLock) { 14246 succeded = deleteApplicationCacheFilesLI(packageName, userId); 14247 } 14248 clearExternalStorageDataSync(packageName, userId, false); 14249 if (observer != null) { 14250 try { 14251 observer.onRemoveCompleted(packageName, succeded); 14252 } catch (RemoteException e) { 14253 Log.i(TAG, "Observer no longer exists."); 14254 } 14255 } //end if observer 14256 } //end run 14257 }); 14258 } 14259 14260 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 14261 if (packageName == null) { 14262 Slog.w(TAG, "Attempt to delete null packageName."); 14263 return false; 14264 } 14265 PackageParser.Package p; 14266 synchronized (mPackages) { 14267 p = mPackages.get(packageName); 14268 } 14269 if (p == null) { 14270 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14271 return false; 14272 } 14273 final ApplicationInfo applicationInfo = p.applicationInfo; 14274 if (applicationInfo == null) { 14275 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14276 return false; 14277 } 14278 // TODO: triage flags as part of 26466827 14279 final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 14280 try { 14281 mInstaller.clearAppData(p.volumeUuid, packageName, userId, 14282 flags | Installer.FLAG_CLEAR_CACHE_ONLY); 14283 } catch (InstallerException e) { 14284 Slog.w(TAG, "Couldn't remove cache files for package " 14285 + packageName + " u" + userId, e); 14286 return false; 14287 } 14288 return true; 14289 } 14290 14291 @Override 14292 public void getPackageSizeInfo(final String packageName, int userHandle, 14293 final IPackageStatsObserver observer) { 14294 mContext.enforceCallingOrSelfPermission( 14295 android.Manifest.permission.GET_PACKAGE_SIZE, null); 14296 if (packageName == null) { 14297 throw new IllegalArgumentException("Attempt to get size of null packageName"); 14298 } 14299 14300 PackageStats stats = new PackageStats(packageName, userHandle); 14301 14302 /* 14303 * Queue up an async operation since the package measurement may take a 14304 * little while. 14305 */ 14306 Message msg = mHandler.obtainMessage(INIT_COPY); 14307 msg.obj = new MeasureParams(stats, observer); 14308 mHandler.sendMessage(msg); 14309 } 14310 14311 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 14312 PackageStats pStats) { 14313 if (packageName == null) { 14314 Slog.w(TAG, "Attempt to get size of null packageName."); 14315 return false; 14316 } 14317 PackageParser.Package p; 14318 boolean dataOnly = false; 14319 String libDirRoot = null; 14320 String asecPath = null; 14321 PackageSetting ps = null; 14322 synchronized (mPackages) { 14323 p = mPackages.get(packageName); 14324 ps = mSettings.mPackages.get(packageName); 14325 if(p == null) { 14326 dataOnly = true; 14327 if((ps == null) || (ps.pkg == null)) { 14328 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14329 return false; 14330 } 14331 p = ps.pkg; 14332 } 14333 if (ps != null) { 14334 libDirRoot = ps.legacyNativeLibraryPathString; 14335 } 14336 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 14337 final long token = Binder.clearCallingIdentity(); 14338 try { 14339 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 14340 if (secureContainerId != null) { 14341 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 14342 } 14343 } finally { 14344 Binder.restoreCallingIdentity(token); 14345 } 14346 } 14347 } 14348 String publicSrcDir = null; 14349 if(!dataOnly) { 14350 final ApplicationInfo applicationInfo = p.applicationInfo; 14351 if (applicationInfo == null) { 14352 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14353 return false; 14354 } 14355 if (p.isForwardLocked()) { 14356 publicSrcDir = applicationInfo.getBaseResourcePath(); 14357 } 14358 } 14359 // TODO: extend to measure size of split APKs 14360 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 14361 // not just the first level. 14362 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 14363 // just the primary. 14364 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 14365 14366 String apkPath; 14367 File packageDir = new File(p.codePath); 14368 14369 if (packageDir.isDirectory() && p.canHaveOatDir()) { 14370 apkPath = packageDir.getAbsolutePath(); 14371 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 14372 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 14373 libDirRoot = null; 14374 } 14375 } else { 14376 apkPath = p.baseCodePath; 14377 } 14378 14379 // TODO: triage flags as part of 26466827 14380 final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 14381 try { 14382 mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath, 14383 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 14384 } catch (InstallerException e) { 14385 return false; 14386 } 14387 14388 // Fix-up for forward-locked applications in ASEC containers. 14389 if (!isExternal(p)) { 14390 pStats.codeSize += pStats.externalCodeSize; 14391 pStats.externalCodeSize = 0L; 14392 } 14393 14394 return true; 14395 } 14396 14397 14398 @Override 14399 public void addPackageToPreferred(String packageName) { 14400 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 14401 } 14402 14403 @Override 14404 public void removePackageFromPreferred(String packageName) { 14405 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 14406 } 14407 14408 @Override 14409 public List<PackageInfo> getPreferredPackages(int flags) { 14410 return new ArrayList<PackageInfo>(); 14411 } 14412 14413 private int getUidTargetSdkVersionLockedLPr(int uid) { 14414 Object obj = mSettings.getUserIdLPr(uid); 14415 if (obj instanceof SharedUserSetting) { 14416 final SharedUserSetting sus = (SharedUserSetting) obj; 14417 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 14418 final Iterator<PackageSetting> it = sus.packages.iterator(); 14419 while (it.hasNext()) { 14420 final PackageSetting ps = it.next(); 14421 if (ps.pkg != null) { 14422 int v = ps.pkg.applicationInfo.targetSdkVersion; 14423 if (v < vers) vers = v; 14424 } 14425 } 14426 return vers; 14427 } else if (obj instanceof PackageSetting) { 14428 final PackageSetting ps = (PackageSetting) obj; 14429 if (ps.pkg != null) { 14430 return ps.pkg.applicationInfo.targetSdkVersion; 14431 } 14432 } 14433 return Build.VERSION_CODES.CUR_DEVELOPMENT; 14434 } 14435 14436 @Override 14437 public void addPreferredActivity(IntentFilter filter, int match, 14438 ComponentName[] set, ComponentName activity, int userId) { 14439 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14440 "Adding preferred"); 14441 } 14442 14443 private void addPreferredActivityInternal(IntentFilter filter, int match, 14444 ComponentName[] set, ComponentName activity, boolean always, int userId, 14445 String opname) { 14446 // writer 14447 int callingUid = Binder.getCallingUid(); 14448 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 14449 if (filter.countActions() == 0) { 14450 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14451 return; 14452 } 14453 synchronized (mPackages) { 14454 if (mContext.checkCallingOrSelfPermission( 14455 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14456 != PackageManager.PERMISSION_GRANTED) { 14457 if (getUidTargetSdkVersionLockedLPr(callingUid) 14458 < Build.VERSION_CODES.FROYO) { 14459 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 14460 + callingUid); 14461 return; 14462 } 14463 mContext.enforceCallingOrSelfPermission( 14464 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14465 } 14466 14467 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 14468 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 14469 + userId + ":"); 14470 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14471 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 14472 scheduleWritePackageRestrictionsLocked(userId); 14473 } 14474 } 14475 14476 @Override 14477 public void replacePreferredActivity(IntentFilter filter, int match, 14478 ComponentName[] set, ComponentName activity, int userId) { 14479 if (filter.countActions() != 1) { 14480 throw new IllegalArgumentException( 14481 "replacePreferredActivity expects filter to have only 1 action."); 14482 } 14483 if (filter.countDataAuthorities() != 0 14484 || filter.countDataPaths() != 0 14485 || filter.countDataSchemes() > 1 14486 || filter.countDataTypes() != 0) { 14487 throw new IllegalArgumentException( 14488 "replacePreferredActivity expects filter to have no data authorities, " + 14489 "paths, or types; and at most one scheme."); 14490 } 14491 14492 final int callingUid = Binder.getCallingUid(); 14493 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 14494 synchronized (mPackages) { 14495 if (mContext.checkCallingOrSelfPermission( 14496 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14497 != PackageManager.PERMISSION_GRANTED) { 14498 if (getUidTargetSdkVersionLockedLPr(callingUid) 14499 < Build.VERSION_CODES.FROYO) { 14500 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 14501 + Binder.getCallingUid()); 14502 return; 14503 } 14504 mContext.enforceCallingOrSelfPermission( 14505 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14506 } 14507 14508 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14509 if (pir != null) { 14510 // Get all of the existing entries that exactly match this filter. 14511 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 14512 if (existing != null && existing.size() == 1) { 14513 PreferredActivity cur = existing.get(0); 14514 if (DEBUG_PREFERRED) { 14515 Slog.i(TAG, "Checking replace of preferred:"); 14516 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14517 if (!cur.mPref.mAlways) { 14518 Slog.i(TAG, " -- CUR; not mAlways!"); 14519 } else { 14520 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 14521 Slog.i(TAG, " -- CUR: mSet=" 14522 + Arrays.toString(cur.mPref.mSetComponents)); 14523 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 14524 Slog.i(TAG, " -- NEW: mMatch=" 14525 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 14526 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 14527 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 14528 } 14529 } 14530 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 14531 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 14532 && cur.mPref.sameSet(set)) { 14533 // Setting the preferred activity to what it happens to be already 14534 if (DEBUG_PREFERRED) { 14535 Slog.i(TAG, "Replacing with same preferred activity " 14536 + cur.mPref.mShortComponent + " for user " 14537 + userId + ":"); 14538 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14539 } 14540 return; 14541 } 14542 } 14543 14544 if (existing != null) { 14545 if (DEBUG_PREFERRED) { 14546 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 14547 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14548 } 14549 for (int i = 0; i < existing.size(); i++) { 14550 PreferredActivity pa = existing.get(i); 14551 if (DEBUG_PREFERRED) { 14552 Slog.i(TAG, "Removing existing preferred activity " 14553 + pa.mPref.mComponent + ":"); 14554 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 14555 } 14556 pir.removeFilter(pa); 14557 } 14558 } 14559 } 14560 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14561 "Replacing preferred"); 14562 } 14563 } 14564 14565 @Override 14566 public void clearPackagePreferredActivities(String packageName) { 14567 final int uid = Binder.getCallingUid(); 14568 // writer 14569 synchronized (mPackages) { 14570 PackageParser.Package pkg = mPackages.get(packageName); 14571 if (pkg == null || pkg.applicationInfo.uid != uid) { 14572 if (mContext.checkCallingOrSelfPermission( 14573 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14574 != PackageManager.PERMISSION_GRANTED) { 14575 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 14576 < Build.VERSION_CODES.FROYO) { 14577 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 14578 + Binder.getCallingUid()); 14579 return; 14580 } 14581 mContext.enforceCallingOrSelfPermission( 14582 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14583 } 14584 } 14585 14586 int user = UserHandle.getCallingUserId(); 14587 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 14588 scheduleWritePackageRestrictionsLocked(user); 14589 } 14590 } 14591 } 14592 14593 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14594 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 14595 ArrayList<PreferredActivity> removed = null; 14596 boolean changed = false; 14597 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14598 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 14599 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14600 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 14601 continue; 14602 } 14603 Iterator<PreferredActivity> it = pir.filterIterator(); 14604 while (it.hasNext()) { 14605 PreferredActivity pa = it.next(); 14606 // Mark entry for removal only if it matches the package name 14607 // and the entry is of type "always". 14608 if (packageName == null || 14609 (pa.mPref.mComponent.getPackageName().equals(packageName) 14610 && pa.mPref.mAlways)) { 14611 if (removed == null) { 14612 removed = new ArrayList<PreferredActivity>(); 14613 } 14614 removed.add(pa); 14615 } 14616 } 14617 if (removed != null) { 14618 for (int j=0; j<removed.size(); j++) { 14619 PreferredActivity pa = removed.get(j); 14620 pir.removeFilter(pa); 14621 } 14622 changed = true; 14623 } 14624 } 14625 return changed; 14626 } 14627 14628 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14629 private void clearIntentFilterVerificationsLPw(int userId) { 14630 final int packageCount = mPackages.size(); 14631 for (int i = 0; i < packageCount; i++) { 14632 PackageParser.Package pkg = mPackages.valueAt(i); 14633 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 14634 } 14635 } 14636 14637 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14638 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 14639 if (userId == UserHandle.USER_ALL) { 14640 if (mSettings.removeIntentFilterVerificationLPw(packageName, 14641 sUserManager.getUserIds())) { 14642 for (int oneUserId : sUserManager.getUserIds()) { 14643 scheduleWritePackageRestrictionsLocked(oneUserId); 14644 } 14645 } 14646 } else { 14647 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 14648 scheduleWritePackageRestrictionsLocked(userId); 14649 } 14650 } 14651 } 14652 14653 void clearDefaultBrowserIfNeeded(String packageName) { 14654 for (int oneUserId : sUserManager.getUserIds()) { 14655 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 14656 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 14657 if (packageName.equals(defaultBrowserPackageName)) { 14658 setDefaultBrowserPackageName(null, oneUserId); 14659 } 14660 } 14661 } 14662 14663 @Override 14664 public void resetApplicationPreferences(int userId) { 14665 mContext.enforceCallingOrSelfPermission( 14666 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14667 // writer 14668 synchronized (mPackages) { 14669 final long identity = Binder.clearCallingIdentity(); 14670 try { 14671 clearPackagePreferredActivitiesLPw(null, userId); 14672 mSettings.applyDefaultPreferredAppsLPw(this, userId); 14673 // TODO: We have to reset the default SMS and Phone. This requires 14674 // significant refactoring to keep all default apps in the package 14675 // manager (cleaner but more work) or have the services provide 14676 // callbacks to the package manager to request a default app reset. 14677 applyFactoryDefaultBrowserLPw(userId); 14678 clearIntentFilterVerificationsLPw(userId); 14679 primeDomainVerificationsLPw(userId); 14680 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 14681 scheduleWritePackageRestrictionsLocked(userId); 14682 } finally { 14683 Binder.restoreCallingIdentity(identity); 14684 } 14685 } 14686 } 14687 14688 @Override 14689 public int getPreferredActivities(List<IntentFilter> outFilters, 14690 List<ComponentName> outActivities, String packageName) { 14691 14692 int num = 0; 14693 final int userId = UserHandle.getCallingUserId(); 14694 // reader 14695 synchronized (mPackages) { 14696 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14697 if (pir != null) { 14698 final Iterator<PreferredActivity> it = pir.filterIterator(); 14699 while (it.hasNext()) { 14700 final PreferredActivity pa = it.next(); 14701 if (packageName == null 14702 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14703 && pa.mPref.mAlways)) { 14704 if (outFilters != null) { 14705 outFilters.add(new IntentFilter(pa)); 14706 } 14707 if (outActivities != null) { 14708 outActivities.add(pa.mPref.mComponent); 14709 } 14710 } 14711 } 14712 } 14713 } 14714 14715 return num; 14716 } 14717 14718 @Override 14719 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14720 int userId) { 14721 int callingUid = Binder.getCallingUid(); 14722 if (callingUid != Process.SYSTEM_UID) { 14723 throw new SecurityException( 14724 "addPersistentPreferredActivity can only be run by the system"); 14725 } 14726 if (filter.countActions() == 0) { 14727 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14728 return; 14729 } 14730 synchronized (mPackages) { 14731 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14732 ":"); 14733 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14734 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14735 new PersistentPreferredActivity(filter, activity)); 14736 scheduleWritePackageRestrictionsLocked(userId); 14737 } 14738 } 14739 14740 @Override 14741 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14742 int callingUid = Binder.getCallingUid(); 14743 if (callingUid != Process.SYSTEM_UID) { 14744 throw new SecurityException( 14745 "clearPackagePersistentPreferredActivities can only be run by the system"); 14746 } 14747 ArrayList<PersistentPreferredActivity> removed = null; 14748 boolean changed = false; 14749 synchronized (mPackages) { 14750 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14751 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14752 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14753 .valueAt(i); 14754 if (userId != thisUserId) { 14755 continue; 14756 } 14757 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14758 while (it.hasNext()) { 14759 PersistentPreferredActivity ppa = it.next(); 14760 // Mark entry for removal only if it matches the package name. 14761 if (ppa.mComponent.getPackageName().equals(packageName)) { 14762 if (removed == null) { 14763 removed = new ArrayList<PersistentPreferredActivity>(); 14764 } 14765 removed.add(ppa); 14766 } 14767 } 14768 if (removed != null) { 14769 for (int j=0; j<removed.size(); j++) { 14770 PersistentPreferredActivity ppa = removed.get(j); 14771 ppir.removeFilter(ppa); 14772 } 14773 changed = true; 14774 } 14775 } 14776 14777 if (changed) { 14778 scheduleWritePackageRestrictionsLocked(userId); 14779 } 14780 } 14781 } 14782 14783 /** 14784 * Common machinery for picking apart a restored XML blob and passing 14785 * it to a caller-supplied functor to be applied to the running system. 14786 */ 14787 private void restoreFromXml(XmlPullParser parser, int userId, 14788 String expectedStartTag, BlobXmlRestorer functor) 14789 throws IOException, XmlPullParserException { 14790 int type; 14791 while ((type = parser.next()) != XmlPullParser.START_TAG 14792 && type != XmlPullParser.END_DOCUMENT) { 14793 } 14794 if (type != XmlPullParser.START_TAG) { 14795 // oops didn't find a start tag?! 14796 if (DEBUG_BACKUP) { 14797 Slog.e(TAG, "Didn't find start tag during restore"); 14798 } 14799 return; 14800 } 14801Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 14802 // this is supposed to be TAG_PREFERRED_BACKUP 14803 if (!expectedStartTag.equals(parser.getName())) { 14804 if (DEBUG_BACKUP) { 14805 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14806 } 14807 return; 14808 } 14809 14810 // skip interfering stuff, then we're aligned with the backing implementation 14811 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14812Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 14813 functor.apply(parser, userId); 14814 } 14815 14816 private interface BlobXmlRestorer { 14817 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14818 } 14819 14820 /** 14821 * Non-Binder method, support for the backup/restore mechanism: write the 14822 * full set of preferred activities in its canonical XML format. Returns the 14823 * XML output as a byte array, or null if there is none. 14824 */ 14825 @Override 14826 public byte[] getPreferredActivityBackup(int userId) { 14827 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14828 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14829 } 14830 14831 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14832 try { 14833 final XmlSerializer serializer = new FastXmlSerializer(); 14834 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14835 serializer.startDocument(null, true); 14836 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14837 14838 synchronized (mPackages) { 14839 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14840 } 14841 14842 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14843 serializer.endDocument(); 14844 serializer.flush(); 14845 } catch (Exception e) { 14846 if (DEBUG_BACKUP) { 14847 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14848 } 14849 return null; 14850 } 14851 14852 return dataStream.toByteArray(); 14853 } 14854 14855 @Override 14856 public void restorePreferredActivities(byte[] backup, int userId) { 14857 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14858 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14859 } 14860 14861 try { 14862 final XmlPullParser parser = Xml.newPullParser(); 14863 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14864 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14865 new BlobXmlRestorer() { 14866 @Override 14867 public void apply(XmlPullParser parser, int userId) 14868 throws XmlPullParserException, IOException { 14869 synchronized (mPackages) { 14870 mSettings.readPreferredActivitiesLPw(parser, userId); 14871 } 14872 } 14873 } ); 14874 } catch (Exception e) { 14875 if (DEBUG_BACKUP) { 14876 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14877 } 14878 } 14879 } 14880 14881 /** 14882 * Non-Binder method, support for the backup/restore mechanism: write the 14883 * default browser (etc) settings in its canonical XML format. Returns the default 14884 * browser XML representation as a byte array, or null if there is none. 14885 */ 14886 @Override 14887 public byte[] getDefaultAppsBackup(int userId) { 14888 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14889 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14890 } 14891 14892 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14893 try { 14894 final XmlSerializer serializer = new FastXmlSerializer(); 14895 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14896 serializer.startDocument(null, true); 14897 serializer.startTag(null, TAG_DEFAULT_APPS); 14898 14899 synchronized (mPackages) { 14900 mSettings.writeDefaultAppsLPr(serializer, userId); 14901 } 14902 14903 serializer.endTag(null, TAG_DEFAULT_APPS); 14904 serializer.endDocument(); 14905 serializer.flush(); 14906 } catch (Exception e) { 14907 if (DEBUG_BACKUP) { 14908 Slog.e(TAG, "Unable to write default apps for backup", e); 14909 } 14910 return null; 14911 } 14912 14913 return dataStream.toByteArray(); 14914 } 14915 14916 @Override 14917 public void restoreDefaultApps(byte[] backup, int userId) { 14918 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14919 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14920 } 14921 14922 try { 14923 final XmlPullParser parser = Xml.newPullParser(); 14924 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14925 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14926 new BlobXmlRestorer() { 14927 @Override 14928 public void apply(XmlPullParser parser, int userId) 14929 throws XmlPullParserException, IOException { 14930 synchronized (mPackages) { 14931 mSettings.readDefaultAppsLPw(parser, userId); 14932 } 14933 } 14934 } ); 14935 } catch (Exception e) { 14936 if (DEBUG_BACKUP) { 14937 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14938 } 14939 } 14940 } 14941 14942 @Override 14943 public byte[] getIntentFilterVerificationBackup(int userId) { 14944 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14945 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14946 } 14947 14948 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14949 try { 14950 final XmlSerializer serializer = new FastXmlSerializer(); 14951 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14952 serializer.startDocument(null, true); 14953 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14954 14955 synchronized (mPackages) { 14956 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14957 } 14958 14959 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14960 serializer.endDocument(); 14961 serializer.flush(); 14962 } catch (Exception e) { 14963 if (DEBUG_BACKUP) { 14964 Slog.e(TAG, "Unable to write default apps for backup", e); 14965 } 14966 return null; 14967 } 14968 14969 return dataStream.toByteArray(); 14970 } 14971 14972 @Override 14973 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14974 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14975 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14976 } 14977 14978 try { 14979 final XmlPullParser parser = Xml.newPullParser(); 14980 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14981 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14982 new BlobXmlRestorer() { 14983 @Override 14984 public void apply(XmlPullParser parser, int userId) 14985 throws XmlPullParserException, IOException { 14986 synchronized (mPackages) { 14987 mSettings.readAllDomainVerificationsLPr(parser, userId); 14988 mSettings.writeLPr(); 14989 } 14990 } 14991 } ); 14992 } catch (Exception e) { 14993 if (DEBUG_BACKUP) { 14994 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14995 } 14996 } 14997 } 14998 14999 @Override 15000 public byte[] getPermissionGrantBackup(int userId) { 15001 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15002 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 15003 } 15004 15005 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 15006 try { 15007 final XmlSerializer serializer = new FastXmlSerializer(); 15008 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 15009 serializer.startDocument(null, true); 15010 serializer.startTag(null, TAG_PERMISSION_BACKUP); 15011 15012 synchronized (mPackages) { 15013 serializeRuntimePermissionGrantsLPr(serializer, userId); 15014 } 15015 15016 serializer.endTag(null, TAG_PERMISSION_BACKUP); 15017 serializer.endDocument(); 15018 serializer.flush(); 15019 } catch (Exception e) { 15020 if (DEBUG_BACKUP) { 15021 Slog.e(TAG, "Unable to write default apps for backup", e); 15022 } 15023 return null; 15024 } 15025 15026 return dataStream.toByteArray(); 15027 } 15028 15029 @Override 15030 public void restorePermissionGrants(byte[] backup, int userId) { 15031 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15032 throw new SecurityException("Only the system may call restorePermissionGrants()"); 15033 } 15034 15035 try { 15036 final XmlPullParser parser = Xml.newPullParser(); 15037 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 15038 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 15039 new BlobXmlRestorer() { 15040 @Override 15041 public void apply(XmlPullParser parser, int userId) 15042 throws XmlPullParserException, IOException { 15043 synchronized (mPackages) { 15044 processRestoredPermissionGrantsLPr(parser, userId); 15045 } 15046 } 15047 } ); 15048 } catch (Exception e) { 15049 if (DEBUG_BACKUP) { 15050 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 15051 } 15052 } 15053 } 15054 15055 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 15056 throws IOException { 15057 serializer.startTag(null, TAG_ALL_GRANTS); 15058 15059 final int N = mSettings.mPackages.size(); 15060 for (int i = 0; i < N; i++) { 15061 final PackageSetting ps = mSettings.mPackages.valueAt(i); 15062 boolean pkgGrantsKnown = false; 15063 15064 PermissionsState packagePerms = ps.getPermissionsState(); 15065 15066 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 15067 final int grantFlags = state.getFlags(); 15068 // only look at grants that are not system/policy fixed 15069 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 15070 final boolean isGranted = state.isGranted(); 15071 // And only back up the user-twiddled state bits 15072 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 15073 final String packageName = mSettings.mPackages.keyAt(i); 15074 if (!pkgGrantsKnown) { 15075 serializer.startTag(null, TAG_GRANT); 15076 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 15077 pkgGrantsKnown = true; 15078 } 15079 15080 final boolean userSet = 15081 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 15082 final boolean userFixed = 15083 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 15084 final boolean revoke = 15085 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 15086 15087 serializer.startTag(null, TAG_PERMISSION); 15088 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 15089 if (isGranted) { 15090 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 15091 } 15092 if (userSet) { 15093 serializer.attribute(null, ATTR_USER_SET, "true"); 15094 } 15095 if (userFixed) { 15096 serializer.attribute(null, ATTR_USER_FIXED, "true"); 15097 } 15098 if (revoke) { 15099 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 15100 } 15101 serializer.endTag(null, TAG_PERMISSION); 15102 } 15103 } 15104 } 15105 15106 if (pkgGrantsKnown) { 15107 serializer.endTag(null, TAG_GRANT); 15108 } 15109 } 15110 15111 serializer.endTag(null, TAG_ALL_GRANTS); 15112 } 15113 15114 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 15115 throws XmlPullParserException, IOException { 15116 String pkgName = null; 15117 int outerDepth = parser.getDepth(); 15118 int type; 15119 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 15120 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 15121 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 15122 continue; 15123 } 15124 15125 final String tagName = parser.getName(); 15126 if (tagName.equals(TAG_GRANT)) { 15127 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 15128 if (DEBUG_BACKUP) { 15129 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 15130 } 15131 } else if (tagName.equals(TAG_PERMISSION)) { 15132 15133 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 15134 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 15135 15136 int newFlagSet = 0; 15137 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 15138 newFlagSet |= FLAG_PERMISSION_USER_SET; 15139 } 15140 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 15141 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 15142 } 15143 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 15144 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 15145 } 15146 if (DEBUG_BACKUP) { 15147 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 15148 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 15149 } 15150 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15151 if (ps != null) { 15152 // Already installed so we apply the grant immediately 15153 if (DEBUG_BACKUP) { 15154 Slog.v(TAG, " + already installed; applying"); 15155 } 15156 PermissionsState perms = ps.getPermissionsState(); 15157 BasePermission bp = mSettings.mPermissions.get(permName); 15158 if (bp != null) { 15159 if (isGranted) { 15160 perms.grantRuntimePermission(bp, userId); 15161 } 15162 if (newFlagSet != 0) { 15163 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 15164 } 15165 } 15166 } else { 15167 // Need to wait for post-restore install to apply the grant 15168 if (DEBUG_BACKUP) { 15169 Slog.v(TAG, " - not yet installed; saving for later"); 15170 } 15171 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 15172 isGranted, newFlagSet, userId); 15173 } 15174 } else { 15175 PackageManagerService.reportSettingsProblem(Log.WARN, 15176 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 15177 XmlUtils.skipCurrentTag(parser); 15178 } 15179 } 15180 15181 scheduleWriteSettingsLocked(); 15182 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15183 } 15184 15185 @Override 15186 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 15187 int sourceUserId, int targetUserId, int flags) { 15188 mContext.enforceCallingOrSelfPermission( 15189 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 15190 int callingUid = Binder.getCallingUid(); 15191 enforceOwnerRights(ownerPackage, callingUid); 15192 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 15193 if (intentFilter.countActions() == 0) { 15194 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 15195 return; 15196 } 15197 synchronized (mPackages) { 15198 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 15199 ownerPackage, targetUserId, flags); 15200 CrossProfileIntentResolver resolver = 15201 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 15202 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 15203 // We have all those whose filter is equal. Now checking if the rest is equal as well. 15204 if (existing != null) { 15205 int size = existing.size(); 15206 for (int i = 0; i < size; i++) { 15207 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 15208 return; 15209 } 15210 } 15211 } 15212 resolver.addFilter(newFilter); 15213 scheduleWritePackageRestrictionsLocked(sourceUserId); 15214 } 15215 } 15216 15217 @Override 15218 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 15219 mContext.enforceCallingOrSelfPermission( 15220 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 15221 int callingUid = Binder.getCallingUid(); 15222 enforceOwnerRights(ownerPackage, callingUid); 15223 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 15224 synchronized (mPackages) { 15225 CrossProfileIntentResolver resolver = 15226 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 15227 ArraySet<CrossProfileIntentFilter> set = 15228 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 15229 for (CrossProfileIntentFilter filter : set) { 15230 if (filter.getOwnerPackage().equals(ownerPackage)) { 15231 resolver.removeFilter(filter); 15232 } 15233 } 15234 scheduleWritePackageRestrictionsLocked(sourceUserId); 15235 } 15236 } 15237 15238 // Enforcing that callingUid is owning pkg on userId 15239 private void enforceOwnerRights(String pkg, int callingUid) { 15240 // The system owns everything. 15241 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 15242 return; 15243 } 15244 int callingUserId = UserHandle.getUserId(callingUid); 15245 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 15246 if (pi == null) { 15247 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 15248 + callingUserId); 15249 } 15250 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 15251 throw new SecurityException("Calling uid " + callingUid 15252 + " does not own package " + pkg); 15253 } 15254 } 15255 15256 @Override 15257 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 15258 Intent intent = new Intent(Intent.ACTION_MAIN); 15259 intent.addCategory(Intent.CATEGORY_HOME); 15260 15261 final int callingUserId = UserHandle.getCallingUserId(); 15262 List<ResolveInfo> list = queryIntentActivities(intent, null, 15263 PackageManager.GET_META_DATA, callingUserId); 15264 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 15265 true, false, false, callingUserId); 15266 15267 allHomeCandidates.clear(); 15268 if (list != null) { 15269 for (ResolveInfo ri : list) { 15270 allHomeCandidates.add(ri); 15271 } 15272 } 15273 return (preferred == null || preferred.activityInfo == null) 15274 ? null 15275 : new ComponentName(preferred.activityInfo.packageName, 15276 preferred.activityInfo.name); 15277 } 15278 15279 @Override 15280 public void setApplicationEnabledSetting(String appPackageName, 15281 int newState, int flags, int userId, String callingPackage) { 15282 if (!sUserManager.exists(userId)) return; 15283 if (callingPackage == null) { 15284 callingPackage = Integer.toString(Binder.getCallingUid()); 15285 } 15286 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 15287 } 15288 15289 @Override 15290 public void setComponentEnabledSetting(ComponentName componentName, 15291 int newState, int flags, int userId) { 15292 if (!sUserManager.exists(userId)) return; 15293 setEnabledSetting(componentName.getPackageName(), 15294 componentName.getClassName(), newState, flags, userId, null); 15295 } 15296 15297 private void setEnabledSetting(final String packageName, String className, int newState, 15298 final int flags, int userId, String callingPackage) { 15299 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 15300 || newState == COMPONENT_ENABLED_STATE_ENABLED 15301 || newState == COMPONENT_ENABLED_STATE_DISABLED 15302 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 15303 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 15304 throw new IllegalArgumentException("Invalid new component state: " 15305 + newState); 15306 } 15307 PackageSetting pkgSetting; 15308 final int uid = Binder.getCallingUid(); 15309 final int permission = mContext.checkCallingOrSelfPermission( 15310 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 15311 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 15312 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 15313 boolean sendNow = false; 15314 boolean isApp = (className == null); 15315 String componentName = isApp ? packageName : className; 15316 int packageUid = -1; 15317 ArrayList<String> components; 15318 15319 // writer 15320 synchronized (mPackages) { 15321 pkgSetting = mSettings.mPackages.get(packageName); 15322 if (pkgSetting == null) { 15323 if (className == null) { 15324 throw new IllegalArgumentException("Unknown package: " + packageName); 15325 } 15326 throw new IllegalArgumentException( 15327 "Unknown component: " + packageName + "/" + className); 15328 } 15329 // Allow root and verify that userId is not being specified by a different user 15330 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 15331 throw new SecurityException( 15332 "Permission Denial: attempt to change component state from pid=" 15333 + Binder.getCallingPid() 15334 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 15335 } 15336 if (className == null) { 15337 // We're dealing with an application/package level state change 15338 if (pkgSetting.getEnabled(userId) == newState) { 15339 // Nothing to do 15340 return; 15341 } 15342 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 15343 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 15344 // Don't care about who enables an app. 15345 callingPackage = null; 15346 } 15347 pkgSetting.setEnabled(newState, userId, callingPackage); 15348 // pkgSetting.pkg.mSetEnabled = newState; 15349 } else { 15350 // We're dealing with a component level state change 15351 // First, verify that this is a valid class name. 15352 PackageParser.Package pkg = pkgSetting.pkg; 15353 if (pkg == null || !pkg.hasComponentClassName(className)) { 15354 if (pkg != null && 15355 pkg.applicationInfo.targetSdkVersion >= 15356 Build.VERSION_CODES.JELLY_BEAN) { 15357 throw new IllegalArgumentException("Component class " + className 15358 + " does not exist in " + packageName); 15359 } else { 15360 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 15361 + className + " does not exist in " + packageName); 15362 } 15363 } 15364 switch (newState) { 15365 case COMPONENT_ENABLED_STATE_ENABLED: 15366 if (!pkgSetting.enableComponentLPw(className, userId)) { 15367 return; 15368 } 15369 break; 15370 case COMPONENT_ENABLED_STATE_DISABLED: 15371 if (!pkgSetting.disableComponentLPw(className, userId)) { 15372 return; 15373 } 15374 break; 15375 case COMPONENT_ENABLED_STATE_DEFAULT: 15376 if (!pkgSetting.restoreComponentLPw(className, userId)) { 15377 return; 15378 } 15379 break; 15380 default: 15381 Slog.e(TAG, "Invalid new component state: " + newState); 15382 return; 15383 } 15384 } 15385 scheduleWritePackageRestrictionsLocked(userId); 15386 components = mPendingBroadcasts.get(userId, packageName); 15387 final boolean newPackage = components == null; 15388 if (newPackage) { 15389 components = new ArrayList<String>(); 15390 } 15391 if (!components.contains(componentName)) { 15392 components.add(componentName); 15393 } 15394 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 15395 sendNow = true; 15396 // Purge entry from pending broadcast list if another one exists already 15397 // since we are sending one right away. 15398 mPendingBroadcasts.remove(userId, packageName); 15399 } else { 15400 if (newPackage) { 15401 mPendingBroadcasts.put(userId, packageName, components); 15402 } 15403 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 15404 // Schedule a message 15405 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 15406 } 15407 } 15408 } 15409 15410 long callingId = Binder.clearCallingIdentity(); 15411 try { 15412 if (sendNow) { 15413 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 15414 sendPackageChangedBroadcast(packageName, 15415 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 15416 } 15417 } finally { 15418 Binder.restoreCallingIdentity(callingId); 15419 } 15420 } 15421 15422 private void sendPackageChangedBroadcast(String packageName, 15423 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 15424 if (DEBUG_INSTALL) 15425 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 15426 + componentNames); 15427 Bundle extras = new Bundle(4); 15428 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 15429 String nameList[] = new String[componentNames.size()]; 15430 componentNames.toArray(nameList); 15431 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 15432 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 15433 extras.putInt(Intent.EXTRA_UID, packageUid); 15434 // If this is not reporting a change of the overall package, then only send it 15435 // to registered receivers. We don't want to launch a swath of apps for every 15436 // little component state change. 15437 final int flags = !componentNames.contains(packageName) 15438 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 15439 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 15440 new int[] {UserHandle.getUserId(packageUid)}); 15441 } 15442 15443 @Override 15444 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 15445 if (!sUserManager.exists(userId)) return; 15446 final int uid = Binder.getCallingUid(); 15447 final int permission = mContext.checkCallingOrSelfPermission( 15448 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 15449 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 15450 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 15451 // writer 15452 synchronized (mPackages) { 15453 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 15454 allowedByPermission, uid, userId)) { 15455 scheduleWritePackageRestrictionsLocked(userId); 15456 } 15457 } 15458 } 15459 15460 @Override 15461 public String getInstallerPackageName(String packageName) { 15462 // reader 15463 synchronized (mPackages) { 15464 return mSettings.getInstallerPackageNameLPr(packageName); 15465 } 15466 } 15467 15468 @Override 15469 public int getApplicationEnabledSetting(String packageName, int userId) { 15470 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 15471 int uid = Binder.getCallingUid(); 15472 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 15473 // reader 15474 synchronized (mPackages) { 15475 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 15476 } 15477 } 15478 15479 @Override 15480 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 15481 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 15482 int uid = Binder.getCallingUid(); 15483 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 15484 // reader 15485 synchronized (mPackages) { 15486 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 15487 } 15488 } 15489 15490 @Override 15491 public void enterSafeMode() { 15492 enforceSystemOrRoot("Only the system can request entering safe mode"); 15493 15494 if (!mSystemReady) { 15495 mSafeMode = true; 15496 } 15497 } 15498 15499 @Override 15500 public void systemReady() { 15501 mSystemReady = true; 15502 15503 // Read the compatibilty setting when the system is ready. 15504 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 15505 mContext.getContentResolver(), 15506 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 15507 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 15508 if (DEBUG_SETTINGS) { 15509 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 15510 } 15511 15512 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 15513 15514 synchronized (mPackages) { 15515 // Verify that all of the preferred activity components actually 15516 // exist. It is possible for applications to be updated and at 15517 // that point remove a previously declared activity component that 15518 // had been set as a preferred activity. We try to clean this up 15519 // the next time we encounter that preferred activity, but it is 15520 // possible for the user flow to never be able to return to that 15521 // situation so here we do a sanity check to make sure we haven't 15522 // left any junk around. 15523 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 15524 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15525 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15526 removed.clear(); 15527 for (PreferredActivity pa : pir.filterSet()) { 15528 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 15529 removed.add(pa); 15530 } 15531 } 15532 if (removed.size() > 0) { 15533 for (int r=0; r<removed.size(); r++) { 15534 PreferredActivity pa = removed.get(r); 15535 Slog.w(TAG, "Removing dangling preferred activity: " 15536 + pa.mPref.mComponent); 15537 pir.removeFilter(pa); 15538 } 15539 mSettings.writePackageRestrictionsLPr( 15540 mSettings.mPreferredActivities.keyAt(i)); 15541 } 15542 } 15543 15544 for (int userId : UserManagerService.getInstance().getUserIds()) { 15545 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 15546 grantPermissionsUserIds = ArrayUtils.appendInt( 15547 grantPermissionsUserIds, userId); 15548 } 15549 } 15550 } 15551 sUserManager.systemReady(); 15552 15553 // If we upgraded grant all default permissions before kicking off. 15554 for (int userId : grantPermissionsUserIds) { 15555 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 15556 } 15557 15558 // Kick off any messages waiting for system ready 15559 if (mPostSystemReadyMessages != null) { 15560 for (Message msg : mPostSystemReadyMessages) { 15561 msg.sendToTarget(); 15562 } 15563 mPostSystemReadyMessages = null; 15564 } 15565 15566 // Watch for external volumes that come and go over time 15567 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15568 storage.registerListener(mStorageListener); 15569 15570 mInstallerService.systemReady(); 15571 mPackageDexOptimizer.systemReady(); 15572 15573 MountServiceInternal mountServiceInternal = LocalServices.getService( 15574 MountServiceInternal.class); 15575 mountServiceInternal.addExternalStoragePolicy( 15576 new MountServiceInternal.ExternalStorageMountPolicy() { 15577 @Override 15578 public int getMountMode(int uid, String packageName) { 15579 if (Process.isIsolated(uid)) { 15580 return Zygote.MOUNT_EXTERNAL_NONE; 15581 } 15582 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 15583 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15584 } 15585 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15586 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15587 } 15588 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15589 return Zygote.MOUNT_EXTERNAL_READ; 15590 } 15591 return Zygote.MOUNT_EXTERNAL_WRITE; 15592 } 15593 15594 @Override 15595 public boolean hasExternalStorage(int uid, String packageName) { 15596 return true; 15597 } 15598 }); 15599 } 15600 15601 @Override 15602 public boolean isSafeMode() { 15603 return mSafeMode; 15604 } 15605 15606 @Override 15607 public boolean hasSystemUidErrors() { 15608 return mHasSystemUidErrors; 15609 } 15610 15611 static String arrayToString(int[] array) { 15612 StringBuffer buf = new StringBuffer(128); 15613 buf.append('['); 15614 if (array != null) { 15615 for (int i=0; i<array.length; i++) { 15616 if (i > 0) buf.append(", "); 15617 buf.append(array[i]); 15618 } 15619 } 15620 buf.append(']'); 15621 return buf.toString(); 15622 } 15623 15624 static class DumpState { 15625 public static final int DUMP_LIBS = 1 << 0; 15626 public static final int DUMP_FEATURES = 1 << 1; 15627 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 15628 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 15629 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 15630 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 15631 public static final int DUMP_PERMISSIONS = 1 << 6; 15632 public static final int DUMP_PACKAGES = 1 << 7; 15633 public static final int DUMP_SHARED_USERS = 1 << 8; 15634 public static final int DUMP_MESSAGES = 1 << 9; 15635 public static final int DUMP_PROVIDERS = 1 << 10; 15636 public static final int DUMP_VERIFIERS = 1 << 11; 15637 public static final int DUMP_PREFERRED = 1 << 12; 15638 public static final int DUMP_PREFERRED_XML = 1 << 13; 15639 public static final int DUMP_KEYSETS = 1 << 14; 15640 public static final int DUMP_VERSION = 1 << 15; 15641 public static final int DUMP_INSTALLS = 1 << 16; 15642 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 15643 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 15644 15645 public static final int OPTION_SHOW_FILTERS = 1 << 0; 15646 15647 private int mTypes; 15648 15649 private int mOptions; 15650 15651 private boolean mTitlePrinted; 15652 15653 private SharedUserSetting mSharedUser; 15654 15655 public boolean isDumping(int type) { 15656 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 15657 return true; 15658 } 15659 15660 return (mTypes & type) != 0; 15661 } 15662 15663 public void setDump(int type) { 15664 mTypes |= type; 15665 } 15666 15667 public boolean isOptionEnabled(int option) { 15668 return (mOptions & option) != 0; 15669 } 15670 15671 public void setOptionEnabled(int option) { 15672 mOptions |= option; 15673 } 15674 15675 public boolean onTitlePrinted() { 15676 final boolean printed = mTitlePrinted; 15677 mTitlePrinted = true; 15678 return printed; 15679 } 15680 15681 public boolean getTitlePrinted() { 15682 return mTitlePrinted; 15683 } 15684 15685 public void setTitlePrinted(boolean enabled) { 15686 mTitlePrinted = enabled; 15687 } 15688 15689 public SharedUserSetting getSharedUser() { 15690 return mSharedUser; 15691 } 15692 15693 public void setSharedUser(SharedUserSetting user) { 15694 mSharedUser = user; 15695 } 15696 } 15697 15698 @Override 15699 public void onShellCommand(FileDescriptor in, FileDescriptor out, 15700 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 15701 (new PackageManagerShellCommand(this)).exec( 15702 this, in, out, err, args, resultReceiver); 15703 } 15704 15705 @Override 15706 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 15707 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 15708 != PackageManager.PERMISSION_GRANTED) { 15709 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 15710 + Binder.getCallingPid() 15711 + ", uid=" + Binder.getCallingUid() 15712 + " without permission " 15713 + android.Manifest.permission.DUMP); 15714 return; 15715 } 15716 15717 DumpState dumpState = new DumpState(); 15718 boolean fullPreferred = false; 15719 boolean checkin = false; 15720 15721 String packageName = null; 15722 ArraySet<String> permissionNames = null; 15723 15724 int opti = 0; 15725 while (opti < args.length) { 15726 String opt = args[opti]; 15727 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 15728 break; 15729 } 15730 opti++; 15731 15732 if ("-a".equals(opt)) { 15733 // Right now we only know how to print all. 15734 } else if ("-h".equals(opt)) { 15735 pw.println("Package manager dump options:"); 15736 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 15737 pw.println(" --checkin: dump for a checkin"); 15738 pw.println(" -f: print details of intent filters"); 15739 pw.println(" -h: print this help"); 15740 pw.println(" cmd may be one of:"); 15741 pw.println(" l[ibraries]: list known shared libraries"); 15742 pw.println(" f[eatures]: list device features"); 15743 pw.println(" k[eysets]: print known keysets"); 15744 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 15745 pw.println(" perm[issions]: dump permissions"); 15746 pw.println(" permission [name ...]: dump declaration and use of given permission"); 15747 pw.println(" pref[erred]: print preferred package settings"); 15748 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 15749 pw.println(" prov[iders]: dump content providers"); 15750 pw.println(" p[ackages]: dump installed packages"); 15751 pw.println(" s[hared-users]: dump shared user IDs"); 15752 pw.println(" m[essages]: print collected runtime messages"); 15753 pw.println(" v[erifiers]: print package verifier info"); 15754 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 15755 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 15756 pw.println(" version: print database version info"); 15757 pw.println(" write: write current settings now"); 15758 pw.println(" installs: details about install sessions"); 15759 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 15760 pw.println(" <package.name>: info about given package"); 15761 return; 15762 } else if ("--checkin".equals(opt)) { 15763 checkin = true; 15764 } else if ("-f".equals(opt)) { 15765 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15766 } else { 15767 pw.println("Unknown argument: " + opt + "; use -h for help"); 15768 } 15769 } 15770 15771 // Is the caller requesting to dump a particular piece of data? 15772 if (opti < args.length) { 15773 String cmd = args[opti]; 15774 opti++; 15775 // Is this a package name? 15776 if ("android".equals(cmd) || cmd.contains(".")) { 15777 packageName = cmd; 15778 // When dumping a single package, we always dump all of its 15779 // filter information since the amount of data will be reasonable. 15780 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15781 } else if ("check-permission".equals(cmd)) { 15782 if (opti >= args.length) { 15783 pw.println("Error: check-permission missing permission argument"); 15784 return; 15785 } 15786 String perm = args[opti]; 15787 opti++; 15788 if (opti >= args.length) { 15789 pw.println("Error: check-permission missing package argument"); 15790 return; 15791 } 15792 String pkg = args[opti]; 15793 opti++; 15794 int user = UserHandle.getUserId(Binder.getCallingUid()); 15795 if (opti < args.length) { 15796 try { 15797 user = Integer.parseInt(args[opti]); 15798 } catch (NumberFormatException e) { 15799 pw.println("Error: check-permission user argument is not a number: " 15800 + args[opti]); 15801 return; 15802 } 15803 } 15804 pw.println(checkPermission(perm, pkg, user)); 15805 return; 15806 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 15807 dumpState.setDump(DumpState.DUMP_LIBS); 15808 } else if ("f".equals(cmd) || "features".equals(cmd)) { 15809 dumpState.setDump(DumpState.DUMP_FEATURES); 15810 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 15811 if (opti >= args.length) { 15812 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 15813 | DumpState.DUMP_SERVICE_RESOLVERS 15814 | DumpState.DUMP_RECEIVER_RESOLVERS 15815 | DumpState.DUMP_CONTENT_RESOLVERS); 15816 } else { 15817 while (opti < args.length) { 15818 String name = args[opti]; 15819 if ("a".equals(name) || "activity".equals(name)) { 15820 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 15821 } else if ("s".equals(name) || "service".equals(name)) { 15822 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 15823 } else if ("r".equals(name) || "receiver".equals(name)) { 15824 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 15825 } else if ("c".equals(name) || "content".equals(name)) { 15826 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 15827 } else { 15828 pw.println("Error: unknown resolver table type: " + name); 15829 return; 15830 } 15831 opti++; 15832 } 15833 } 15834 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 15835 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 15836 } else if ("permission".equals(cmd)) { 15837 if (opti >= args.length) { 15838 pw.println("Error: permission requires permission name"); 15839 return; 15840 } 15841 permissionNames = new ArraySet<>(); 15842 while (opti < args.length) { 15843 permissionNames.add(args[opti]); 15844 opti++; 15845 } 15846 dumpState.setDump(DumpState.DUMP_PERMISSIONS 15847 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 15848 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 15849 dumpState.setDump(DumpState.DUMP_PREFERRED); 15850 } else if ("preferred-xml".equals(cmd)) { 15851 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 15852 if (opti < args.length && "--full".equals(args[opti])) { 15853 fullPreferred = true; 15854 opti++; 15855 } 15856 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 15857 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 15858 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 15859 dumpState.setDump(DumpState.DUMP_PACKAGES); 15860 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 15861 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 15862 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 15863 dumpState.setDump(DumpState.DUMP_PROVIDERS); 15864 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 15865 dumpState.setDump(DumpState.DUMP_MESSAGES); 15866 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 15867 dumpState.setDump(DumpState.DUMP_VERIFIERS); 15868 } else if ("i".equals(cmd) || "ifv".equals(cmd) 15869 || "intent-filter-verifiers".equals(cmd)) { 15870 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 15871 } else if ("version".equals(cmd)) { 15872 dumpState.setDump(DumpState.DUMP_VERSION); 15873 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 15874 dumpState.setDump(DumpState.DUMP_KEYSETS); 15875 } else if ("installs".equals(cmd)) { 15876 dumpState.setDump(DumpState.DUMP_INSTALLS); 15877 } else if ("write".equals(cmd)) { 15878 synchronized (mPackages) { 15879 mSettings.writeLPr(); 15880 pw.println("Settings written."); 15881 return; 15882 } 15883 } 15884 } 15885 15886 if (checkin) { 15887 pw.println("vers,1"); 15888 } 15889 15890 // reader 15891 synchronized (mPackages) { 15892 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 15893 if (!checkin) { 15894 if (dumpState.onTitlePrinted()) 15895 pw.println(); 15896 pw.println("Database versions:"); 15897 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 15898 } 15899 } 15900 15901 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 15902 if (!checkin) { 15903 if (dumpState.onTitlePrinted()) 15904 pw.println(); 15905 pw.println("Verifiers:"); 15906 pw.print(" Required: "); 15907 pw.print(mRequiredVerifierPackage); 15908 pw.print(" (uid="); 15909 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 15910 UserHandle.USER_SYSTEM)); 15911 pw.println(")"); 15912 } else if (mRequiredVerifierPackage != null) { 15913 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 15914 pw.print(","); 15915 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 15916 UserHandle.USER_SYSTEM)); 15917 } 15918 } 15919 15920 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 15921 packageName == null) { 15922 if (mIntentFilterVerifierComponent != null) { 15923 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 15924 if (!checkin) { 15925 if (dumpState.onTitlePrinted()) 15926 pw.println(); 15927 pw.println("Intent Filter Verifier:"); 15928 pw.print(" Using: "); 15929 pw.print(verifierPackageName); 15930 pw.print(" (uid="); 15931 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 15932 UserHandle.USER_SYSTEM)); 15933 pw.println(")"); 15934 } else if (verifierPackageName != null) { 15935 pw.print("ifv,"); pw.print(verifierPackageName); 15936 pw.print(","); 15937 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 15938 UserHandle.USER_SYSTEM)); 15939 } 15940 } else { 15941 pw.println(); 15942 pw.println("No Intent Filter Verifier available!"); 15943 } 15944 } 15945 15946 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 15947 boolean printedHeader = false; 15948 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 15949 while (it.hasNext()) { 15950 String name = it.next(); 15951 SharedLibraryEntry ent = mSharedLibraries.get(name); 15952 if (!checkin) { 15953 if (!printedHeader) { 15954 if (dumpState.onTitlePrinted()) 15955 pw.println(); 15956 pw.println("Libraries:"); 15957 printedHeader = true; 15958 } 15959 pw.print(" "); 15960 } else { 15961 pw.print("lib,"); 15962 } 15963 pw.print(name); 15964 if (!checkin) { 15965 pw.print(" -> "); 15966 } 15967 if (ent.path != null) { 15968 if (!checkin) { 15969 pw.print("(jar) "); 15970 pw.print(ent.path); 15971 } else { 15972 pw.print(",jar,"); 15973 pw.print(ent.path); 15974 } 15975 } else { 15976 if (!checkin) { 15977 pw.print("(apk) "); 15978 pw.print(ent.apk); 15979 } else { 15980 pw.print(",apk,"); 15981 pw.print(ent.apk); 15982 } 15983 } 15984 pw.println(); 15985 } 15986 } 15987 15988 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 15989 if (dumpState.onTitlePrinted()) 15990 pw.println(); 15991 if (!checkin) { 15992 pw.println("Features:"); 15993 } 15994 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 15995 while (it.hasNext()) { 15996 String name = it.next(); 15997 if (!checkin) { 15998 pw.print(" "); 15999 } else { 16000 pw.print("feat,"); 16001 } 16002 pw.println(name); 16003 } 16004 } 16005 16006 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 16007 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 16008 : "Activity Resolver Table:", " ", packageName, 16009 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16010 dumpState.setTitlePrinted(true); 16011 } 16012 } 16013 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 16014 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 16015 : "Receiver Resolver Table:", " ", packageName, 16016 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16017 dumpState.setTitlePrinted(true); 16018 } 16019 } 16020 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 16021 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 16022 : "Service Resolver Table:", " ", packageName, 16023 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16024 dumpState.setTitlePrinted(true); 16025 } 16026 } 16027 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 16028 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 16029 : "Provider Resolver Table:", " ", packageName, 16030 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16031 dumpState.setTitlePrinted(true); 16032 } 16033 } 16034 16035 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 16036 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16037 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16038 int user = mSettings.mPreferredActivities.keyAt(i); 16039 if (pir.dump(pw, 16040 dumpState.getTitlePrinted() 16041 ? "\nPreferred Activities User " + user + ":" 16042 : "Preferred Activities User " + user + ":", " ", 16043 packageName, true, false)) { 16044 dumpState.setTitlePrinted(true); 16045 } 16046 } 16047 } 16048 16049 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 16050 pw.flush(); 16051 FileOutputStream fout = new FileOutputStream(fd); 16052 BufferedOutputStream str = new BufferedOutputStream(fout); 16053 XmlSerializer serializer = new FastXmlSerializer(); 16054 try { 16055 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 16056 serializer.startDocument(null, true); 16057 serializer.setFeature( 16058 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 16059 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 16060 serializer.endDocument(); 16061 serializer.flush(); 16062 } catch (IllegalArgumentException e) { 16063 pw.println("Failed writing: " + e); 16064 } catch (IllegalStateException e) { 16065 pw.println("Failed writing: " + e); 16066 } catch (IOException e) { 16067 pw.println("Failed writing: " + e); 16068 } 16069 } 16070 16071 if (!checkin 16072 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 16073 && packageName == null) { 16074 pw.println(); 16075 int count = mSettings.mPackages.size(); 16076 if (count == 0) { 16077 pw.println("No applications!"); 16078 pw.println(); 16079 } else { 16080 final String prefix = " "; 16081 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 16082 if (allPackageSettings.size() == 0) { 16083 pw.println("No domain preferred apps!"); 16084 pw.println(); 16085 } else { 16086 pw.println("App verification status:"); 16087 pw.println(); 16088 count = 0; 16089 for (PackageSetting ps : allPackageSettings) { 16090 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 16091 if (ivi == null || ivi.getPackageName() == null) continue; 16092 pw.println(prefix + "Package: " + ivi.getPackageName()); 16093 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 16094 pw.println(prefix + "Status: " + ivi.getStatusString()); 16095 pw.println(); 16096 count++; 16097 } 16098 if (count == 0) { 16099 pw.println(prefix + "No app verification established."); 16100 pw.println(); 16101 } 16102 for (int userId : sUserManager.getUserIds()) { 16103 pw.println("App linkages for user " + userId + ":"); 16104 pw.println(); 16105 count = 0; 16106 for (PackageSetting ps : allPackageSettings) { 16107 final long status = ps.getDomainVerificationStatusForUser(userId); 16108 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 16109 continue; 16110 } 16111 pw.println(prefix + "Package: " + ps.name); 16112 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 16113 String statusStr = IntentFilterVerificationInfo. 16114 getStatusStringFromValue(status); 16115 pw.println(prefix + "Status: " + statusStr); 16116 pw.println(); 16117 count++; 16118 } 16119 if (count == 0) { 16120 pw.println(prefix + "No configured app linkages."); 16121 pw.println(); 16122 } 16123 } 16124 } 16125 } 16126 } 16127 16128 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 16129 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 16130 if (packageName == null && permissionNames == null) { 16131 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 16132 if (iperm == 0) { 16133 if (dumpState.onTitlePrinted()) 16134 pw.println(); 16135 pw.println("AppOp Permissions:"); 16136 } 16137 pw.print(" AppOp Permission "); 16138 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 16139 pw.println(":"); 16140 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 16141 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 16142 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 16143 } 16144 } 16145 } 16146 } 16147 16148 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 16149 boolean printedSomething = false; 16150 for (PackageParser.Provider p : mProviders.mProviders.values()) { 16151 if (packageName != null && !packageName.equals(p.info.packageName)) { 16152 continue; 16153 } 16154 if (!printedSomething) { 16155 if (dumpState.onTitlePrinted()) 16156 pw.println(); 16157 pw.println("Registered ContentProviders:"); 16158 printedSomething = true; 16159 } 16160 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 16161 pw.print(" "); pw.println(p.toString()); 16162 } 16163 printedSomething = false; 16164 for (Map.Entry<String, PackageParser.Provider> entry : 16165 mProvidersByAuthority.entrySet()) { 16166 PackageParser.Provider p = entry.getValue(); 16167 if (packageName != null && !packageName.equals(p.info.packageName)) { 16168 continue; 16169 } 16170 if (!printedSomething) { 16171 if (dumpState.onTitlePrinted()) 16172 pw.println(); 16173 pw.println("ContentProvider Authorities:"); 16174 printedSomething = true; 16175 } 16176 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 16177 pw.print(" "); pw.println(p.toString()); 16178 if (p.info != null && p.info.applicationInfo != null) { 16179 final String appInfo = p.info.applicationInfo.toString(); 16180 pw.print(" applicationInfo="); pw.println(appInfo); 16181 } 16182 } 16183 } 16184 16185 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 16186 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 16187 } 16188 16189 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 16190 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 16191 } 16192 16193 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 16194 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 16195 } 16196 16197 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 16198 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 16199 } 16200 16201 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 16202 // XXX should handle packageName != null by dumping only install data that 16203 // the given package is involved with. 16204 if (dumpState.onTitlePrinted()) pw.println(); 16205 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 16206 } 16207 16208 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 16209 if (dumpState.onTitlePrinted()) pw.println(); 16210 mSettings.dumpReadMessagesLPr(pw, dumpState); 16211 16212 pw.println(); 16213 pw.println("Package warning messages:"); 16214 BufferedReader in = null; 16215 String line = null; 16216 try { 16217 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 16218 while ((line = in.readLine()) != null) { 16219 if (line.contains("ignored: updated version")) continue; 16220 pw.println(line); 16221 } 16222 } catch (IOException ignored) { 16223 } finally { 16224 IoUtils.closeQuietly(in); 16225 } 16226 } 16227 16228 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 16229 BufferedReader in = null; 16230 String line = null; 16231 try { 16232 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 16233 while ((line = in.readLine()) != null) { 16234 if (line.contains("ignored: updated version")) continue; 16235 pw.print("msg,"); 16236 pw.println(line); 16237 } 16238 } catch (IOException ignored) { 16239 } finally { 16240 IoUtils.closeQuietly(in); 16241 } 16242 } 16243 } 16244 } 16245 16246 private String dumpDomainString(String packageName) { 16247 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 16248 List<IntentFilter> filters = getAllIntentFilters(packageName); 16249 16250 ArraySet<String> result = new ArraySet<>(); 16251 if (iviList.size() > 0) { 16252 for (IntentFilterVerificationInfo ivi : iviList) { 16253 for (String host : ivi.getDomains()) { 16254 result.add(host); 16255 } 16256 } 16257 } 16258 if (filters != null && filters.size() > 0) { 16259 for (IntentFilter filter : filters) { 16260 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 16261 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 16262 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 16263 result.addAll(filter.getHostsList()); 16264 } 16265 } 16266 } 16267 16268 StringBuilder sb = new StringBuilder(result.size() * 16); 16269 for (String domain : result) { 16270 if (sb.length() > 0) sb.append(" "); 16271 sb.append(domain); 16272 } 16273 return sb.toString(); 16274 } 16275 16276 // ------- apps on sdcard specific code ------- 16277 static final boolean DEBUG_SD_INSTALL = false; 16278 16279 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 16280 16281 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 16282 16283 private boolean mMediaMounted = false; 16284 16285 static String getEncryptKey() { 16286 try { 16287 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 16288 SD_ENCRYPTION_KEYSTORE_NAME); 16289 if (sdEncKey == null) { 16290 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 16291 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 16292 if (sdEncKey == null) { 16293 Slog.e(TAG, "Failed to create encryption keys"); 16294 return null; 16295 } 16296 } 16297 return sdEncKey; 16298 } catch (NoSuchAlgorithmException nsae) { 16299 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 16300 return null; 16301 } catch (IOException ioe) { 16302 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 16303 return null; 16304 } 16305 } 16306 16307 /* 16308 * Update media status on PackageManager. 16309 */ 16310 @Override 16311 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 16312 int callingUid = Binder.getCallingUid(); 16313 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 16314 throw new SecurityException("Media status can only be updated by the system"); 16315 } 16316 // reader; this apparently protects mMediaMounted, but should probably 16317 // be a different lock in that case. 16318 synchronized (mPackages) { 16319 Log.i(TAG, "Updating external media status from " 16320 + (mMediaMounted ? "mounted" : "unmounted") + " to " 16321 + (mediaStatus ? "mounted" : "unmounted")); 16322 if (DEBUG_SD_INSTALL) 16323 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 16324 + ", mMediaMounted=" + mMediaMounted); 16325 if (mediaStatus == mMediaMounted) { 16326 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 16327 : 0, -1); 16328 mHandler.sendMessage(msg); 16329 return; 16330 } 16331 mMediaMounted = mediaStatus; 16332 } 16333 // Queue up an async operation since the package installation may take a 16334 // little while. 16335 mHandler.post(new Runnable() { 16336 public void run() { 16337 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 16338 } 16339 }); 16340 } 16341 16342 /** 16343 * Called by MountService when the initial ASECs to scan are available. 16344 * Should block until all the ASEC containers are finished being scanned. 16345 */ 16346 public void scanAvailableAsecs() { 16347 updateExternalMediaStatusInner(true, false, false); 16348 } 16349 16350 /* 16351 * Collect information of applications on external media, map them against 16352 * existing containers and update information based on current mount status. 16353 * Please note that we always have to report status if reportStatus has been 16354 * set to true especially when unloading packages. 16355 */ 16356 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 16357 boolean externalStorage) { 16358 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 16359 int[] uidArr = EmptyArray.INT; 16360 16361 final String[] list = PackageHelper.getSecureContainerList(); 16362 if (ArrayUtils.isEmpty(list)) { 16363 Log.i(TAG, "No secure containers found"); 16364 } else { 16365 // Process list of secure containers and categorize them 16366 // as active or stale based on their package internal state. 16367 16368 // reader 16369 synchronized (mPackages) { 16370 for (String cid : list) { 16371 // Leave stages untouched for now; installer service owns them 16372 if (PackageInstallerService.isStageName(cid)) continue; 16373 16374 if (DEBUG_SD_INSTALL) 16375 Log.i(TAG, "Processing container " + cid); 16376 String pkgName = getAsecPackageName(cid); 16377 if (pkgName == null) { 16378 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 16379 continue; 16380 } 16381 if (DEBUG_SD_INSTALL) 16382 Log.i(TAG, "Looking for pkg : " + pkgName); 16383 16384 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16385 if (ps == null) { 16386 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 16387 continue; 16388 } 16389 16390 /* 16391 * Skip packages that are not external if we're unmounting 16392 * external storage. 16393 */ 16394 if (externalStorage && !isMounted && !isExternal(ps)) { 16395 continue; 16396 } 16397 16398 final AsecInstallArgs args = new AsecInstallArgs(cid, 16399 getAppDexInstructionSets(ps), ps.isForwardLocked()); 16400 // The package status is changed only if the code path 16401 // matches between settings and the container id. 16402 if (ps.codePathString != null 16403 && ps.codePathString.startsWith(args.getCodePath())) { 16404 if (DEBUG_SD_INSTALL) { 16405 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 16406 + " at code path: " + ps.codePathString); 16407 } 16408 16409 // We do have a valid package installed on sdcard 16410 processCids.put(args, ps.codePathString); 16411 final int uid = ps.appId; 16412 if (uid != -1) { 16413 uidArr = ArrayUtils.appendInt(uidArr, uid); 16414 } 16415 } else { 16416 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 16417 + ps.codePathString); 16418 } 16419 } 16420 } 16421 16422 Arrays.sort(uidArr); 16423 } 16424 16425 // Process packages with valid entries. 16426 if (isMounted) { 16427 if (DEBUG_SD_INSTALL) 16428 Log.i(TAG, "Loading packages"); 16429 loadMediaPackages(processCids, uidArr, externalStorage); 16430 startCleaningPackages(); 16431 mInstallerService.onSecureContainersAvailable(); 16432 } else { 16433 if (DEBUG_SD_INSTALL) 16434 Log.i(TAG, "Unloading packages"); 16435 unloadMediaPackages(processCids, uidArr, reportStatus); 16436 } 16437 } 16438 16439 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16440 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 16441 final int size = infos.size(); 16442 final String[] packageNames = new String[size]; 16443 final int[] packageUids = new int[size]; 16444 for (int i = 0; i < size; i++) { 16445 final ApplicationInfo info = infos.get(i); 16446 packageNames[i] = info.packageName; 16447 packageUids[i] = info.uid; 16448 } 16449 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 16450 finishedReceiver); 16451 } 16452 16453 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16454 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 16455 sendResourcesChangedBroadcast(mediaStatus, replacing, 16456 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 16457 } 16458 16459 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16460 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 16461 int size = pkgList.length; 16462 if (size > 0) { 16463 // Send broadcasts here 16464 Bundle extras = new Bundle(); 16465 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 16466 if (uidArr != null) { 16467 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 16468 } 16469 if (replacing) { 16470 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 16471 } 16472 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 16473 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 16474 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 16475 } 16476 } 16477 16478 /* 16479 * Look at potentially valid container ids from processCids If package 16480 * information doesn't match the one on record or package scanning fails, 16481 * the cid is added to list of removeCids. We currently don't delete stale 16482 * containers. 16483 */ 16484 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 16485 boolean externalStorage) { 16486 ArrayList<String> pkgList = new ArrayList<String>(); 16487 Set<AsecInstallArgs> keys = processCids.keySet(); 16488 16489 for (AsecInstallArgs args : keys) { 16490 String codePath = processCids.get(args); 16491 if (DEBUG_SD_INSTALL) 16492 Log.i(TAG, "Loading container : " + args.cid); 16493 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 16494 try { 16495 // Make sure there are no container errors first. 16496 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 16497 Slog.e(TAG, "Failed to mount cid : " + args.cid 16498 + " when installing from sdcard"); 16499 continue; 16500 } 16501 // Check code path here. 16502 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 16503 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 16504 + " does not match one in settings " + codePath); 16505 continue; 16506 } 16507 // Parse package 16508 int parseFlags = mDefParseFlags; 16509 if (args.isExternalAsec()) { 16510 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 16511 } 16512 if (args.isFwdLocked()) { 16513 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 16514 } 16515 16516 synchronized (mInstallLock) { 16517 PackageParser.Package pkg = null; 16518 try { 16519 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 16520 } catch (PackageManagerException e) { 16521 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 16522 } 16523 // Scan the package 16524 if (pkg != null) { 16525 /* 16526 * TODO why is the lock being held? doPostInstall is 16527 * called in other places without the lock. This needs 16528 * to be straightened out. 16529 */ 16530 // writer 16531 synchronized (mPackages) { 16532 retCode = PackageManager.INSTALL_SUCCEEDED; 16533 pkgList.add(pkg.packageName); 16534 // Post process args 16535 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 16536 pkg.applicationInfo.uid); 16537 } 16538 } else { 16539 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 16540 } 16541 } 16542 16543 } finally { 16544 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 16545 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 16546 } 16547 } 16548 } 16549 // writer 16550 synchronized (mPackages) { 16551 // If the platform SDK has changed since the last time we booted, 16552 // we need to re-grant app permission to catch any new ones that 16553 // appear. This is really a hack, and means that apps can in some 16554 // cases get permissions that the user didn't initially explicitly 16555 // allow... it would be nice to have some better way to handle 16556 // this situation. 16557 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 16558 : mSettings.getInternalVersion(); 16559 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 16560 : StorageManager.UUID_PRIVATE_INTERNAL; 16561 16562 int updateFlags = UPDATE_PERMISSIONS_ALL; 16563 if (ver.sdkVersion != mSdkVersion) { 16564 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16565 + mSdkVersion + "; regranting permissions for external"); 16566 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16567 } 16568 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 16569 16570 // Yay, everything is now upgraded 16571 ver.forceCurrent(); 16572 16573 // can downgrade to reader 16574 // Persist settings 16575 mSettings.writeLPr(); 16576 } 16577 // Send a broadcast to let everyone know we are done processing 16578 if (pkgList.size() > 0) { 16579 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 16580 } 16581 } 16582 16583 /* 16584 * Utility method to unload a list of specified containers 16585 */ 16586 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 16587 // Just unmount all valid containers. 16588 for (AsecInstallArgs arg : cidArgs) { 16589 synchronized (mInstallLock) { 16590 arg.doPostDeleteLI(false); 16591 } 16592 } 16593 } 16594 16595 /* 16596 * Unload packages mounted on external media. This involves deleting package 16597 * data from internal structures, sending broadcasts about diabled packages, 16598 * gc'ing to free up references, unmounting all secure containers 16599 * corresponding to packages on external media, and posting a 16600 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 16601 * that we always have to post this message if status has been requested no 16602 * matter what. 16603 */ 16604 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 16605 final boolean reportStatus) { 16606 if (DEBUG_SD_INSTALL) 16607 Log.i(TAG, "unloading media packages"); 16608 ArrayList<String> pkgList = new ArrayList<String>(); 16609 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 16610 final Set<AsecInstallArgs> keys = processCids.keySet(); 16611 for (AsecInstallArgs args : keys) { 16612 String pkgName = args.getPackageName(); 16613 if (DEBUG_SD_INSTALL) 16614 Log.i(TAG, "Trying to unload pkg : " + pkgName); 16615 // Delete package internally 16616 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16617 synchronized (mInstallLock) { 16618 boolean res = deletePackageLI(pkgName, null, false, null, null, 16619 PackageManager.DELETE_KEEP_DATA, outInfo, false); 16620 if (res) { 16621 pkgList.add(pkgName); 16622 } else { 16623 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 16624 failedList.add(args); 16625 } 16626 } 16627 } 16628 16629 // reader 16630 synchronized (mPackages) { 16631 // We didn't update the settings after removing each package; 16632 // write them now for all packages. 16633 mSettings.writeLPr(); 16634 } 16635 16636 // We have to absolutely send UPDATED_MEDIA_STATUS only 16637 // after confirming that all the receivers processed the ordered 16638 // broadcast when packages get disabled, force a gc to clean things up. 16639 // and unload all the containers. 16640 if (pkgList.size() > 0) { 16641 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 16642 new IIntentReceiver.Stub() { 16643 public void performReceive(Intent intent, int resultCode, String data, 16644 Bundle extras, boolean ordered, boolean sticky, 16645 int sendingUser) throws RemoteException { 16646 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 16647 reportStatus ? 1 : 0, 1, keys); 16648 mHandler.sendMessage(msg); 16649 } 16650 }); 16651 } else { 16652 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 16653 keys); 16654 mHandler.sendMessage(msg); 16655 } 16656 } 16657 16658 private void loadPrivatePackages(final VolumeInfo vol) { 16659 mHandler.post(new Runnable() { 16660 @Override 16661 public void run() { 16662 loadPrivatePackagesInner(vol); 16663 } 16664 }); 16665 } 16666 16667 private void loadPrivatePackagesInner(VolumeInfo vol) { 16668 final String volumeUuid = vol.fsUuid; 16669 if (TextUtils.isEmpty(volumeUuid)) { 16670 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 16671 return; 16672 } 16673 16674 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 16675 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 16676 16677 final VersionInfo ver; 16678 final List<PackageSetting> packages; 16679 synchronized (mPackages) { 16680 ver = mSettings.findOrCreateVersion(volumeUuid); 16681 packages = mSettings.getVolumePackagesLPr(volumeUuid); 16682 } 16683 16684 // TODO: introduce a new concept similar to "frozen" to prevent these 16685 // apps from being launched until after data has been fully reconciled 16686 for (PackageSetting ps : packages) { 16687 synchronized (mInstallLock) { 16688 final PackageParser.Package pkg; 16689 try { 16690 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 16691 loaded.add(pkg.applicationInfo); 16692 16693 } catch (PackageManagerException e) { 16694 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 16695 } 16696 16697 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 16698 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 16699 } 16700 } 16701 } 16702 16703 // Reconcile app data for all started/unlocked users 16704 final UserManager um = mContext.getSystemService(UserManager.class); 16705 for (UserInfo user : um.getUsers()) { 16706 if (um.isUserUnlocked(user.id)) { 16707 reconcileAppsData(volumeUuid, user.id, 16708 Installer.FLAG_DE_STORAGE | Installer.FLAG_CE_STORAGE); 16709 } else if (um.isUserRunning(user.id)) { 16710 reconcileAppsData(volumeUuid, user.id, Installer.FLAG_DE_STORAGE); 16711 } else { 16712 continue; 16713 } 16714 } 16715 16716 synchronized (mPackages) { 16717 int updateFlags = UPDATE_PERMISSIONS_ALL; 16718 if (ver.sdkVersion != mSdkVersion) { 16719 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16720 + mSdkVersion + "; regranting permissions for " + volumeUuid); 16721 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16722 } 16723 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 16724 16725 // Yay, everything is now upgraded 16726 ver.forceCurrent(); 16727 16728 mSettings.writeLPr(); 16729 } 16730 16731 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 16732 sendResourcesChangedBroadcast(true, false, loaded, null); 16733 } 16734 16735 private void unloadPrivatePackages(final VolumeInfo vol) { 16736 mHandler.post(new Runnable() { 16737 @Override 16738 public void run() { 16739 unloadPrivatePackagesInner(vol); 16740 } 16741 }); 16742 } 16743 16744 private void unloadPrivatePackagesInner(VolumeInfo vol) { 16745 final String volumeUuid = vol.fsUuid; 16746 if (TextUtils.isEmpty(volumeUuid)) { 16747 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 16748 return; 16749 } 16750 16751 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 16752 synchronized (mInstallLock) { 16753 synchronized (mPackages) { 16754 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 16755 for (PackageSetting ps : packages) { 16756 if (ps.pkg == null) continue; 16757 16758 final ApplicationInfo info = ps.pkg.applicationInfo; 16759 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16760 if (deletePackageLI(ps.name, null, false, null, null, 16761 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 16762 unloaded.add(info); 16763 } else { 16764 Slog.w(TAG, "Failed to unload " + ps.codePath); 16765 } 16766 } 16767 16768 mSettings.writeLPr(); 16769 } 16770 } 16771 16772 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 16773 sendResourcesChangedBroadcast(false, false, unloaded, null); 16774 } 16775 16776 /** 16777 * Examine all users present on given mounted volume, and destroy data 16778 * belonging to users that are no longer valid, or whose user ID has been 16779 * recycled. 16780 */ 16781 private void reconcileUsers(String volumeUuid) { 16782 final File[] files = FileUtils 16783 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 16784 for (File file : files) { 16785 if (!file.isDirectory()) continue; 16786 16787 final int userId; 16788 final UserInfo info; 16789 try { 16790 userId = Integer.parseInt(file.getName()); 16791 info = sUserManager.getUserInfo(userId); 16792 } catch (NumberFormatException e) { 16793 Slog.w(TAG, "Invalid user directory " + file); 16794 continue; 16795 } 16796 16797 boolean destroyUser = false; 16798 if (info == null) { 16799 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16800 + " because no matching user was found"); 16801 destroyUser = true; 16802 } else { 16803 try { 16804 UserManagerService.enforceSerialNumber(file, info.serialNumber); 16805 } catch (IOException e) { 16806 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16807 + " because we failed to enforce serial number: " + e); 16808 destroyUser = true; 16809 } 16810 } 16811 16812 if (destroyUser) { 16813 synchronized (mInstallLock) { 16814 try { 16815 mInstaller.removeUserDataDirs(volumeUuid, userId); 16816 } catch (InstallerException e) { 16817 Slog.w(TAG, "Failed to clean up user dirs", e); 16818 } 16819 } 16820 } 16821 } 16822 16823 final StorageManager sm = mContext.getSystemService(StorageManager.class); 16824 final UserManager um = mContext.getSystemService(UserManager.class); 16825 for (UserInfo user : um.getUsers()) { 16826 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 16827 if (userDir.exists()) continue; 16828 16829 try { 16830 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, user.isEphemeral()); 16831 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 16832 } catch (IOException e) { 16833 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 16834 } 16835 } 16836 } 16837 16838 private void assertPackageKnown(String volumeUuid, String packageName) 16839 throws PackageManagerException { 16840 synchronized (mPackages) { 16841 final PackageSetting ps = mSettings.mPackages.get(packageName); 16842 if (ps == null) { 16843 throw new PackageManagerException("Package " + packageName + " is unknown"); 16844 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 16845 throw new PackageManagerException( 16846 "Package " + packageName + " found on unknown volume " + volumeUuid 16847 + "; expected volume " + ps.volumeUuid); 16848 } 16849 } 16850 } 16851 16852 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 16853 throws PackageManagerException { 16854 synchronized (mPackages) { 16855 final PackageSetting ps = mSettings.mPackages.get(packageName); 16856 if (ps == null) { 16857 throw new PackageManagerException("Package " + packageName + " is unknown"); 16858 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 16859 throw new PackageManagerException( 16860 "Package " + packageName + " found on unknown volume " + volumeUuid 16861 + "; expected volume " + ps.volumeUuid); 16862 } else if (!ps.getInstalled(userId)) { 16863 throw new PackageManagerException( 16864 "Package " + packageName + " not installed for user " + userId); 16865 } 16866 } 16867 } 16868 16869 /** 16870 * Examine all apps present on given mounted volume, and destroy apps that 16871 * aren't expected, either due to uninstallation or reinstallation on 16872 * another volume. 16873 */ 16874 private void reconcileApps(String volumeUuid) { 16875 final File[] files = FileUtils 16876 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 16877 for (File file : files) { 16878 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 16879 && !PackageInstallerService.isStageName(file.getName()); 16880 if (!isPackage) { 16881 // Ignore entries which are not packages 16882 continue; 16883 } 16884 16885 try { 16886 final PackageLite pkg = PackageParser.parsePackageLite(file, 16887 PackageParser.PARSE_MUST_BE_APK); 16888 assertPackageKnown(volumeUuid, pkg.packageName); 16889 16890 } catch (PackageParserException | PackageManagerException e) { 16891 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 16892 synchronized (mInstallLock) { 16893 removeCodePathLI(file); 16894 } 16895 } 16896 } 16897 } 16898 16899 /** 16900 * Reconcile all app data for the given user. 16901 * <p> 16902 * Verifies that directories exist and that ownership and labeling is 16903 * correct for all installed apps on all mounted volumes. 16904 */ 16905 void reconcileAppsData(int userId, @StorageFlags int flags) { 16906 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16907 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16908 final String volumeUuid = vol.getFsUuid(); 16909 reconcileAppsData(volumeUuid, userId, flags); 16910 } 16911 } 16912 16913 /** 16914 * Reconcile all app data on given mounted volume. 16915 * <p> 16916 * Destroys app data that isn't expected, either due to uninstallation or 16917 * reinstallation on another volume. 16918 * <p> 16919 * Verifies that directories exist and that ownership and labeling is 16920 * correct for all installed apps. 16921 */ 16922 private void reconcileAppsData(String volumeUuid, int userId, @StorageFlags int flags) { 16923 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 16924 + Integer.toHexString(flags)); 16925 16926 final File ceDir = Environment.getDataUserCredentialEncryptedDirectory(volumeUuid, userId); 16927 final File deDir = Environment.getDataUserDeviceEncryptedDirectory(volumeUuid, userId); 16928 16929 boolean restoreconNeeded = false; 16930 16931 // First look for stale data that doesn't belong, and check if things 16932 // have changed since we did our last restorecon 16933 if ((flags & Installer.FLAG_CE_STORAGE) != 0) { 16934 if (!isUserKeyUnlocked(userId)) { 16935 throw new RuntimeException( 16936 "Yikes, someone asked us to reconcile CE storage while " + userId 16937 + " was still locked; this would have caused massive data loss!"); 16938 } 16939 16940 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 16941 16942 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 16943 for (File file : files) { 16944 final String packageName = file.getName(); 16945 try { 16946 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 16947 } catch (PackageManagerException e) { 16948 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 16949 synchronized (mInstallLock) { 16950 destroyAppDataLI(volumeUuid, packageName, userId, 16951 Installer.FLAG_CE_STORAGE); 16952 } 16953 } 16954 } 16955 } 16956 if ((flags & Installer.FLAG_DE_STORAGE) != 0) { 16957 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 16958 16959 final File[] files = FileUtils.listFilesOrEmpty(deDir); 16960 for (File file : files) { 16961 final String packageName = file.getName(); 16962 try { 16963 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 16964 } catch (PackageManagerException e) { 16965 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 16966 synchronized (mInstallLock) { 16967 destroyAppDataLI(volumeUuid, packageName, userId, 16968 Installer.FLAG_DE_STORAGE); 16969 } 16970 } 16971 } 16972 } 16973 16974 // Ensure that data directories are ready to roll for all packages 16975 // installed for this volume and user 16976 final List<PackageSetting> packages; 16977 synchronized (mPackages) { 16978 packages = mSettings.getVolumePackagesLPr(volumeUuid); 16979 } 16980 int preparedCount = 0; 16981 for (PackageSetting ps : packages) { 16982 final String packageName = ps.name; 16983 if (ps.pkg == null) { 16984 Slog.w(TAG, "Odd, missing scanned package " + packageName); 16985 // TODO: might be due to legacy ASEC apps; we should circle back 16986 // and reconcile again once they're scanned 16987 continue; 16988 } 16989 16990 if (ps.getInstalled(userId)) { 16991 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 16992 preparedCount++; 16993 } 16994 } 16995 16996 if (restoreconNeeded) { 16997 if ((flags & Installer.FLAG_CE_STORAGE) != 0) { 16998 SELinuxMMAC.setRestoreconDone(ceDir); 16999 } 17000 if ((flags & Installer.FLAG_DE_STORAGE) != 0) { 17001 SELinuxMMAC.setRestoreconDone(deDir); 17002 } 17003 } 17004 17005 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 17006 + " packages; restoreconNeeded was " + restoreconNeeded); 17007 } 17008 17009 /** 17010 * Prepare app data for the given app just after it was installed or 17011 * upgraded. This method carefully only touches users that it's installed 17012 * for, and it forces a restorecon to handle any seinfo changes. 17013 * <p> 17014 * Verifies that directories exist and that ownership and labeling is 17015 * correct for all installed apps. If there is an ownership mismatch, it 17016 * will try recovering system apps by wiping data; third-party app data is 17017 * left intact. 17018 */ 17019 private void prepareAppDataAfterInstall(PackageParser.Package pkg) { 17020 final PackageSetting ps; 17021 synchronized (mPackages) { 17022 ps = mSettings.mPackages.get(pkg.packageName); 17023 } 17024 17025 final UserManager um = mContext.getSystemService(UserManager.class); 17026 for (UserInfo user : um.getUsers()) { 17027 final int flags; 17028 if (um.isUserUnlocked(user.id)) { 17029 flags = Installer.FLAG_DE_STORAGE | Installer.FLAG_CE_STORAGE; 17030 } else if (um.isUserRunning(user.id)) { 17031 flags = Installer.FLAG_DE_STORAGE; 17032 } else { 17033 continue; 17034 } 17035 17036 if (ps.getInstalled(user.id)) { 17037 // Whenever an app changes, force a restorecon of its data 17038 // TODO: when user data is locked, mark that we're still dirty 17039 prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true); 17040 } 17041 } 17042 } 17043 17044 /** 17045 * Prepare app data for the given app. 17046 * <p> 17047 * Verifies that directories exist and that ownership and labeling is 17048 * correct for all installed apps. If there is an ownership mismatch, this 17049 * will try recovering system apps by wiping data; third-party app data is 17050 * left intact. 17051 */ 17052 private void prepareAppData(String volumeUuid, int userId, @StorageFlags int flags, 17053 PackageParser.Package pkg, boolean restoreconNeeded) { 17054 if (DEBUG_APP_DATA) { 17055 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 17056 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 17057 } 17058 17059 final String packageName = pkg.packageName; 17060 final ApplicationInfo app = pkg.applicationInfo; 17061 final int appId = UserHandle.getAppId(app.uid); 17062 17063 Preconditions.checkNotNull(app.seinfo); 17064 17065 synchronized (mInstallLock) { 17066 try { 17067 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 17068 appId, app.seinfo, app.targetSdkVersion); 17069 } catch (InstallerException e) { 17070 if (app.isSystemApp()) { 17071 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 17072 + ", but trying to recover: " + e); 17073 destroyAppDataLI(volumeUuid, packageName, userId, flags); 17074 try { 17075 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 17076 appId, app.seinfo, app.targetSdkVersion); 17077 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 17078 } catch (InstallerException e2) { 17079 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 17080 } 17081 } else { 17082 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 17083 } 17084 } 17085 17086 if (restoreconNeeded) { 17087 restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo); 17088 } 17089 17090 if ((flags & Installer.FLAG_CE_STORAGE) != 0) { 17091 // Create a native library symlink only if we have native libraries 17092 // and if the native libraries are 32 bit libraries. We do not provide 17093 // this symlink for 64 bit libraries. 17094 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 17095 final String nativeLibPath = app.nativeLibraryDir; 17096 try { 17097 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 17098 nativeLibPath, userId); 17099 } catch (InstallerException e) { 17100 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 17101 } 17102 } 17103 } 17104 } 17105 } 17106 17107 private void unfreezePackage(String packageName) { 17108 synchronized (mPackages) { 17109 final PackageSetting ps = mSettings.mPackages.get(packageName); 17110 if (ps != null) { 17111 ps.frozen = false; 17112 } 17113 } 17114 } 17115 17116 @Override 17117 public int movePackage(final String packageName, final String volumeUuid) { 17118 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 17119 17120 final int moveId = mNextMoveId.getAndIncrement(); 17121 mHandler.post(new Runnable() { 17122 @Override 17123 public void run() { 17124 try { 17125 movePackageInternal(packageName, volumeUuid, moveId); 17126 } catch (PackageManagerException e) { 17127 Slog.w(TAG, "Failed to move " + packageName, e); 17128 mMoveCallbacks.notifyStatusChanged(moveId, 17129 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 17130 } 17131 } 17132 }); 17133 return moveId; 17134 } 17135 17136 private void movePackageInternal(final String packageName, final String volumeUuid, 17137 final int moveId) throws PackageManagerException { 17138 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 17139 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17140 final PackageManager pm = mContext.getPackageManager(); 17141 17142 final boolean currentAsec; 17143 final String currentVolumeUuid; 17144 final File codeFile; 17145 final String installerPackageName; 17146 final String packageAbiOverride; 17147 final int appId; 17148 final String seinfo; 17149 final String label; 17150 final int targetSdkVersion; 17151 17152 // reader 17153 synchronized (mPackages) { 17154 final PackageParser.Package pkg = mPackages.get(packageName); 17155 final PackageSetting ps = mSettings.mPackages.get(packageName); 17156 if (pkg == null || ps == null) { 17157 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 17158 } 17159 17160 if (pkg.applicationInfo.isSystemApp()) { 17161 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 17162 "Cannot move system application"); 17163 } 17164 17165 if (pkg.applicationInfo.isExternalAsec()) { 17166 currentAsec = true; 17167 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 17168 } else if (pkg.applicationInfo.isForwardLocked()) { 17169 currentAsec = true; 17170 currentVolumeUuid = "forward_locked"; 17171 } else { 17172 currentAsec = false; 17173 currentVolumeUuid = ps.volumeUuid; 17174 17175 final File probe = new File(pkg.codePath); 17176 final File probeOat = new File(probe, "oat"); 17177 if (!probe.isDirectory() || !probeOat.isDirectory()) { 17178 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17179 "Move only supported for modern cluster style installs"); 17180 } 17181 } 17182 17183 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 17184 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17185 "Package already moved to " + volumeUuid); 17186 } 17187 17188 if (ps.frozen) { 17189 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 17190 "Failed to move already frozen package"); 17191 } 17192 ps.frozen = true; 17193 17194 codeFile = new File(pkg.codePath); 17195 installerPackageName = ps.installerPackageName; 17196 packageAbiOverride = ps.cpuAbiOverrideString; 17197 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 17198 seinfo = pkg.applicationInfo.seinfo; 17199 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 17200 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 17201 } 17202 17203 // Now that we're guarded by frozen state, kill app during move 17204 final long token = Binder.clearCallingIdentity(); 17205 try { 17206 killApplication(packageName, appId, "move pkg"); 17207 } finally { 17208 Binder.restoreCallingIdentity(token); 17209 } 17210 17211 final Bundle extras = new Bundle(); 17212 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 17213 extras.putString(Intent.EXTRA_TITLE, label); 17214 mMoveCallbacks.notifyCreated(moveId, extras); 17215 17216 int installFlags; 17217 final boolean moveCompleteApp; 17218 final File measurePath; 17219 17220 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 17221 installFlags = INSTALL_INTERNAL; 17222 moveCompleteApp = !currentAsec; 17223 measurePath = Environment.getDataAppDirectory(volumeUuid); 17224 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 17225 installFlags = INSTALL_EXTERNAL; 17226 moveCompleteApp = false; 17227 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 17228 } else { 17229 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 17230 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 17231 || !volume.isMountedWritable()) { 17232 unfreezePackage(packageName); 17233 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17234 "Move location not mounted private volume"); 17235 } 17236 17237 Preconditions.checkState(!currentAsec); 17238 17239 installFlags = INSTALL_INTERNAL; 17240 moveCompleteApp = true; 17241 measurePath = Environment.getDataAppDirectory(volumeUuid); 17242 } 17243 17244 final PackageStats stats = new PackageStats(null, -1); 17245 synchronized (mInstaller) { 17246 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 17247 unfreezePackage(packageName); 17248 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17249 "Failed to measure package size"); 17250 } 17251 } 17252 17253 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 17254 + stats.dataSize); 17255 17256 final long startFreeBytes = measurePath.getFreeSpace(); 17257 final long sizeBytes; 17258 if (moveCompleteApp) { 17259 sizeBytes = stats.codeSize + stats.dataSize; 17260 } else { 17261 sizeBytes = stats.codeSize; 17262 } 17263 17264 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 17265 unfreezePackage(packageName); 17266 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17267 "Not enough free space to move"); 17268 } 17269 17270 mMoveCallbacks.notifyStatusChanged(moveId, 10); 17271 17272 final CountDownLatch installedLatch = new CountDownLatch(1); 17273 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 17274 @Override 17275 public void onUserActionRequired(Intent intent) throws RemoteException { 17276 throw new IllegalStateException(); 17277 } 17278 17279 @Override 17280 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 17281 Bundle extras) throws RemoteException { 17282 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 17283 + PackageManager.installStatusToString(returnCode, msg)); 17284 17285 installedLatch.countDown(); 17286 17287 // Regardless of success or failure of the move operation, 17288 // always unfreeze the package 17289 unfreezePackage(packageName); 17290 17291 final int status = PackageManager.installStatusToPublicStatus(returnCode); 17292 switch (status) { 17293 case PackageInstaller.STATUS_SUCCESS: 17294 mMoveCallbacks.notifyStatusChanged(moveId, 17295 PackageManager.MOVE_SUCCEEDED); 17296 break; 17297 case PackageInstaller.STATUS_FAILURE_STORAGE: 17298 mMoveCallbacks.notifyStatusChanged(moveId, 17299 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 17300 break; 17301 default: 17302 mMoveCallbacks.notifyStatusChanged(moveId, 17303 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 17304 break; 17305 } 17306 } 17307 }; 17308 17309 final MoveInfo move; 17310 if (moveCompleteApp) { 17311 // Kick off a thread to report progress estimates 17312 new Thread() { 17313 @Override 17314 public void run() { 17315 while (true) { 17316 try { 17317 if (installedLatch.await(1, TimeUnit.SECONDS)) { 17318 break; 17319 } 17320 } catch (InterruptedException ignored) { 17321 } 17322 17323 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 17324 final int progress = 10 + (int) MathUtils.constrain( 17325 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 17326 mMoveCallbacks.notifyStatusChanged(moveId, progress); 17327 } 17328 } 17329 }.start(); 17330 17331 final String dataAppName = codeFile.getName(); 17332 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 17333 dataAppName, appId, seinfo, targetSdkVersion); 17334 } else { 17335 move = null; 17336 } 17337 17338 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 17339 17340 final Message msg = mHandler.obtainMessage(INIT_COPY); 17341 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 17342 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 17343 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 17344 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 17345 msg.obj = params; 17346 17347 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 17348 System.identityHashCode(msg.obj)); 17349 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 17350 System.identityHashCode(msg.obj)); 17351 17352 mHandler.sendMessage(msg); 17353 } 17354 17355 @Override 17356 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 17357 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 17358 17359 final int realMoveId = mNextMoveId.getAndIncrement(); 17360 final Bundle extras = new Bundle(); 17361 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 17362 mMoveCallbacks.notifyCreated(realMoveId, extras); 17363 17364 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 17365 @Override 17366 public void onCreated(int moveId, Bundle extras) { 17367 // Ignored 17368 } 17369 17370 @Override 17371 public void onStatusChanged(int moveId, int status, long estMillis) { 17372 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 17373 } 17374 }; 17375 17376 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17377 storage.setPrimaryStorageUuid(volumeUuid, callback); 17378 return realMoveId; 17379 } 17380 17381 @Override 17382 public int getMoveStatus(int moveId) { 17383 mContext.enforceCallingOrSelfPermission( 17384 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 17385 return mMoveCallbacks.mLastStatus.get(moveId); 17386 } 17387 17388 @Override 17389 public void registerMoveCallback(IPackageMoveObserver callback) { 17390 mContext.enforceCallingOrSelfPermission( 17391 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 17392 mMoveCallbacks.register(callback); 17393 } 17394 17395 @Override 17396 public void unregisterMoveCallback(IPackageMoveObserver callback) { 17397 mContext.enforceCallingOrSelfPermission( 17398 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 17399 mMoveCallbacks.unregister(callback); 17400 } 17401 17402 @Override 17403 public boolean setInstallLocation(int loc) { 17404 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 17405 null); 17406 if (getInstallLocation() == loc) { 17407 return true; 17408 } 17409 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 17410 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 17411 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 17412 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 17413 return true; 17414 } 17415 return false; 17416 } 17417 17418 @Override 17419 public int getInstallLocation() { 17420 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 17421 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 17422 PackageHelper.APP_INSTALL_AUTO); 17423 } 17424 17425 /** Called by UserManagerService */ 17426 void cleanUpUser(UserManagerService userManager, int userHandle) { 17427 synchronized (mPackages) { 17428 mDirtyUsers.remove(userHandle); 17429 mUserNeedsBadging.delete(userHandle); 17430 mSettings.removeUserLPw(userHandle); 17431 mPendingBroadcasts.remove(userHandle); 17432 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 17433 } 17434 synchronized (mInstallLock) { 17435 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17436 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 17437 final String volumeUuid = vol.getFsUuid(); 17438 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 17439 try { 17440 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 17441 } catch (InstallerException e) { 17442 Slog.w(TAG, "Failed to remove user data", e); 17443 } 17444 } 17445 synchronized (mPackages) { 17446 removeUnusedPackagesLILPw(userManager, userHandle); 17447 } 17448 } 17449 } 17450 17451 /** 17452 * We're removing userHandle and would like to remove any downloaded packages 17453 * that are no longer in use by any other user. 17454 * @param userHandle the user being removed 17455 */ 17456 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 17457 final boolean DEBUG_CLEAN_APKS = false; 17458 int [] users = userManager.getUserIds(); 17459 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 17460 while (psit.hasNext()) { 17461 PackageSetting ps = psit.next(); 17462 if (ps.pkg == null) { 17463 continue; 17464 } 17465 final String packageName = ps.pkg.packageName; 17466 // Skip over if system app 17467 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 17468 continue; 17469 } 17470 if (DEBUG_CLEAN_APKS) { 17471 Slog.i(TAG, "Checking package " + packageName); 17472 } 17473 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 17474 if (keep) { 17475 if (DEBUG_CLEAN_APKS) { 17476 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 17477 } 17478 } else { 17479 for (int i = 0; i < users.length; i++) { 17480 if (users[i] != userHandle && ps.getInstalled(users[i])) { 17481 keep = true; 17482 if (DEBUG_CLEAN_APKS) { 17483 Slog.i(TAG, " Keeping package " + packageName + " for user " 17484 + users[i]); 17485 } 17486 break; 17487 } 17488 } 17489 } 17490 if (!keep) { 17491 if (DEBUG_CLEAN_APKS) { 17492 Slog.i(TAG, " Removing package " + packageName); 17493 } 17494 mHandler.post(new Runnable() { 17495 public void run() { 17496 deletePackageX(packageName, userHandle, 0); 17497 } //end run 17498 }); 17499 } 17500 } 17501 } 17502 17503 /** Called by UserManagerService */ 17504 void createNewUser(int userHandle) { 17505 synchronized (mInstallLock) { 17506 try { 17507 mInstaller.createUserConfig(userHandle); 17508 } catch (InstallerException e) { 17509 Slog.w(TAG, "Failed to create user config", e); 17510 } 17511 mSettings.createNewUserLI(this, mInstaller, userHandle); 17512 } 17513 synchronized (mPackages) { 17514 applyFactoryDefaultBrowserLPw(userHandle); 17515 primeDomainVerificationsLPw(userHandle); 17516 } 17517 } 17518 17519 void newUserCreated(final int userHandle) { 17520 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 17521 // If permission review for legacy apps is required, we represent 17522 // dagerous permissions for such apps as always granted runtime 17523 // permissions to keep per user flag state whether review is needed. 17524 // Hence, if a new user is added we have to propagate dangerous 17525 // permission grants for these legacy apps. 17526 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 17527 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 17528 | UPDATE_PERMISSIONS_REPLACE_ALL); 17529 } 17530 } 17531 17532 @Override 17533 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 17534 mContext.enforceCallingOrSelfPermission( 17535 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 17536 "Only package verification agents can read the verifier device identity"); 17537 17538 synchronized (mPackages) { 17539 return mSettings.getVerifierDeviceIdentityLPw(); 17540 } 17541 } 17542 17543 @Override 17544 public void setPermissionEnforced(String permission, boolean enforced) { 17545 // TODO: Now that we no longer change GID for storage, this should to away. 17546 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 17547 "setPermissionEnforced"); 17548 if (READ_EXTERNAL_STORAGE.equals(permission)) { 17549 synchronized (mPackages) { 17550 if (mSettings.mReadExternalStorageEnforced == null 17551 || mSettings.mReadExternalStorageEnforced != enforced) { 17552 mSettings.mReadExternalStorageEnforced = enforced; 17553 mSettings.writeLPr(); 17554 } 17555 } 17556 // kill any non-foreground processes so we restart them and 17557 // grant/revoke the GID. 17558 final IActivityManager am = ActivityManagerNative.getDefault(); 17559 if (am != null) { 17560 final long token = Binder.clearCallingIdentity(); 17561 try { 17562 am.killProcessesBelowForeground("setPermissionEnforcement"); 17563 } catch (RemoteException e) { 17564 } finally { 17565 Binder.restoreCallingIdentity(token); 17566 } 17567 } 17568 } else { 17569 throw new IllegalArgumentException("No selective enforcement for " + permission); 17570 } 17571 } 17572 17573 @Override 17574 @Deprecated 17575 public boolean isPermissionEnforced(String permission) { 17576 return true; 17577 } 17578 17579 @Override 17580 public boolean isStorageLow() { 17581 final long token = Binder.clearCallingIdentity(); 17582 try { 17583 final DeviceStorageMonitorInternal 17584 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 17585 if (dsm != null) { 17586 return dsm.isMemoryLow(); 17587 } else { 17588 return false; 17589 } 17590 } finally { 17591 Binder.restoreCallingIdentity(token); 17592 } 17593 } 17594 17595 @Override 17596 public IPackageInstaller getPackageInstaller() { 17597 return mInstallerService; 17598 } 17599 17600 private boolean userNeedsBadging(int userId) { 17601 int index = mUserNeedsBadging.indexOfKey(userId); 17602 if (index < 0) { 17603 final UserInfo userInfo; 17604 final long token = Binder.clearCallingIdentity(); 17605 try { 17606 userInfo = sUserManager.getUserInfo(userId); 17607 } finally { 17608 Binder.restoreCallingIdentity(token); 17609 } 17610 final boolean b; 17611 if (userInfo != null && userInfo.isManagedProfile()) { 17612 b = true; 17613 } else { 17614 b = false; 17615 } 17616 mUserNeedsBadging.put(userId, b); 17617 return b; 17618 } 17619 return mUserNeedsBadging.valueAt(index); 17620 } 17621 17622 @Override 17623 public KeySet getKeySetByAlias(String packageName, String alias) { 17624 if (packageName == null || alias == null) { 17625 return null; 17626 } 17627 synchronized(mPackages) { 17628 final PackageParser.Package pkg = mPackages.get(packageName); 17629 if (pkg == null) { 17630 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17631 throw new IllegalArgumentException("Unknown package: " + packageName); 17632 } 17633 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17634 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 17635 } 17636 } 17637 17638 @Override 17639 public KeySet getSigningKeySet(String packageName) { 17640 if (packageName == null) { 17641 return null; 17642 } 17643 synchronized(mPackages) { 17644 final PackageParser.Package pkg = mPackages.get(packageName); 17645 if (pkg == null) { 17646 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17647 throw new IllegalArgumentException("Unknown package: " + packageName); 17648 } 17649 if (pkg.applicationInfo.uid != Binder.getCallingUid() 17650 && Process.SYSTEM_UID != Binder.getCallingUid()) { 17651 throw new SecurityException("May not access signing KeySet of other apps."); 17652 } 17653 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17654 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 17655 } 17656 } 17657 17658 @Override 17659 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 17660 if (packageName == null || ks == null) { 17661 return false; 17662 } 17663 synchronized(mPackages) { 17664 final PackageParser.Package pkg = mPackages.get(packageName); 17665 if (pkg == null) { 17666 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17667 throw new IllegalArgumentException("Unknown package: " + packageName); 17668 } 17669 IBinder ksh = ks.getToken(); 17670 if (ksh instanceof KeySetHandle) { 17671 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17672 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 17673 } 17674 return false; 17675 } 17676 } 17677 17678 @Override 17679 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 17680 if (packageName == null || ks == null) { 17681 return false; 17682 } 17683 synchronized(mPackages) { 17684 final PackageParser.Package pkg = mPackages.get(packageName); 17685 if (pkg == null) { 17686 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17687 throw new IllegalArgumentException("Unknown package: " + packageName); 17688 } 17689 IBinder ksh = ks.getToken(); 17690 if (ksh instanceof KeySetHandle) { 17691 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17692 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 17693 } 17694 return false; 17695 } 17696 } 17697 17698 private void deletePackageIfUnusedLPr(final String packageName) { 17699 PackageSetting ps = mSettings.mPackages.get(packageName); 17700 if (ps == null) { 17701 return; 17702 } 17703 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 17704 // TODO Implement atomic delete if package is unused 17705 // It is currently possible that the package will be deleted even if it is installed 17706 // after this method returns. 17707 mHandler.post(new Runnable() { 17708 public void run() { 17709 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 17710 } 17711 }); 17712 } 17713 } 17714 17715 /** 17716 * Check and throw if the given before/after packages would be considered a 17717 * downgrade. 17718 */ 17719 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 17720 throws PackageManagerException { 17721 if (after.versionCode < before.mVersionCode) { 17722 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17723 "Update version code " + after.versionCode + " is older than current " 17724 + before.mVersionCode); 17725 } else if (after.versionCode == before.mVersionCode) { 17726 if (after.baseRevisionCode < before.baseRevisionCode) { 17727 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17728 "Update base revision code " + after.baseRevisionCode 17729 + " is older than current " + before.baseRevisionCode); 17730 } 17731 17732 if (!ArrayUtils.isEmpty(after.splitNames)) { 17733 for (int i = 0; i < after.splitNames.length; i++) { 17734 final String splitName = after.splitNames[i]; 17735 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 17736 if (j != -1) { 17737 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 17738 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17739 "Update split " + splitName + " revision code " 17740 + after.splitRevisionCodes[i] + " is older than current " 17741 + before.splitRevisionCodes[j]); 17742 } 17743 } 17744 } 17745 } 17746 } 17747 } 17748 17749 private static class MoveCallbacks extends Handler { 17750 private static final int MSG_CREATED = 1; 17751 private static final int MSG_STATUS_CHANGED = 2; 17752 17753 private final RemoteCallbackList<IPackageMoveObserver> 17754 mCallbacks = new RemoteCallbackList<>(); 17755 17756 private final SparseIntArray mLastStatus = new SparseIntArray(); 17757 17758 public MoveCallbacks(Looper looper) { 17759 super(looper); 17760 } 17761 17762 public void register(IPackageMoveObserver callback) { 17763 mCallbacks.register(callback); 17764 } 17765 17766 public void unregister(IPackageMoveObserver callback) { 17767 mCallbacks.unregister(callback); 17768 } 17769 17770 @Override 17771 public void handleMessage(Message msg) { 17772 final SomeArgs args = (SomeArgs) msg.obj; 17773 final int n = mCallbacks.beginBroadcast(); 17774 for (int i = 0; i < n; i++) { 17775 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 17776 try { 17777 invokeCallback(callback, msg.what, args); 17778 } catch (RemoteException ignored) { 17779 } 17780 } 17781 mCallbacks.finishBroadcast(); 17782 args.recycle(); 17783 } 17784 17785 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 17786 throws RemoteException { 17787 switch (what) { 17788 case MSG_CREATED: { 17789 callback.onCreated(args.argi1, (Bundle) args.arg2); 17790 break; 17791 } 17792 case MSG_STATUS_CHANGED: { 17793 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 17794 break; 17795 } 17796 } 17797 } 17798 17799 private void notifyCreated(int moveId, Bundle extras) { 17800 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 17801 17802 final SomeArgs args = SomeArgs.obtain(); 17803 args.argi1 = moveId; 17804 args.arg2 = extras; 17805 obtainMessage(MSG_CREATED, args).sendToTarget(); 17806 } 17807 17808 private void notifyStatusChanged(int moveId, int status) { 17809 notifyStatusChanged(moveId, status, -1); 17810 } 17811 17812 private void notifyStatusChanged(int moveId, int status, long estMillis) { 17813 Slog.v(TAG, "Move " + moveId + " status " + status); 17814 17815 final SomeArgs args = SomeArgs.obtain(); 17816 args.argi1 = moveId; 17817 args.argi2 = status; 17818 args.arg3 = estMillis; 17819 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 17820 17821 synchronized (mLastStatus) { 17822 mLastStatus.put(moveId, status); 17823 } 17824 } 17825 } 17826 17827 private final static class OnPermissionChangeListeners extends Handler { 17828 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 17829 17830 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 17831 new RemoteCallbackList<>(); 17832 17833 public OnPermissionChangeListeners(Looper looper) { 17834 super(looper); 17835 } 17836 17837 @Override 17838 public void handleMessage(Message msg) { 17839 switch (msg.what) { 17840 case MSG_ON_PERMISSIONS_CHANGED: { 17841 final int uid = msg.arg1; 17842 handleOnPermissionsChanged(uid); 17843 } break; 17844 } 17845 } 17846 17847 public void addListenerLocked(IOnPermissionsChangeListener listener) { 17848 mPermissionListeners.register(listener); 17849 17850 } 17851 17852 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 17853 mPermissionListeners.unregister(listener); 17854 } 17855 17856 public void onPermissionsChanged(int uid) { 17857 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 17858 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 17859 } 17860 } 17861 17862 private void handleOnPermissionsChanged(int uid) { 17863 final int count = mPermissionListeners.beginBroadcast(); 17864 try { 17865 for (int i = 0; i < count; i++) { 17866 IOnPermissionsChangeListener callback = mPermissionListeners 17867 .getBroadcastItem(i); 17868 try { 17869 callback.onPermissionsChanged(uid); 17870 } catch (RemoteException e) { 17871 Log.e(TAG, "Permission listener is dead", e); 17872 } 17873 } 17874 } finally { 17875 mPermissionListeners.finishBroadcast(); 17876 } 17877 } 17878 } 17879 17880 private class PackageManagerInternalImpl extends PackageManagerInternal { 17881 @Override 17882 public void setLocationPackagesProvider(PackagesProvider provider) { 17883 synchronized (mPackages) { 17884 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 17885 } 17886 } 17887 17888 @Override 17889 public void setImePackagesProvider(PackagesProvider provider) { 17890 synchronized (mPackages) { 17891 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 17892 } 17893 } 17894 17895 @Override 17896 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 17897 synchronized (mPackages) { 17898 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 17899 } 17900 } 17901 17902 @Override 17903 public void setSmsAppPackagesProvider(PackagesProvider provider) { 17904 synchronized (mPackages) { 17905 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 17906 } 17907 } 17908 17909 @Override 17910 public void setDialerAppPackagesProvider(PackagesProvider provider) { 17911 synchronized (mPackages) { 17912 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 17913 } 17914 } 17915 17916 @Override 17917 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 17918 synchronized (mPackages) { 17919 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 17920 } 17921 } 17922 17923 @Override 17924 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 17925 synchronized (mPackages) { 17926 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 17927 } 17928 } 17929 17930 @Override 17931 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 17932 synchronized (mPackages) { 17933 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 17934 packageName, userId); 17935 } 17936 } 17937 17938 @Override 17939 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 17940 synchronized (mPackages) { 17941 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 17942 packageName, userId); 17943 } 17944 } 17945 17946 @Override 17947 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 17948 synchronized (mPackages) { 17949 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 17950 packageName, userId); 17951 } 17952 } 17953 17954 @Override 17955 public void setKeepUninstalledPackages(final List<String> packageList) { 17956 Preconditions.checkNotNull(packageList); 17957 List<String> removedFromList = null; 17958 synchronized (mPackages) { 17959 if (mKeepUninstalledPackages != null) { 17960 final int packagesCount = mKeepUninstalledPackages.size(); 17961 for (int i = 0; i < packagesCount; i++) { 17962 String oldPackage = mKeepUninstalledPackages.get(i); 17963 if (packageList != null && packageList.contains(oldPackage)) { 17964 continue; 17965 } 17966 if (removedFromList == null) { 17967 removedFromList = new ArrayList<>(); 17968 } 17969 removedFromList.add(oldPackage); 17970 } 17971 } 17972 mKeepUninstalledPackages = new ArrayList<>(packageList); 17973 if (removedFromList != null) { 17974 final int removedCount = removedFromList.size(); 17975 for (int i = 0; i < removedCount; i++) { 17976 deletePackageIfUnusedLPr(removedFromList.get(i)); 17977 } 17978 } 17979 } 17980 } 17981 17982 @Override 17983 public boolean isPermissionsReviewRequired(String packageName, int userId) { 17984 synchronized (mPackages) { 17985 // If we do not support permission review, done. 17986 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 17987 return false; 17988 } 17989 17990 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 17991 if (packageSetting == null) { 17992 return false; 17993 } 17994 17995 // Permission review applies only to apps not supporting the new permission model. 17996 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 17997 return false; 17998 } 17999 18000 // Legacy apps have the permission and get user consent on launch. 18001 PermissionsState permissionsState = packageSetting.getPermissionsState(); 18002 return permissionsState.isPermissionReviewRequired(userId); 18003 } 18004 } 18005 } 18006 18007 @Override 18008 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 18009 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 18010 synchronized (mPackages) { 18011 final long identity = Binder.clearCallingIdentity(); 18012 try { 18013 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 18014 packageNames, userId); 18015 } finally { 18016 Binder.restoreCallingIdentity(identity); 18017 } 18018 } 18019 } 18020 18021 private static void enforceSystemOrPhoneCaller(String tag) { 18022 int callingUid = Binder.getCallingUid(); 18023 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 18024 throw new SecurityException( 18025 "Cannot call " + tag + " from UID " + callingUid); 18026 } 18027 } 18028} 18029