PackageManagerService.java revision c9a0237f5f49f2ffa52affb1bfd3e190b2267f22
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 34import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 35import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 36import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 37import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 40import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 41import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 45import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 46import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 47import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 48import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 54import static android.content.pm.PackageManager.INSTALL_INTERNAL; 55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 61import static android.content.pm.PackageManager.MATCH_ALL; 62import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 63import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 64import static android.content.pm.PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE; 65import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 66import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 67import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 68import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 69import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 70import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 71import static android.content.pm.PackageManager.PERMISSION_DENIED; 72import static android.content.pm.PackageManager.PERMISSION_GRANTED; 73import static android.content.pm.PackageParser.isApkFile; 74import static android.os.Process.PACKAGE_INFO_GID; 75import static android.os.Process.SYSTEM_UID; 76import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 77import static android.system.OsConstants.O_CREAT; 78import static android.system.OsConstants.O_RDWR; 79 80import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 81import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 82import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 83import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 84import static com.android.internal.util.ArrayUtils.appendInt; 85import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 86import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 87import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 88import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 89import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 90import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 91import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 92import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 93import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 94 95import android.Manifest; 96import android.annotation.NonNull; 97import android.annotation.Nullable; 98import android.app.ActivityManager; 99import android.app.ActivityManagerNative; 100import android.app.AppGlobals; 101import android.app.IActivityManager; 102import android.app.admin.IDevicePolicyManager; 103import android.app.backup.IBackupManager; 104import android.content.BroadcastReceiver; 105import android.content.ComponentName; 106import android.content.Context; 107import android.content.IIntentReceiver; 108import android.content.Intent; 109import android.content.IntentFilter; 110import android.content.IntentSender; 111import android.content.IntentSender.SendIntentException; 112import android.content.ServiceConnection; 113import android.content.pm.ActivityInfo; 114import android.content.pm.ApplicationInfo; 115import android.content.pm.AppsQueryHelper; 116import android.content.pm.ComponentInfo; 117import android.content.pm.EphemeralApplicationInfo; 118import android.content.pm.EphemeralResolveInfo; 119import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 120import android.content.pm.FeatureInfo; 121import android.content.pm.IOnPermissionsChangeListener; 122import android.content.pm.IPackageDataObserver; 123import android.content.pm.IPackageDeleteObserver; 124import android.content.pm.IPackageDeleteObserver2; 125import android.content.pm.IPackageInstallObserver2; 126import android.content.pm.IPackageInstaller; 127import android.content.pm.IPackageManager; 128import android.content.pm.IPackageMoveObserver; 129import android.content.pm.IPackageStatsObserver; 130import android.content.pm.InstrumentationInfo; 131import android.content.pm.IntentFilterVerificationInfo; 132import android.content.pm.KeySet; 133import android.content.pm.PackageCleanItem; 134import android.content.pm.PackageInfo; 135import android.content.pm.PackageInfoLite; 136import android.content.pm.PackageInstaller; 137import android.content.pm.PackageManager; 138import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 139import android.content.pm.PackageManagerInternal; 140import android.content.pm.PackageParser; 141import android.content.pm.PackageParser.ActivityIntentInfo; 142import android.content.pm.PackageParser.PackageLite; 143import android.content.pm.PackageParser.PackageParserException; 144import android.content.pm.PackageStats; 145import android.content.pm.PackageUserState; 146import android.content.pm.ParceledListSlice; 147import android.content.pm.PermissionGroupInfo; 148import android.content.pm.PermissionInfo; 149import android.content.pm.ProviderInfo; 150import android.content.pm.ResolveInfo; 151import android.content.pm.ServiceInfo; 152import android.content.pm.Signature; 153import android.content.pm.UserInfo; 154import android.content.pm.VerificationParams; 155import android.content.pm.VerifierDeviceIdentity; 156import android.content.pm.VerifierInfo; 157import android.content.res.Resources; 158import android.graphics.Bitmap; 159import android.hardware.display.DisplayManager; 160import android.net.Uri; 161import android.os.Binder; 162import android.os.Build; 163import android.os.Bundle; 164import android.os.Debug; 165import android.os.Environment; 166import android.os.Environment.UserEnvironment; 167import android.os.FileUtils; 168import android.os.Handler; 169import android.os.IBinder; 170import android.os.Looper; 171import android.os.Message; 172import android.os.Parcel; 173import android.os.ParcelFileDescriptor; 174import android.os.Process; 175import android.os.RemoteCallbackList; 176import android.os.RemoteException; 177import android.os.ResultReceiver; 178import android.os.SELinux; 179import android.os.ServiceManager; 180import android.os.SystemClock; 181import android.os.SystemProperties; 182import android.os.Trace; 183import android.os.UserHandle; 184import android.os.UserManager; 185import android.os.storage.IMountService; 186import android.os.storage.MountServiceInternal; 187import android.os.storage.StorageEventListener; 188import android.os.storage.StorageManager; 189import android.os.storage.VolumeInfo; 190import android.os.storage.VolumeRecord; 191import android.security.KeyStore; 192import android.security.SystemKeyStore; 193import android.system.ErrnoException; 194import android.system.Os; 195import android.text.TextUtils; 196import android.text.format.DateUtils; 197import android.util.ArrayMap; 198import android.util.ArraySet; 199import android.util.AtomicFile; 200import android.util.DisplayMetrics; 201import android.util.EventLog; 202import android.util.ExceptionUtils; 203import android.util.Log; 204import android.util.LogPrinter; 205import android.util.MathUtils; 206import android.util.PrintStreamPrinter; 207import android.util.Slog; 208import android.util.SparseArray; 209import android.util.SparseBooleanArray; 210import android.util.SparseIntArray; 211import android.util.Xml; 212import android.view.Display; 213 214import com.android.internal.R; 215import com.android.internal.annotations.GuardedBy; 216import com.android.internal.app.IMediaContainerService; 217import com.android.internal.app.ResolverActivity; 218import com.android.internal.content.NativeLibraryHelper; 219import com.android.internal.content.PackageHelper; 220import com.android.internal.os.IParcelFileDescriptorFactory; 221import com.android.internal.os.InstallerConnection.InstallerException; 222import com.android.internal.os.SomeArgs; 223import com.android.internal.os.Zygote; 224import com.android.internal.util.ArrayUtils; 225import com.android.internal.util.FastPrintWriter; 226import com.android.internal.util.FastXmlSerializer; 227import com.android.internal.util.IndentingPrintWriter; 228import com.android.internal.util.Preconditions; 229import com.android.internal.util.XmlUtils; 230import com.android.server.EventLogTags; 231import com.android.server.FgThread; 232import com.android.server.IntentResolver; 233import com.android.server.LocalServices; 234import com.android.server.ServiceThread; 235import com.android.server.SystemConfig; 236import com.android.server.Watchdog; 237import com.android.server.pm.Installer.StorageFlags; 238import com.android.server.pm.PermissionsState.PermissionState; 239import com.android.server.pm.Settings.DatabaseVersion; 240import com.android.server.pm.Settings.VersionInfo; 241import com.android.server.storage.DeviceStorageMonitorInternal; 242 243import dalvik.system.DexFile; 244import dalvik.system.VMRuntime; 245 246import libcore.io.IoUtils; 247import libcore.util.EmptyArray; 248 249import org.xmlpull.v1.XmlPullParser; 250import org.xmlpull.v1.XmlPullParserException; 251import org.xmlpull.v1.XmlSerializer; 252 253import java.io.BufferedInputStream; 254import java.io.BufferedOutputStream; 255import java.io.BufferedReader; 256import java.io.ByteArrayInputStream; 257import java.io.ByteArrayOutputStream; 258import java.io.File; 259import java.io.FileDescriptor; 260import java.io.FileNotFoundException; 261import java.io.FileOutputStream; 262import java.io.FileReader; 263import java.io.FilenameFilter; 264import java.io.IOException; 265import java.io.InputStream; 266import java.io.PrintWriter; 267import java.nio.charset.StandardCharsets; 268import java.security.MessageDigest; 269import java.security.NoSuchAlgorithmException; 270import java.security.PublicKey; 271import java.security.cert.CertificateEncodingException; 272import java.security.cert.CertificateException; 273import java.text.SimpleDateFormat; 274import java.util.ArrayList; 275import java.util.Arrays; 276import java.util.Collection; 277import java.util.Collections; 278import java.util.Comparator; 279import java.util.Date; 280import java.util.Iterator; 281import java.util.List; 282import java.util.Map; 283import java.util.Objects; 284import java.util.Set; 285import java.util.concurrent.CountDownLatch; 286import java.util.concurrent.TimeUnit; 287import java.util.concurrent.atomic.AtomicBoolean; 288import java.util.concurrent.atomic.AtomicInteger; 289import java.util.concurrent.atomic.AtomicLong; 290 291/** 292 * Keep track of all those .apks everywhere. 293 * 294 * This is very central to the platform's security; please run the unit 295 * tests whenever making modifications here: 296 * 297runtest -c android.content.pm.PackageManagerTests frameworks-core 298 * 299 * {@hide} 300 */ 301public class PackageManagerService extends IPackageManager.Stub { 302 static final String TAG = "PackageManager"; 303 static final boolean DEBUG_SETTINGS = false; 304 static final boolean DEBUG_PREFERRED = false; 305 static final boolean DEBUG_UPGRADE = false; 306 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 307 private static final boolean DEBUG_BACKUP = false; 308 private static final boolean DEBUG_INSTALL = false; 309 private static final boolean DEBUG_REMOVE = false; 310 private static final boolean DEBUG_BROADCASTS = false; 311 private static final boolean DEBUG_SHOW_INFO = false; 312 private static final boolean DEBUG_PACKAGE_INFO = false; 313 private static final boolean DEBUG_INTENT_MATCHING = false; 314 private static final boolean DEBUG_PACKAGE_SCANNING = false; 315 private static final boolean DEBUG_VERIFY = false; 316 private static final boolean DEBUG_DEXOPT = false; 317 private static final boolean DEBUG_ABI_SELECTION = false; 318 private static final boolean DEBUG_EPHEMERAL = false; 319 private static final boolean DEBUG_TRIAGED_MISSING = false; 320 private static final boolean DEBUG_APP_DATA = false; 321 322 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 323 324 private static final boolean DISABLE_EPHEMERAL_APPS = true; 325 326 private static final int RADIO_UID = Process.PHONE_UID; 327 private static final int LOG_UID = Process.LOG_UID; 328 private static final int NFC_UID = Process.NFC_UID; 329 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 330 private static final int SHELL_UID = Process.SHELL_UID; 331 332 // Cap the size of permission trees that 3rd party apps can define 333 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 334 335 // Suffix used during package installation when copying/moving 336 // package apks to install directory. 337 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 338 339 static final int SCAN_NO_DEX = 1<<1; 340 static final int SCAN_FORCE_DEX = 1<<2; 341 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 342 static final int SCAN_NEW_INSTALL = 1<<4; 343 static final int SCAN_NO_PATHS = 1<<5; 344 static final int SCAN_UPDATE_TIME = 1<<6; 345 static final int SCAN_DEFER_DEX = 1<<7; 346 static final int SCAN_BOOTING = 1<<8; 347 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 348 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 349 static final int SCAN_REPLACING = 1<<11; 350 static final int SCAN_REQUIRE_KNOWN = 1<<12; 351 static final int SCAN_MOVE = 1<<13; 352 static final int SCAN_INITIAL = 1<<14; 353 354 static final int REMOVE_CHATTY = 1<<16; 355 356 private static final int[] EMPTY_INT_ARRAY = new int[0]; 357 358 /** 359 * Timeout (in milliseconds) after which the watchdog should declare that 360 * our handler thread is wedged. The usual default for such things is one 361 * minute but we sometimes do very lengthy I/O operations on this thread, 362 * such as installing multi-gigabyte applications, so ours needs to be longer. 363 */ 364 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 365 366 /** 367 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 368 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 369 * settings entry if available, otherwise we use the hardcoded default. If it's been 370 * more than this long since the last fstrim, we force one during the boot sequence. 371 * 372 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 373 * one gets run at the next available charging+idle time. This final mandatory 374 * no-fstrim check kicks in only of the other scheduling criteria is never met. 375 */ 376 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 377 378 /** 379 * Whether verification is enabled by default. 380 */ 381 private static final boolean DEFAULT_VERIFY_ENABLE = true; 382 383 /** 384 * The default maximum time to wait for the verification agent to return in 385 * milliseconds. 386 */ 387 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 388 389 /** 390 * The default response for package verification timeout. 391 * 392 * This can be either PackageManager.VERIFICATION_ALLOW or 393 * PackageManager.VERIFICATION_REJECT. 394 */ 395 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 396 397 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 398 399 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 400 DEFAULT_CONTAINER_PACKAGE, 401 "com.android.defcontainer.DefaultContainerService"); 402 403 private static final String KILL_APP_REASON_GIDS_CHANGED = 404 "permission grant or revoke changed gids"; 405 406 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 407 "permissions revoked"; 408 409 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 410 411 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 412 413 /** Permission grant: not grant the permission. */ 414 private static final int GRANT_DENIED = 1; 415 416 /** Permission grant: grant the permission as an install permission. */ 417 private static final int GRANT_INSTALL = 2; 418 419 /** Permission grant: grant the permission as a runtime one. */ 420 private static final int GRANT_RUNTIME = 3; 421 422 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 423 private static final int GRANT_UPGRADE = 4; 424 425 /** Canonical intent used to identify what counts as a "web browser" app */ 426 private static final Intent sBrowserIntent; 427 static { 428 sBrowserIntent = new Intent(); 429 sBrowserIntent.setAction(Intent.ACTION_VIEW); 430 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 431 sBrowserIntent.setData(Uri.parse("http:")); 432 } 433 434 final ServiceThread mHandlerThread; 435 436 final PackageHandler mHandler; 437 438 /** 439 * Messages for {@link #mHandler} that need to wait for system ready before 440 * being dispatched. 441 */ 442 private ArrayList<Message> mPostSystemReadyMessages; 443 444 final int mSdkVersion = Build.VERSION.SDK_INT; 445 446 final Context mContext; 447 final boolean mFactoryTest; 448 final boolean mOnlyCore; 449 final DisplayMetrics mMetrics; 450 final int mDefParseFlags; 451 final String[] mSeparateProcesses; 452 final boolean mIsUpgrade; 453 454 /** The location for ASEC container files on internal storage. */ 455 final String mAsecInternalPath; 456 457 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 458 // LOCK HELD. Can be called with mInstallLock held. 459 @GuardedBy("mInstallLock") 460 final Installer mInstaller; 461 462 /** Directory where installed third-party apps stored */ 463 final File mAppInstallDir; 464 final File mEphemeralInstallDir; 465 466 /** 467 * Directory to which applications installed internally have their 468 * 32 bit native libraries copied. 469 */ 470 private File mAppLib32InstallDir; 471 472 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 473 // apps. 474 final File mDrmAppPrivateInstallDir; 475 476 // ---------------------------------------------------------------- 477 478 // Lock for state used when installing and doing other long running 479 // operations. Methods that must be called with this lock held have 480 // the suffix "LI". 481 final Object mInstallLock = new Object(); 482 483 // ---------------------------------------------------------------- 484 485 // Keys are String (package name), values are Package. This also serves 486 // as the lock for the global state. Methods that must be called with 487 // this lock held have the prefix "LP". 488 @GuardedBy("mPackages") 489 final ArrayMap<String, PackageParser.Package> mPackages = 490 new ArrayMap<String, PackageParser.Package>(); 491 492 // Tracks available target package names -> overlay package paths. 493 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 494 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 495 496 /** 497 * Tracks new system packages [received in an OTA] that we expect to 498 * find updated user-installed versions. Keys are package name, values 499 * are package location. 500 */ 501 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 502 503 /** 504 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 505 */ 506 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 507 /** 508 * Whether or not system app permissions should be promoted from install to runtime. 509 */ 510 boolean mPromoteSystemApps; 511 512 final Settings mSettings; 513 boolean mRestoredSettings; 514 515 // System configuration read by SystemConfig. 516 final int[] mGlobalGids; 517 final SparseArray<ArraySet<String>> mSystemPermissions; 518 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 519 520 // If mac_permissions.xml was found for seinfo labeling. 521 boolean mFoundPolicyFile; 522 523 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 524 525 public static final class SharedLibraryEntry { 526 public final String path; 527 public final String apk; 528 529 SharedLibraryEntry(String _path, String _apk) { 530 path = _path; 531 apk = _apk; 532 } 533 } 534 535 // Currently known shared libraries. 536 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 537 new ArrayMap<String, SharedLibraryEntry>(); 538 539 // All available activities, for your resolving pleasure. 540 final ActivityIntentResolver mActivities = 541 new ActivityIntentResolver(); 542 543 // All available receivers, for your resolving pleasure. 544 final ActivityIntentResolver mReceivers = 545 new ActivityIntentResolver(); 546 547 // All available services, for your resolving pleasure. 548 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 549 550 // All available providers, for your resolving pleasure. 551 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 552 553 // Mapping from provider base names (first directory in content URI codePath) 554 // to the provider information. 555 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 556 new ArrayMap<String, PackageParser.Provider>(); 557 558 // Mapping from instrumentation class names to info about them. 559 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 560 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 561 562 // Mapping from permission names to info about them. 563 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 564 new ArrayMap<String, PackageParser.PermissionGroup>(); 565 566 // Packages whose data we have transfered into another package, thus 567 // should no longer exist. 568 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 569 570 // Broadcast actions that are only available to the system. 571 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 572 573 /** List of packages waiting for verification. */ 574 final SparseArray<PackageVerificationState> mPendingVerification 575 = new SparseArray<PackageVerificationState>(); 576 577 /** Set of packages associated with each app op permission. */ 578 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 579 580 final PackageInstallerService mInstallerService; 581 582 private final PackageDexOptimizer mPackageDexOptimizer; 583 584 private AtomicInteger mNextMoveId = new AtomicInteger(); 585 private final MoveCallbacks mMoveCallbacks; 586 587 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 588 589 // Cache of users who need badging. 590 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 591 592 /** Token for keys in mPendingVerification. */ 593 private int mPendingVerificationToken = 0; 594 595 volatile boolean mSystemReady; 596 volatile boolean mSafeMode; 597 volatile boolean mHasSystemUidErrors; 598 599 ApplicationInfo mAndroidApplication; 600 final ActivityInfo mResolveActivity = new ActivityInfo(); 601 final ResolveInfo mResolveInfo = new ResolveInfo(); 602 ComponentName mResolveComponentName; 603 PackageParser.Package mPlatformPackage; 604 ComponentName mCustomResolverComponentName; 605 606 boolean mResolverReplaced = false; 607 608 private final @Nullable ComponentName mIntentFilterVerifierComponent; 609 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 610 611 private int mIntentFilterVerificationToken = 0; 612 613 /** Component that knows whether or not an ephemeral application exists */ 614 final ComponentName mEphemeralResolverComponent; 615 /** The service connection to the ephemeral resolver */ 616 final EphemeralResolverConnection mEphemeralResolverConnection; 617 618 /** Component used to install ephemeral applications */ 619 final ComponentName mEphemeralInstallerComponent; 620 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 621 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 622 623 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 624 = new SparseArray<IntentFilterVerificationState>(); 625 626 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 627 new DefaultPermissionGrantPolicy(this); 628 629 // List of packages names to keep cached, even if they are uninstalled for all users 630 private List<String> mKeepUninstalledPackages; 631 632 private boolean mUseJitProfiles = 633 SystemProperties.getBoolean("dalvik.vm.usejitprofiles", false); 634 635 private static class IFVerificationParams { 636 PackageParser.Package pkg; 637 boolean replacing; 638 int userId; 639 int verifierUid; 640 641 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 642 int _userId, int _verifierUid) { 643 pkg = _pkg; 644 replacing = _replacing; 645 userId = _userId; 646 replacing = _replacing; 647 verifierUid = _verifierUid; 648 } 649 } 650 651 private interface IntentFilterVerifier<T extends IntentFilter> { 652 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 653 T filter, String packageName); 654 void startVerifications(int userId); 655 void receiveVerificationResponse(int verificationId); 656 } 657 658 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 659 private Context mContext; 660 private ComponentName mIntentFilterVerifierComponent; 661 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 662 663 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 664 mContext = context; 665 mIntentFilterVerifierComponent = verifierComponent; 666 } 667 668 private String getDefaultScheme() { 669 return IntentFilter.SCHEME_HTTPS; 670 } 671 672 @Override 673 public void startVerifications(int userId) { 674 // Launch verifications requests 675 int count = mCurrentIntentFilterVerifications.size(); 676 for (int n=0; n<count; n++) { 677 int verificationId = mCurrentIntentFilterVerifications.get(n); 678 final IntentFilterVerificationState ivs = 679 mIntentFilterVerificationStates.get(verificationId); 680 681 String packageName = ivs.getPackageName(); 682 683 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 684 final int filterCount = filters.size(); 685 ArraySet<String> domainsSet = new ArraySet<>(); 686 for (int m=0; m<filterCount; m++) { 687 PackageParser.ActivityIntentInfo filter = filters.get(m); 688 domainsSet.addAll(filter.getHostsList()); 689 } 690 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 691 synchronized (mPackages) { 692 if (mSettings.createIntentFilterVerificationIfNeededLPw( 693 packageName, domainsList) != null) { 694 scheduleWriteSettingsLocked(); 695 } 696 } 697 sendVerificationRequest(userId, verificationId, ivs); 698 } 699 mCurrentIntentFilterVerifications.clear(); 700 } 701 702 private void sendVerificationRequest(int userId, int verificationId, 703 IntentFilterVerificationState ivs) { 704 705 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 706 verificationIntent.putExtra( 707 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 708 verificationId); 709 verificationIntent.putExtra( 710 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 711 getDefaultScheme()); 712 verificationIntent.putExtra( 713 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 714 ivs.getHostsString()); 715 verificationIntent.putExtra( 716 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 717 ivs.getPackageName()); 718 verificationIntent.setComponent(mIntentFilterVerifierComponent); 719 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 720 721 UserHandle user = new UserHandle(userId); 722 mContext.sendBroadcastAsUser(verificationIntent, user); 723 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 724 "Sending IntentFilter verification broadcast"); 725 } 726 727 public void receiveVerificationResponse(int verificationId) { 728 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 729 730 final boolean verified = ivs.isVerified(); 731 732 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 733 final int count = filters.size(); 734 if (DEBUG_DOMAIN_VERIFICATION) { 735 Slog.i(TAG, "Received verification response " + verificationId 736 + " for " + count + " filters, verified=" + verified); 737 } 738 for (int n=0; n<count; n++) { 739 PackageParser.ActivityIntentInfo filter = filters.get(n); 740 filter.setVerified(verified); 741 742 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 743 + " verified with result:" + verified + " and hosts:" 744 + ivs.getHostsString()); 745 } 746 747 mIntentFilterVerificationStates.remove(verificationId); 748 749 final String packageName = ivs.getPackageName(); 750 IntentFilterVerificationInfo ivi = null; 751 752 synchronized (mPackages) { 753 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 754 } 755 if (ivi == null) { 756 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 757 + verificationId + " packageName:" + packageName); 758 return; 759 } 760 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 761 "Updating IntentFilterVerificationInfo for package " + packageName 762 +" verificationId:" + verificationId); 763 764 synchronized (mPackages) { 765 if (verified) { 766 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 767 } else { 768 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 769 } 770 scheduleWriteSettingsLocked(); 771 772 final int userId = ivs.getUserId(); 773 if (userId != UserHandle.USER_ALL) { 774 final int userStatus = 775 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 776 777 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 778 boolean needUpdate = false; 779 780 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 781 // already been set by the User thru the Disambiguation dialog 782 switch (userStatus) { 783 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 784 if (verified) { 785 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 786 } else { 787 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 788 } 789 needUpdate = true; 790 break; 791 792 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 793 if (verified) { 794 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 795 needUpdate = true; 796 } 797 break; 798 799 default: 800 // Nothing to do 801 } 802 803 if (needUpdate) { 804 mSettings.updateIntentFilterVerificationStatusLPw( 805 packageName, updatedStatus, userId); 806 scheduleWritePackageRestrictionsLocked(userId); 807 } 808 } 809 } 810 } 811 812 @Override 813 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 814 ActivityIntentInfo filter, String packageName) { 815 if (!hasValidDomains(filter)) { 816 return false; 817 } 818 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 819 if (ivs == null) { 820 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 821 packageName); 822 } 823 if (DEBUG_DOMAIN_VERIFICATION) { 824 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 825 } 826 ivs.addFilter(filter); 827 return true; 828 } 829 830 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 831 int userId, int verificationId, String packageName) { 832 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 833 verifierUid, userId, packageName); 834 ivs.setPendingState(); 835 synchronized (mPackages) { 836 mIntentFilterVerificationStates.append(verificationId, ivs); 837 mCurrentIntentFilterVerifications.add(verificationId); 838 } 839 return ivs; 840 } 841 } 842 843 private static boolean hasValidDomains(ActivityIntentInfo filter) { 844 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 845 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 846 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 847 } 848 849 // Set of pending broadcasts for aggregating enable/disable of components. 850 static class PendingPackageBroadcasts { 851 // for each user id, a map of <package name -> components within that package> 852 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 853 854 public PendingPackageBroadcasts() { 855 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 856 } 857 858 public ArrayList<String> get(int userId, String packageName) { 859 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 860 return packages.get(packageName); 861 } 862 863 public void put(int userId, String packageName, ArrayList<String> components) { 864 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 865 packages.put(packageName, components); 866 } 867 868 public void remove(int userId, String packageName) { 869 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 870 if (packages != null) { 871 packages.remove(packageName); 872 } 873 } 874 875 public void remove(int userId) { 876 mUidMap.remove(userId); 877 } 878 879 public int userIdCount() { 880 return mUidMap.size(); 881 } 882 883 public int userIdAt(int n) { 884 return mUidMap.keyAt(n); 885 } 886 887 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 888 return mUidMap.get(userId); 889 } 890 891 public int size() { 892 // total number of pending broadcast entries across all userIds 893 int num = 0; 894 for (int i = 0; i< mUidMap.size(); i++) { 895 num += mUidMap.valueAt(i).size(); 896 } 897 return num; 898 } 899 900 public void clear() { 901 mUidMap.clear(); 902 } 903 904 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 905 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 906 if (map == null) { 907 map = new ArrayMap<String, ArrayList<String>>(); 908 mUidMap.put(userId, map); 909 } 910 return map; 911 } 912 } 913 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 914 915 // Service Connection to remote media container service to copy 916 // package uri's from external media onto secure containers 917 // or internal storage. 918 private IMediaContainerService mContainerService = null; 919 920 static final int SEND_PENDING_BROADCAST = 1; 921 static final int MCS_BOUND = 3; 922 static final int END_COPY = 4; 923 static final int INIT_COPY = 5; 924 static final int MCS_UNBIND = 6; 925 static final int START_CLEANING_PACKAGE = 7; 926 static final int FIND_INSTALL_LOC = 8; 927 static final int POST_INSTALL = 9; 928 static final int MCS_RECONNECT = 10; 929 static final int MCS_GIVE_UP = 11; 930 static final int UPDATED_MEDIA_STATUS = 12; 931 static final int WRITE_SETTINGS = 13; 932 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 933 static final int PACKAGE_VERIFIED = 15; 934 static final int CHECK_PENDING_VERIFICATION = 16; 935 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 936 static final int INTENT_FILTER_VERIFIED = 18; 937 938 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 939 940 // Delay time in millisecs 941 static final int BROADCAST_DELAY = 10 * 1000; 942 943 static UserManagerService sUserManager; 944 945 // Stores a list of users whose package restrictions file needs to be updated 946 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 947 948 final private DefaultContainerConnection mDefContainerConn = 949 new DefaultContainerConnection(); 950 class DefaultContainerConnection implements ServiceConnection { 951 public void onServiceConnected(ComponentName name, IBinder service) { 952 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 953 IMediaContainerService imcs = 954 IMediaContainerService.Stub.asInterface(service); 955 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 956 } 957 958 public void onServiceDisconnected(ComponentName name) { 959 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 960 } 961 } 962 963 // Recordkeeping of restore-after-install operations that are currently in flight 964 // between the Package Manager and the Backup Manager 965 static class PostInstallData { 966 public InstallArgs args; 967 public PackageInstalledInfo res; 968 969 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 970 args = _a; 971 res = _r; 972 } 973 } 974 975 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 976 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 977 978 // XML tags for backup/restore of various bits of state 979 private static final String TAG_PREFERRED_BACKUP = "pa"; 980 private static final String TAG_DEFAULT_APPS = "da"; 981 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 982 983 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 984 private static final String TAG_ALL_GRANTS = "rt-grants"; 985 private static final String TAG_GRANT = "grant"; 986 private static final String ATTR_PACKAGE_NAME = "pkg"; 987 988 private static final String TAG_PERMISSION = "perm"; 989 private static final String ATTR_PERMISSION_NAME = "name"; 990 private static final String ATTR_IS_GRANTED = "g"; 991 private static final String ATTR_USER_SET = "set"; 992 private static final String ATTR_USER_FIXED = "fixed"; 993 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 994 995 // System/policy permission grants are not backed up 996 private static final int SYSTEM_RUNTIME_GRANT_MASK = 997 FLAG_PERMISSION_POLICY_FIXED 998 | FLAG_PERMISSION_SYSTEM_FIXED 999 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1000 1001 // And we back up these user-adjusted states 1002 private static final int USER_RUNTIME_GRANT_MASK = 1003 FLAG_PERMISSION_USER_SET 1004 | FLAG_PERMISSION_USER_FIXED 1005 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1006 1007 final @Nullable String mRequiredVerifierPackage; 1008 final @Nullable String mRequiredInstallerPackage; 1009 1010 private final PackageUsage mPackageUsage = new PackageUsage(); 1011 1012 private class PackageUsage { 1013 private static final int WRITE_INTERVAL 1014 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1015 1016 private final Object mFileLock = new Object(); 1017 private final AtomicLong mLastWritten = new AtomicLong(0); 1018 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1019 1020 private boolean mIsHistoricalPackageUsageAvailable = true; 1021 1022 boolean isHistoricalPackageUsageAvailable() { 1023 return mIsHistoricalPackageUsageAvailable; 1024 } 1025 1026 void write(boolean force) { 1027 if (force) { 1028 writeInternal(); 1029 return; 1030 } 1031 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1032 && !DEBUG_DEXOPT) { 1033 return; 1034 } 1035 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1036 new Thread("PackageUsage_DiskWriter") { 1037 @Override 1038 public void run() { 1039 try { 1040 writeInternal(); 1041 } finally { 1042 mBackgroundWriteRunning.set(false); 1043 } 1044 } 1045 }.start(); 1046 } 1047 } 1048 1049 private void writeInternal() { 1050 synchronized (mPackages) { 1051 synchronized (mFileLock) { 1052 AtomicFile file = getFile(); 1053 FileOutputStream f = null; 1054 try { 1055 f = file.startWrite(); 1056 BufferedOutputStream out = new BufferedOutputStream(f); 1057 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1058 StringBuilder sb = new StringBuilder(); 1059 for (PackageParser.Package pkg : mPackages.values()) { 1060 if (pkg.mLastPackageUsageTimeInMills == 0) { 1061 continue; 1062 } 1063 sb.setLength(0); 1064 sb.append(pkg.packageName); 1065 sb.append(' '); 1066 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1067 sb.append('\n'); 1068 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1069 } 1070 out.flush(); 1071 file.finishWrite(f); 1072 } catch (IOException e) { 1073 if (f != null) { 1074 file.failWrite(f); 1075 } 1076 Log.e(TAG, "Failed to write package usage times", e); 1077 } 1078 } 1079 } 1080 mLastWritten.set(SystemClock.elapsedRealtime()); 1081 } 1082 1083 void readLP() { 1084 synchronized (mFileLock) { 1085 AtomicFile file = getFile(); 1086 BufferedInputStream in = null; 1087 try { 1088 in = new BufferedInputStream(file.openRead()); 1089 StringBuffer sb = new StringBuffer(); 1090 while (true) { 1091 String packageName = readToken(in, sb, ' '); 1092 if (packageName == null) { 1093 break; 1094 } 1095 String timeInMillisString = readToken(in, sb, '\n'); 1096 if (timeInMillisString == null) { 1097 throw new IOException("Failed to find last usage time for package " 1098 + packageName); 1099 } 1100 PackageParser.Package pkg = mPackages.get(packageName); 1101 if (pkg == null) { 1102 continue; 1103 } 1104 long timeInMillis; 1105 try { 1106 timeInMillis = Long.parseLong(timeInMillisString); 1107 } catch (NumberFormatException e) { 1108 throw new IOException("Failed to parse " + timeInMillisString 1109 + " as a long.", e); 1110 } 1111 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1112 } 1113 } catch (FileNotFoundException expected) { 1114 mIsHistoricalPackageUsageAvailable = false; 1115 } catch (IOException e) { 1116 Log.w(TAG, "Failed to read package usage times", e); 1117 } finally { 1118 IoUtils.closeQuietly(in); 1119 } 1120 } 1121 mLastWritten.set(SystemClock.elapsedRealtime()); 1122 } 1123 1124 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1125 throws IOException { 1126 sb.setLength(0); 1127 while (true) { 1128 int ch = in.read(); 1129 if (ch == -1) { 1130 if (sb.length() == 0) { 1131 return null; 1132 } 1133 throw new IOException("Unexpected EOF"); 1134 } 1135 if (ch == endOfToken) { 1136 return sb.toString(); 1137 } 1138 sb.append((char)ch); 1139 } 1140 } 1141 1142 private AtomicFile getFile() { 1143 File dataDir = Environment.getDataDirectory(); 1144 File systemDir = new File(dataDir, "system"); 1145 File fname = new File(systemDir, "package-usage.list"); 1146 return new AtomicFile(fname); 1147 } 1148 } 1149 1150 class PackageHandler extends Handler { 1151 private boolean mBound = false; 1152 final ArrayList<HandlerParams> mPendingInstalls = 1153 new ArrayList<HandlerParams>(); 1154 1155 private boolean connectToService() { 1156 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1157 " DefaultContainerService"); 1158 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1159 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1160 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1161 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1162 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1163 mBound = true; 1164 return true; 1165 } 1166 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1167 return false; 1168 } 1169 1170 private void disconnectService() { 1171 mContainerService = null; 1172 mBound = false; 1173 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1174 mContext.unbindService(mDefContainerConn); 1175 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1176 } 1177 1178 PackageHandler(Looper looper) { 1179 super(looper); 1180 } 1181 1182 public void handleMessage(Message msg) { 1183 try { 1184 doHandleMessage(msg); 1185 } finally { 1186 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1187 } 1188 } 1189 1190 void doHandleMessage(Message msg) { 1191 switch (msg.what) { 1192 case INIT_COPY: { 1193 HandlerParams params = (HandlerParams) msg.obj; 1194 int idx = mPendingInstalls.size(); 1195 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1196 // If a bind was already initiated we dont really 1197 // need to do anything. The pending install 1198 // will be processed later on. 1199 if (!mBound) { 1200 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1201 System.identityHashCode(mHandler)); 1202 // If this is the only one pending we might 1203 // have to bind to the service again. 1204 if (!connectToService()) { 1205 Slog.e(TAG, "Failed to bind to media container service"); 1206 params.serviceError(); 1207 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1208 System.identityHashCode(mHandler)); 1209 if (params.traceMethod != null) { 1210 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1211 params.traceCookie); 1212 } 1213 return; 1214 } else { 1215 // Once we bind to the service, the first 1216 // pending request will be processed. 1217 mPendingInstalls.add(idx, params); 1218 } 1219 } else { 1220 mPendingInstalls.add(idx, params); 1221 // Already bound to the service. Just make 1222 // sure we trigger off processing the first request. 1223 if (idx == 0) { 1224 mHandler.sendEmptyMessage(MCS_BOUND); 1225 } 1226 } 1227 break; 1228 } 1229 case MCS_BOUND: { 1230 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1231 if (msg.obj != null) { 1232 mContainerService = (IMediaContainerService) msg.obj; 1233 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1234 System.identityHashCode(mHandler)); 1235 } 1236 if (mContainerService == null) { 1237 if (!mBound) { 1238 // Something seriously wrong since we are not bound and we are not 1239 // waiting for connection. Bail out. 1240 Slog.e(TAG, "Cannot bind to media container service"); 1241 for (HandlerParams params : mPendingInstalls) { 1242 // Indicate service bind error 1243 params.serviceError(); 1244 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1245 System.identityHashCode(params)); 1246 if (params.traceMethod != null) { 1247 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1248 params.traceMethod, params.traceCookie); 1249 } 1250 return; 1251 } 1252 mPendingInstalls.clear(); 1253 } else { 1254 Slog.w(TAG, "Waiting to connect to media container service"); 1255 } 1256 } else if (mPendingInstalls.size() > 0) { 1257 HandlerParams params = mPendingInstalls.get(0); 1258 if (params != null) { 1259 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1260 System.identityHashCode(params)); 1261 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1262 if (params.startCopy()) { 1263 // We are done... look for more work or to 1264 // go idle. 1265 if (DEBUG_SD_INSTALL) Log.i(TAG, 1266 "Checking for more work or unbind..."); 1267 // Delete pending install 1268 if (mPendingInstalls.size() > 0) { 1269 mPendingInstalls.remove(0); 1270 } 1271 if (mPendingInstalls.size() == 0) { 1272 if (mBound) { 1273 if (DEBUG_SD_INSTALL) Log.i(TAG, 1274 "Posting delayed MCS_UNBIND"); 1275 removeMessages(MCS_UNBIND); 1276 Message ubmsg = obtainMessage(MCS_UNBIND); 1277 // Unbind after a little delay, to avoid 1278 // continual thrashing. 1279 sendMessageDelayed(ubmsg, 10000); 1280 } 1281 } else { 1282 // There are more pending requests in queue. 1283 // Just post MCS_BOUND message to trigger processing 1284 // of next pending install. 1285 if (DEBUG_SD_INSTALL) Log.i(TAG, 1286 "Posting MCS_BOUND for next work"); 1287 mHandler.sendEmptyMessage(MCS_BOUND); 1288 } 1289 } 1290 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1291 } 1292 } else { 1293 // Should never happen ideally. 1294 Slog.w(TAG, "Empty queue"); 1295 } 1296 break; 1297 } 1298 case MCS_RECONNECT: { 1299 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1300 if (mPendingInstalls.size() > 0) { 1301 if (mBound) { 1302 disconnectService(); 1303 } 1304 if (!connectToService()) { 1305 Slog.e(TAG, "Failed to bind to media container service"); 1306 for (HandlerParams params : mPendingInstalls) { 1307 // Indicate service bind error 1308 params.serviceError(); 1309 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1310 System.identityHashCode(params)); 1311 } 1312 mPendingInstalls.clear(); 1313 } 1314 } 1315 break; 1316 } 1317 case MCS_UNBIND: { 1318 // If there is no actual work left, then time to unbind. 1319 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1320 1321 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1322 if (mBound) { 1323 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1324 1325 disconnectService(); 1326 } 1327 } else if (mPendingInstalls.size() > 0) { 1328 // There are more pending requests in queue. 1329 // Just post MCS_BOUND message to trigger processing 1330 // of next pending install. 1331 mHandler.sendEmptyMessage(MCS_BOUND); 1332 } 1333 1334 break; 1335 } 1336 case MCS_GIVE_UP: { 1337 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1338 HandlerParams params = mPendingInstalls.remove(0); 1339 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1340 System.identityHashCode(params)); 1341 break; 1342 } 1343 case SEND_PENDING_BROADCAST: { 1344 String packages[]; 1345 ArrayList<String> components[]; 1346 int size = 0; 1347 int uids[]; 1348 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1349 synchronized (mPackages) { 1350 if (mPendingBroadcasts == null) { 1351 return; 1352 } 1353 size = mPendingBroadcasts.size(); 1354 if (size <= 0) { 1355 // Nothing to be done. Just return 1356 return; 1357 } 1358 packages = new String[size]; 1359 components = new ArrayList[size]; 1360 uids = new int[size]; 1361 int i = 0; // filling out the above arrays 1362 1363 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1364 int packageUserId = mPendingBroadcasts.userIdAt(n); 1365 Iterator<Map.Entry<String, ArrayList<String>>> it 1366 = mPendingBroadcasts.packagesForUserId(packageUserId) 1367 .entrySet().iterator(); 1368 while (it.hasNext() && i < size) { 1369 Map.Entry<String, ArrayList<String>> ent = it.next(); 1370 packages[i] = ent.getKey(); 1371 components[i] = ent.getValue(); 1372 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1373 uids[i] = (ps != null) 1374 ? UserHandle.getUid(packageUserId, ps.appId) 1375 : -1; 1376 i++; 1377 } 1378 } 1379 size = i; 1380 mPendingBroadcasts.clear(); 1381 } 1382 // Send broadcasts 1383 for (int i = 0; i < size; i++) { 1384 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1385 } 1386 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1387 break; 1388 } 1389 case START_CLEANING_PACKAGE: { 1390 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1391 final String packageName = (String)msg.obj; 1392 final int userId = msg.arg1; 1393 final boolean andCode = msg.arg2 != 0; 1394 synchronized (mPackages) { 1395 if (userId == UserHandle.USER_ALL) { 1396 int[] users = sUserManager.getUserIds(); 1397 for (int user : users) { 1398 mSettings.addPackageToCleanLPw( 1399 new PackageCleanItem(user, packageName, andCode)); 1400 } 1401 } else { 1402 mSettings.addPackageToCleanLPw( 1403 new PackageCleanItem(userId, packageName, andCode)); 1404 } 1405 } 1406 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1407 startCleaningPackages(); 1408 } break; 1409 case POST_INSTALL: { 1410 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1411 1412 PostInstallData data = mRunningInstalls.get(msg.arg1); 1413 mRunningInstalls.delete(msg.arg1); 1414 boolean deleteOld = false; 1415 1416 if (data != null) { 1417 InstallArgs args = data.args; 1418 PackageInstalledInfo res = data.res; 1419 1420 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1421 final String packageName = res.pkg.applicationInfo.packageName; 1422 res.removedInfo.sendBroadcast(false, true, false); 1423 Bundle extras = new Bundle(1); 1424 extras.putInt(Intent.EXTRA_UID, res.uid); 1425 1426 // Now that we successfully installed the package, grant runtime 1427 // permissions if requested before broadcasting the install. 1428 if ((args.installFlags 1429 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 1430 && res.pkg.applicationInfo.targetSdkVersion 1431 >= Build.VERSION_CODES.M) { 1432 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1433 args.installGrantPermissions); 1434 } 1435 1436 synchronized (mPackages) { 1437 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1438 } 1439 1440 // Determine the set of users who are adding this 1441 // package for the first time vs. those who are seeing 1442 // an update. 1443 int[] firstUsers; 1444 int[] updateUsers = new int[0]; 1445 if (res.origUsers == null || res.origUsers.length == 0) { 1446 firstUsers = res.newUsers; 1447 } else { 1448 firstUsers = new int[0]; 1449 for (int i=0; i<res.newUsers.length; i++) { 1450 int user = res.newUsers[i]; 1451 boolean isNew = true; 1452 for (int j=0; j<res.origUsers.length; j++) { 1453 if (res.origUsers[j] == user) { 1454 isNew = false; 1455 break; 1456 } 1457 } 1458 if (isNew) { 1459 int[] newFirst = new int[firstUsers.length+1]; 1460 System.arraycopy(firstUsers, 0, newFirst, 0, 1461 firstUsers.length); 1462 newFirst[firstUsers.length] = user; 1463 firstUsers = newFirst; 1464 } else { 1465 int[] newUpdate = new int[updateUsers.length+1]; 1466 System.arraycopy(updateUsers, 0, newUpdate, 0, 1467 updateUsers.length); 1468 newUpdate[updateUsers.length] = user; 1469 updateUsers = newUpdate; 1470 } 1471 } 1472 } 1473 // don't broadcast for ephemeral installs/updates 1474 final boolean isEphemeral = isEphemeral(res.pkg); 1475 if (!isEphemeral) { 1476 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1477 extras, 0 /*flags*/, null /*targetPackage*/, 1478 null /*finishedReceiver*/, firstUsers); 1479 } 1480 final boolean update = res.removedInfo.removedPackage != null; 1481 if (update) { 1482 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1483 } 1484 if (!isEphemeral) { 1485 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1486 extras, 0 /*flags*/, null /*targetPackage*/, 1487 null /*finishedReceiver*/, updateUsers); 1488 } 1489 if (update) { 1490 if (!isEphemeral) { 1491 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1492 packageName, extras, 0 /*flags*/, 1493 null /*targetPackage*/, null /*finishedReceiver*/, 1494 updateUsers); 1495 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1496 null /*package*/, null /*extras*/, 0 /*flags*/, 1497 packageName /*targetPackage*/, 1498 null /*finishedReceiver*/, updateUsers); 1499 } 1500 1501 // treat asec-hosted packages like removable media on upgrade 1502 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1503 if (DEBUG_INSTALL) { 1504 Slog.i(TAG, "upgrading pkg " + res.pkg 1505 + " is ASEC-hosted -> AVAILABLE"); 1506 } 1507 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1508 ArrayList<String> pkgList = new ArrayList<String>(1); 1509 pkgList.add(packageName); 1510 sendResourcesChangedBroadcast(true, true, 1511 pkgList,uidArray, null); 1512 } 1513 } 1514 if (res.removedInfo.args != null) { 1515 // Remove the replaced package's older resources safely now 1516 deleteOld = true; 1517 } 1518 1519 1520 // Work that needs to happen on first install within each user 1521 if (firstUsers.length > 0) { 1522 for (int userId : firstUsers) { 1523 synchronized (mPackages) { 1524 // If this app is a browser and it's newly-installed for 1525 // some users, clear any default-browser state in those 1526 // users. The app's nature doesn't depend on the user, 1527 // so we can just check its browser nature in any user 1528 // and generalize. 1529 if (packageIsBrowser(packageName, firstUsers[0])) { 1530 mSettings.setDefaultBrowserPackageNameLPw( 1531 null, userId); 1532 } 1533 1534 // We may also need to apply pending (restored) runtime 1535 // permission grants within these users. 1536 mSettings.applyPendingPermissionGrantsLPw( 1537 packageName, userId); 1538 } 1539 } 1540 } 1541 // Log current value of "unknown sources" setting 1542 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1543 getUnknownSourcesSettings()); 1544 } 1545 // Force a gc to clear up things 1546 Runtime.getRuntime().gc(); 1547 // We delete after a gc for applications on sdcard. 1548 if (deleteOld) { 1549 synchronized (mInstallLock) { 1550 res.removedInfo.args.doPostDeleteLI(true); 1551 } 1552 } 1553 if (args.observer != null) { 1554 try { 1555 Bundle extras = extrasForInstallResult(res); 1556 args.observer.onPackageInstalled(res.name, res.returnCode, 1557 res.returnMsg, extras); 1558 } catch (RemoteException e) { 1559 Slog.i(TAG, "Observer no longer exists."); 1560 } 1561 } 1562 if (args.traceMethod != null) { 1563 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1564 args.traceCookie); 1565 } 1566 return; 1567 } else { 1568 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1569 } 1570 1571 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1572 } break; 1573 case UPDATED_MEDIA_STATUS: { 1574 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1575 boolean reportStatus = msg.arg1 == 1; 1576 boolean doGc = msg.arg2 == 1; 1577 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1578 if (doGc) { 1579 // Force a gc to clear up stale containers. 1580 Runtime.getRuntime().gc(); 1581 } 1582 if (msg.obj != null) { 1583 @SuppressWarnings("unchecked") 1584 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1585 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1586 // Unload containers 1587 unloadAllContainers(args); 1588 } 1589 if (reportStatus) { 1590 try { 1591 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1592 PackageHelper.getMountService().finishMediaUpdate(); 1593 } catch (RemoteException e) { 1594 Log.e(TAG, "MountService not running?"); 1595 } 1596 } 1597 } break; 1598 case WRITE_SETTINGS: { 1599 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1600 synchronized (mPackages) { 1601 removeMessages(WRITE_SETTINGS); 1602 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1603 mSettings.writeLPr(); 1604 mDirtyUsers.clear(); 1605 } 1606 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1607 } break; 1608 case WRITE_PACKAGE_RESTRICTIONS: { 1609 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1610 synchronized (mPackages) { 1611 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1612 for (int userId : mDirtyUsers) { 1613 mSettings.writePackageRestrictionsLPr(userId); 1614 } 1615 mDirtyUsers.clear(); 1616 } 1617 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1618 } break; 1619 case CHECK_PENDING_VERIFICATION: { 1620 final int verificationId = msg.arg1; 1621 final PackageVerificationState state = mPendingVerification.get(verificationId); 1622 1623 if ((state != null) && !state.timeoutExtended()) { 1624 final InstallArgs args = state.getInstallArgs(); 1625 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1626 1627 Slog.i(TAG, "Verification timed out for " + originUri); 1628 mPendingVerification.remove(verificationId); 1629 1630 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1631 1632 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1633 Slog.i(TAG, "Continuing with installation of " + originUri); 1634 state.setVerifierResponse(Binder.getCallingUid(), 1635 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1636 broadcastPackageVerified(verificationId, originUri, 1637 PackageManager.VERIFICATION_ALLOW, 1638 state.getInstallArgs().getUser()); 1639 try { 1640 ret = args.copyApk(mContainerService, true); 1641 } catch (RemoteException e) { 1642 Slog.e(TAG, "Could not contact the ContainerService"); 1643 } 1644 } else { 1645 broadcastPackageVerified(verificationId, originUri, 1646 PackageManager.VERIFICATION_REJECT, 1647 state.getInstallArgs().getUser()); 1648 } 1649 1650 Trace.asyncTraceEnd( 1651 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1652 1653 processPendingInstall(args, ret); 1654 mHandler.sendEmptyMessage(MCS_UNBIND); 1655 } 1656 break; 1657 } 1658 case PACKAGE_VERIFIED: { 1659 final int verificationId = msg.arg1; 1660 1661 final PackageVerificationState state = mPendingVerification.get(verificationId); 1662 if (state == null) { 1663 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1664 break; 1665 } 1666 1667 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1668 1669 state.setVerifierResponse(response.callerUid, response.code); 1670 1671 if (state.isVerificationComplete()) { 1672 mPendingVerification.remove(verificationId); 1673 1674 final InstallArgs args = state.getInstallArgs(); 1675 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1676 1677 int ret; 1678 if (state.isInstallAllowed()) { 1679 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1680 broadcastPackageVerified(verificationId, originUri, 1681 response.code, state.getInstallArgs().getUser()); 1682 try { 1683 ret = args.copyApk(mContainerService, true); 1684 } catch (RemoteException e) { 1685 Slog.e(TAG, "Could not contact the ContainerService"); 1686 } 1687 } else { 1688 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1689 } 1690 1691 Trace.asyncTraceEnd( 1692 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1693 1694 processPendingInstall(args, ret); 1695 mHandler.sendEmptyMessage(MCS_UNBIND); 1696 } 1697 1698 break; 1699 } 1700 case START_INTENT_FILTER_VERIFICATIONS: { 1701 IFVerificationParams params = (IFVerificationParams) msg.obj; 1702 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1703 params.replacing, params.pkg); 1704 break; 1705 } 1706 case INTENT_FILTER_VERIFIED: { 1707 final int verificationId = msg.arg1; 1708 1709 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1710 verificationId); 1711 if (state == null) { 1712 Slog.w(TAG, "Invalid IntentFilter verification token " 1713 + verificationId + " received"); 1714 break; 1715 } 1716 1717 final int userId = state.getUserId(); 1718 1719 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1720 "Processing IntentFilter verification with token:" 1721 + verificationId + " and userId:" + userId); 1722 1723 final IntentFilterVerificationResponse response = 1724 (IntentFilterVerificationResponse) msg.obj; 1725 1726 state.setVerifierResponse(response.callerUid, response.code); 1727 1728 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1729 "IntentFilter verification with token:" + verificationId 1730 + " and userId:" + userId 1731 + " is settings verifier response with response code:" 1732 + response.code); 1733 1734 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1735 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1736 + response.getFailedDomainsString()); 1737 } 1738 1739 if (state.isVerificationComplete()) { 1740 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1741 } else { 1742 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1743 "IntentFilter verification with token:" + verificationId 1744 + " was not said to be complete"); 1745 } 1746 1747 break; 1748 } 1749 } 1750 } 1751 } 1752 1753 private StorageEventListener mStorageListener = new StorageEventListener() { 1754 @Override 1755 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1756 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1757 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1758 final String volumeUuid = vol.getFsUuid(); 1759 1760 // Clean up any users or apps that were removed or recreated 1761 // while this volume was missing 1762 reconcileUsers(volumeUuid); 1763 reconcileApps(volumeUuid); 1764 1765 // Clean up any install sessions that expired or were 1766 // cancelled while this volume was missing 1767 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1768 1769 loadPrivatePackages(vol); 1770 1771 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1772 unloadPrivatePackages(vol); 1773 } 1774 } 1775 1776 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1777 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1778 updateExternalMediaStatus(true, false); 1779 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1780 updateExternalMediaStatus(false, false); 1781 } 1782 } 1783 } 1784 1785 @Override 1786 public void onVolumeForgotten(String fsUuid) { 1787 if (TextUtils.isEmpty(fsUuid)) { 1788 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1789 return; 1790 } 1791 1792 // Remove any apps installed on the forgotten volume 1793 synchronized (mPackages) { 1794 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1795 for (PackageSetting ps : packages) { 1796 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1797 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1798 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1799 } 1800 1801 mSettings.onVolumeForgotten(fsUuid); 1802 mSettings.writeLPr(); 1803 } 1804 } 1805 }; 1806 1807 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1808 String[] grantedPermissions) { 1809 if (userId >= UserHandle.USER_SYSTEM) { 1810 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1811 } else if (userId == UserHandle.USER_ALL) { 1812 final int[] userIds; 1813 synchronized (mPackages) { 1814 userIds = UserManagerService.getInstance().getUserIds(); 1815 } 1816 for (int someUserId : userIds) { 1817 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1818 } 1819 } 1820 1821 // We could have touched GID membership, so flush out packages.list 1822 synchronized (mPackages) { 1823 mSettings.writePackageListLPr(); 1824 } 1825 } 1826 1827 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1828 String[] grantedPermissions) { 1829 SettingBase sb = (SettingBase) pkg.mExtras; 1830 if (sb == null) { 1831 return; 1832 } 1833 1834 PermissionsState permissionsState = sb.getPermissionsState(); 1835 1836 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1837 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1838 1839 synchronized (mPackages) { 1840 for (String permission : pkg.requestedPermissions) { 1841 BasePermission bp = mSettings.mPermissions.get(permission); 1842 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1843 && (grantedPermissions == null 1844 || ArrayUtils.contains(grantedPermissions, permission))) { 1845 final int flags = permissionsState.getPermissionFlags(permission, userId); 1846 // Installer cannot change immutable permissions. 1847 if ((flags & immutableFlags) == 0) { 1848 grantRuntimePermission(pkg.packageName, permission, userId); 1849 } 1850 } 1851 } 1852 } 1853 } 1854 1855 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1856 Bundle extras = null; 1857 switch (res.returnCode) { 1858 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1859 extras = new Bundle(); 1860 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1861 res.origPermission); 1862 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1863 res.origPackage); 1864 break; 1865 } 1866 case PackageManager.INSTALL_SUCCEEDED: { 1867 extras = new Bundle(); 1868 extras.putBoolean(Intent.EXTRA_REPLACING, 1869 res.removedInfo != null && res.removedInfo.removedPackage != null); 1870 break; 1871 } 1872 } 1873 return extras; 1874 } 1875 1876 void scheduleWriteSettingsLocked() { 1877 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1878 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1879 } 1880 } 1881 1882 void scheduleWritePackageRestrictionsLocked(int userId) { 1883 if (!sUserManager.exists(userId)) return; 1884 mDirtyUsers.add(userId); 1885 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1886 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1887 } 1888 } 1889 1890 public static PackageManagerService main(Context context, Installer installer, 1891 boolean factoryTest, boolean onlyCore) { 1892 PackageManagerService m = new PackageManagerService(context, installer, 1893 factoryTest, onlyCore); 1894 m.enableSystemUserPackages(); 1895 ServiceManager.addService("package", m); 1896 return m; 1897 } 1898 1899 private void enableSystemUserPackages() { 1900 if (!UserManager.isSplitSystemUser()) { 1901 return; 1902 } 1903 // For system user, enable apps based on the following conditions: 1904 // - app is whitelisted or belong to one of these groups: 1905 // -- system app which has no launcher icons 1906 // -- system app which has INTERACT_ACROSS_USERS permission 1907 // -- system IME app 1908 // - app is not in the blacklist 1909 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 1910 Set<String> enableApps = new ArraySet<>(); 1911 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 1912 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 1913 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 1914 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 1915 enableApps.addAll(wlApps); 1916 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 1917 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 1918 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 1919 enableApps.removeAll(blApps); 1920 Log.i(TAG, "Applications installed for system user: " + enableApps); 1921 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 1922 UserHandle.SYSTEM); 1923 final int allAppsSize = allAps.size(); 1924 synchronized (mPackages) { 1925 for (int i = 0; i < allAppsSize; i++) { 1926 String pName = allAps.get(i); 1927 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 1928 // Should not happen, but we shouldn't be failing if it does 1929 if (pkgSetting == null) { 1930 continue; 1931 } 1932 boolean install = enableApps.contains(pName); 1933 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 1934 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 1935 + " for system user"); 1936 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 1937 } 1938 } 1939 } 1940 } 1941 1942 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1943 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1944 Context.DISPLAY_SERVICE); 1945 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1946 } 1947 1948 public PackageManagerService(Context context, Installer installer, 1949 boolean factoryTest, boolean onlyCore) { 1950 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1951 SystemClock.uptimeMillis()); 1952 1953 if (mSdkVersion <= 0) { 1954 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1955 } 1956 1957 mContext = context; 1958 mFactoryTest = factoryTest; 1959 mOnlyCore = onlyCore; 1960 mMetrics = new DisplayMetrics(); 1961 mSettings = new Settings(mPackages); 1962 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1963 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1964 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1965 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1966 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1967 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1968 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1969 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1970 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1971 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1972 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1973 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1974 1975 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1976 if (separateProcesses != null && separateProcesses.length() > 0) { 1977 if ("*".equals(separateProcesses)) { 1978 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1979 mSeparateProcesses = null; 1980 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1981 } else { 1982 mDefParseFlags = 0; 1983 mSeparateProcesses = separateProcesses.split(","); 1984 Slog.w(TAG, "Running with debug.separate_processes: " 1985 + separateProcesses); 1986 } 1987 } else { 1988 mDefParseFlags = 0; 1989 mSeparateProcesses = null; 1990 } 1991 1992 mInstaller = installer; 1993 mPackageDexOptimizer = new PackageDexOptimizer(this); 1994 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1995 1996 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1997 FgThread.get().getLooper()); 1998 1999 getDefaultDisplayMetrics(context, mMetrics); 2000 2001 SystemConfig systemConfig = SystemConfig.getInstance(); 2002 mGlobalGids = systemConfig.getGlobalGids(); 2003 mSystemPermissions = systemConfig.getSystemPermissions(); 2004 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2005 2006 synchronized (mInstallLock) { 2007 // writer 2008 synchronized (mPackages) { 2009 mHandlerThread = new ServiceThread(TAG, 2010 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2011 mHandlerThread.start(); 2012 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2013 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2014 2015 File dataDir = Environment.getDataDirectory(); 2016 mAppInstallDir = new File(dataDir, "app"); 2017 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2018 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2019 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2020 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2021 2022 sUserManager = new UserManagerService(context, this, mPackages); 2023 2024 // Propagate permission configuration in to package manager. 2025 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2026 = systemConfig.getPermissions(); 2027 for (int i=0; i<permConfig.size(); i++) { 2028 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2029 BasePermission bp = mSettings.mPermissions.get(perm.name); 2030 if (bp == null) { 2031 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2032 mSettings.mPermissions.put(perm.name, bp); 2033 } 2034 if (perm.gids != null) { 2035 bp.setGids(perm.gids, perm.perUser); 2036 } 2037 } 2038 2039 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2040 for (int i=0; i<libConfig.size(); i++) { 2041 mSharedLibraries.put(libConfig.keyAt(i), 2042 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2043 } 2044 2045 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2046 2047 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2048 2049 String customResolverActivity = Resources.getSystem().getString( 2050 R.string.config_customResolverActivity); 2051 if (TextUtils.isEmpty(customResolverActivity)) { 2052 customResolverActivity = null; 2053 } else { 2054 mCustomResolverComponentName = ComponentName.unflattenFromString( 2055 customResolverActivity); 2056 } 2057 2058 long startTime = SystemClock.uptimeMillis(); 2059 2060 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2061 startTime); 2062 2063 // Set flag to monitor and not change apk file paths when 2064 // scanning install directories. 2065 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2066 2067 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2068 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2069 2070 if (bootClassPath == null) { 2071 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2072 } 2073 2074 if (systemServerClassPath == null) { 2075 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2076 } 2077 2078 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2079 final String[] dexCodeInstructionSets = 2080 getDexCodeInstructionSets( 2081 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2082 2083 /** 2084 * Ensure all external libraries have had dexopt run on them. 2085 */ 2086 if (mSharedLibraries.size() > 0) { 2087 // NOTE: For now, we're compiling these system "shared libraries" 2088 // (and framework jars) into all available architectures. It's possible 2089 // to compile them only when we come across an app that uses them (there's 2090 // already logic for that in scanPackageLI) but that adds some complexity. 2091 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2092 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2093 final String lib = libEntry.path; 2094 if (lib == null) { 2095 continue; 2096 } 2097 2098 try { 2099 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 2100 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2101 // Shared libraries do not have profiles so we perform a full 2102 // AOT compilation. 2103 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2104 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2105 StorageManager.UUID_PRIVATE_INTERNAL, 2106 false /*useProfiles*/); 2107 } 2108 } catch (FileNotFoundException e) { 2109 Slog.w(TAG, "Library not found: " + lib); 2110 } catch (IOException | InstallerException e) { 2111 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2112 + e.getMessage()); 2113 } 2114 } 2115 } 2116 } 2117 2118 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2119 2120 final VersionInfo ver = mSettings.getInternalVersion(); 2121 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2122 // when upgrading from pre-M, promote system app permissions from install to runtime 2123 mPromoteSystemApps = 2124 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2125 2126 // save off the names of pre-existing system packages prior to scanning; we don't 2127 // want to automatically grant runtime permissions for new system apps 2128 if (mPromoteSystemApps) { 2129 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2130 while (pkgSettingIter.hasNext()) { 2131 PackageSetting ps = pkgSettingIter.next(); 2132 if (isSystemApp(ps)) { 2133 mExistingSystemPackages.add(ps.name); 2134 } 2135 } 2136 } 2137 2138 // Collect vendor overlay packages. 2139 // (Do this before scanning any apps.) 2140 // For security and version matching reason, only consider 2141 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2142 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2143 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2144 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2145 2146 // Find base frameworks (resource packages without code). 2147 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2148 | PackageParser.PARSE_IS_SYSTEM_DIR 2149 | PackageParser.PARSE_IS_PRIVILEGED, 2150 scanFlags | SCAN_NO_DEX, 0); 2151 2152 // Collected privileged system packages. 2153 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2154 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2155 | PackageParser.PARSE_IS_SYSTEM_DIR 2156 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2157 2158 // Collect ordinary system packages. 2159 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2160 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2161 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2162 2163 // Collect all vendor packages. 2164 File vendorAppDir = new File("/vendor/app"); 2165 try { 2166 vendorAppDir = vendorAppDir.getCanonicalFile(); 2167 } catch (IOException e) { 2168 // failed to look up canonical path, continue with original one 2169 } 2170 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2171 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2172 2173 // Collect all OEM packages. 2174 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2175 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2176 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2177 2178 // Prune any system packages that no longer exist. 2179 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2180 if (!mOnlyCore) { 2181 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2182 while (psit.hasNext()) { 2183 PackageSetting ps = psit.next(); 2184 2185 /* 2186 * If this is not a system app, it can't be a 2187 * disable system app. 2188 */ 2189 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2190 continue; 2191 } 2192 2193 /* 2194 * If the package is scanned, it's not erased. 2195 */ 2196 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2197 if (scannedPkg != null) { 2198 /* 2199 * If the system app is both scanned and in the 2200 * disabled packages list, then it must have been 2201 * added via OTA. Remove it from the currently 2202 * scanned package so the previously user-installed 2203 * application can be scanned. 2204 */ 2205 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2206 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2207 + ps.name + "; removing system app. Last known codePath=" 2208 + ps.codePathString + ", installStatus=" + ps.installStatus 2209 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2210 + scannedPkg.mVersionCode); 2211 removePackageLI(ps, true); 2212 mExpectingBetter.put(ps.name, ps.codePath); 2213 } 2214 2215 continue; 2216 } 2217 2218 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2219 psit.remove(); 2220 logCriticalInfo(Log.WARN, "System package " + ps.name 2221 + " no longer exists; wiping its data"); 2222 removeDataDirsLI(null, ps.name); 2223 } else { 2224 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2225 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2226 possiblyDeletedUpdatedSystemApps.add(ps.name); 2227 } 2228 } 2229 } 2230 } 2231 2232 //look for any incomplete package installations 2233 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2234 //clean up list 2235 for(int i = 0; i < deletePkgsList.size(); i++) { 2236 //clean up here 2237 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2238 } 2239 //delete tmp files 2240 deleteTempPackageFiles(); 2241 2242 // Remove any shared userIDs that have no associated packages 2243 mSettings.pruneSharedUsersLPw(); 2244 2245 if (!mOnlyCore) { 2246 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2247 SystemClock.uptimeMillis()); 2248 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2249 2250 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2251 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2252 2253 scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL, 2254 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2255 2256 /** 2257 * Remove disable package settings for any updated system 2258 * apps that were removed via an OTA. If they're not a 2259 * previously-updated app, remove them completely. 2260 * Otherwise, just revoke their system-level permissions. 2261 */ 2262 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2263 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2264 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2265 2266 String msg; 2267 if (deletedPkg == null) { 2268 msg = "Updated system package " + deletedAppName 2269 + " no longer exists; wiping its data"; 2270 removeDataDirsLI(null, deletedAppName); 2271 } else { 2272 msg = "Updated system app + " + deletedAppName 2273 + " no longer present; removing system privileges for " 2274 + deletedAppName; 2275 2276 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2277 2278 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2279 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2280 } 2281 logCriticalInfo(Log.WARN, msg); 2282 } 2283 2284 /** 2285 * Make sure all system apps that we expected to appear on 2286 * the userdata partition actually showed up. If they never 2287 * appeared, crawl back and revive the system version. 2288 */ 2289 for (int i = 0; i < mExpectingBetter.size(); i++) { 2290 final String packageName = mExpectingBetter.keyAt(i); 2291 if (!mPackages.containsKey(packageName)) { 2292 final File scanFile = mExpectingBetter.valueAt(i); 2293 2294 logCriticalInfo(Log.WARN, "Expected better " + packageName 2295 + " but never showed up; reverting to system"); 2296 2297 final int reparseFlags; 2298 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2299 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2300 | PackageParser.PARSE_IS_SYSTEM_DIR 2301 | PackageParser.PARSE_IS_PRIVILEGED; 2302 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2303 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2304 | PackageParser.PARSE_IS_SYSTEM_DIR; 2305 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2306 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2307 | PackageParser.PARSE_IS_SYSTEM_DIR; 2308 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2309 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2310 | PackageParser.PARSE_IS_SYSTEM_DIR; 2311 } else { 2312 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2313 continue; 2314 } 2315 2316 mSettings.enableSystemPackageLPw(packageName); 2317 2318 try { 2319 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2320 } catch (PackageManagerException e) { 2321 Slog.e(TAG, "Failed to parse original system package: " 2322 + e.getMessage()); 2323 } 2324 } 2325 } 2326 } 2327 mExpectingBetter.clear(); 2328 2329 // Now that we know all of the shared libraries, update all clients to have 2330 // the correct library paths. 2331 updateAllSharedLibrariesLPw(); 2332 2333 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2334 // NOTE: We ignore potential failures here during a system scan (like 2335 // the rest of the commands above) because there's precious little we 2336 // can do about it. A settings error is reported, though. 2337 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2338 false /* boot complete */); 2339 } 2340 2341 // Now that we know all the packages we are keeping, 2342 // read and update their last usage times. 2343 mPackageUsage.readLP(); 2344 2345 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2346 SystemClock.uptimeMillis()); 2347 Slog.i(TAG, "Time to scan packages: " 2348 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2349 + " seconds"); 2350 2351 // If the platform SDK has changed since the last time we booted, 2352 // we need to re-grant app permission to catch any new ones that 2353 // appear. This is really a hack, and means that apps can in some 2354 // cases get permissions that the user didn't initially explicitly 2355 // allow... it would be nice to have some better way to handle 2356 // this situation. 2357 int updateFlags = UPDATE_PERMISSIONS_ALL; 2358 if (ver.sdkVersion != mSdkVersion) { 2359 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2360 + mSdkVersion + "; regranting permissions for internal storage"); 2361 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2362 } 2363 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2364 ver.sdkVersion = mSdkVersion; 2365 2366 // If this is the first boot or an update from pre-M, and it is a normal 2367 // boot, then we need to initialize the default preferred apps across 2368 // all defined users. 2369 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2370 for (UserInfo user : sUserManager.getUsers(true)) { 2371 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2372 applyFactoryDefaultBrowserLPw(user.id); 2373 primeDomainVerificationsLPw(user.id); 2374 } 2375 } 2376 2377 // Prepare storage for system user really early during boot, 2378 // since core system apps like SettingsProvider and SystemUI 2379 // can't wait for user to start 2380 final int flags; 2381 if (StorageManager.isFileBasedEncryptionEnabled()) { 2382 flags = Installer.FLAG_DE_STORAGE; 2383 } else { 2384 flags = Installer.FLAG_DE_STORAGE | Installer.FLAG_CE_STORAGE; 2385 } 2386 reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, flags); 2387 2388 // If this is first boot after an OTA, and a normal boot, then 2389 // we need to clear code cache directories. 2390 if (mIsUpgrade && !onlyCore) { 2391 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2392 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2393 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2394 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2395 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2396 } 2397 } 2398 ver.fingerprint = Build.FINGERPRINT; 2399 } 2400 2401 checkDefaultBrowser(); 2402 2403 // clear only after permissions and other defaults have been updated 2404 mExistingSystemPackages.clear(); 2405 mPromoteSystemApps = false; 2406 2407 // All the changes are done during package scanning. 2408 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2409 2410 // can downgrade to reader 2411 mSettings.writeLPr(); 2412 2413 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2414 SystemClock.uptimeMillis()); 2415 2416 if (!mOnlyCore) { 2417 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2418 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2419 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2420 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2421 mIntentFilterVerifierComponent); 2422 } else { 2423 mRequiredVerifierPackage = null; 2424 mRequiredInstallerPackage = null; 2425 mIntentFilterVerifierComponent = null; 2426 mIntentFilterVerifier = null; 2427 } 2428 2429 mInstallerService = new PackageInstallerService(context, this); 2430 2431 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2432 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2433 // both the installer and resolver must be present to enable ephemeral 2434 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2435 if (DEBUG_EPHEMERAL) { 2436 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2437 + " installer:" + ephemeralInstallerComponent); 2438 } 2439 mEphemeralResolverComponent = ephemeralResolverComponent; 2440 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2441 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2442 mEphemeralResolverConnection = 2443 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2444 } else { 2445 if (DEBUG_EPHEMERAL) { 2446 final String missingComponent = 2447 (ephemeralResolverComponent == null) 2448 ? (ephemeralInstallerComponent == null) 2449 ? "resolver and installer" 2450 : "resolver" 2451 : "installer"; 2452 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2453 } 2454 mEphemeralResolverComponent = null; 2455 mEphemeralInstallerComponent = null; 2456 mEphemeralResolverConnection = null; 2457 } 2458 2459 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2460 } // synchronized (mPackages) 2461 } // synchronized (mInstallLock) 2462 2463 // Now after opening every single application zip, make sure they 2464 // are all flushed. Not really needed, but keeps things nice and 2465 // tidy. 2466 Runtime.getRuntime().gc(); 2467 2468 // The initial scanning above does many calls into installd while 2469 // holding the mPackages lock, but we're mostly interested in yelling 2470 // once we have a booted system. 2471 mInstaller.setWarnIfHeld(mPackages); 2472 2473 // Expose private service for system components to use. 2474 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2475 } 2476 2477 @Override 2478 public boolean isFirstBoot() { 2479 return !mRestoredSettings; 2480 } 2481 2482 @Override 2483 public boolean isOnlyCoreApps() { 2484 return mOnlyCore; 2485 } 2486 2487 @Override 2488 public boolean isUpgrade() { 2489 return mIsUpgrade; 2490 } 2491 2492 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2493 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2494 2495 final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE, 2496 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2497 if (matches.size() == 1) { 2498 return matches.get(0).getComponentInfo().packageName; 2499 } else { 2500 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2501 return null; 2502 } 2503 } 2504 2505 private @NonNull String getRequiredInstallerLPr() { 2506 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2507 intent.addCategory(Intent.CATEGORY_DEFAULT); 2508 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2509 2510 final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE, 2511 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2512 if (matches.size() == 1) { 2513 return matches.get(0).getComponentInfo().packageName; 2514 } else { 2515 throw new RuntimeException("There must be exactly one installer; found " + matches); 2516 } 2517 } 2518 2519 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2520 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2521 2522 final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE, 2523 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2524 ResolveInfo best = null; 2525 final int N = matches.size(); 2526 for (int i = 0; i < N; i++) { 2527 final ResolveInfo cur = matches.get(i); 2528 final String packageName = cur.getComponentInfo().packageName; 2529 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2530 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2531 continue; 2532 } 2533 2534 if (best == null || cur.priority > best.priority) { 2535 best = cur; 2536 } 2537 } 2538 2539 if (best != null) { 2540 return best.getComponentInfo().getComponentName(); 2541 } else { 2542 throw new RuntimeException("There must be at least one intent filter verifier"); 2543 } 2544 } 2545 2546 private @Nullable ComponentName getEphemeralResolverLPr() { 2547 final String[] packageArray = 2548 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2549 if (packageArray.length == 0) { 2550 if (DEBUG_EPHEMERAL) { 2551 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2552 } 2553 return null; 2554 } 2555 2556 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2557 final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, null, 2558 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2559 2560 final int N = resolvers.size(); 2561 if (N == 0) { 2562 if (DEBUG_EPHEMERAL) { 2563 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2564 } 2565 return null; 2566 } 2567 2568 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2569 for (int i = 0; i < N; i++) { 2570 final ResolveInfo info = resolvers.get(i); 2571 2572 if (info.serviceInfo == null) { 2573 continue; 2574 } 2575 2576 final String packageName = info.serviceInfo.packageName; 2577 if (!possiblePackages.contains(packageName)) { 2578 if (DEBUG_EPHEMERAL) { 2579 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2580 + " pkg: " + packageName + ", info:" + info); 2581 } 2582 continue; 2583 } 2584 2585 if (DEBUG_EPHEMERAL) { 2586 Slog.v(TAG, "Ephemeral resolver found;" 2587 + " pkg: " + packageName + ", info:" + info); 2588 } 2589 return new ComponentName(packageName, info.serviceInfo.name); 2590 } 2591 if (DEBUG_EPHEMERAL) { 2592 Slog.v(TAG, "Ephemeral resolver NOT found"); 2593 } 2594 return null; 2595 } 2596 2597 private @Nullable ComponentName getEphemeralInstallerLPr() { 2598 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2599 intent.addCategory(Intent.CATEGORY_DEFAULT); 2600 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2601 2602 final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE, 2603 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2604 if (matches.size() == 0) { 2605 return null; 2606 } else if (matches.size() == 1) { 2607 return matches.get(0).getComponentInfo().getComponentName(); 2608 } else { 2609 throw new RuntimeException( 2610 "There must be at most one ephemeral installer; found " + matches); 2611 } 2612 } 2613 2614 private void primeDomainVerificationsLPw(int userId) { 2615 if (DEBUG_DOMAIN_VERIFICATION) { 2616 Slog.d(TAG, "Priming domain verifications in user " + userId); 2617 } 2618 2619 SystemConfig systemConfig = SystemConfig.getInstance(); 2620 ArraySet<String> packages = systemConfig.getLinkedApps(); 2621 ArraySet<String> domains = new ArraySet<String>(); 2622 2623 for (String packageName : packages) { 2624 PackageParser.Package pkg = mPackages.get(packageName); 2625 if (pkg != null) { 2626 if (!pkg.isSystemApp()) { 2627 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2628 continue; 2629 } 2630 2631 domains.clear(); 2632 for (PackageParser.Activity a : pkg.activities) { 2633 for (ActivityIntentInfo filter : a.intents) { 2634 if (hasValidDomains(filter)) { 2635 domains.addAll(filter.getHostsList()); 2636 } 2637 } 2638 } 2639 2640 if (domains.size() > 0) { 2641 if (DEBUG_DOMAIN_VERIFICATION) { 2642 Slog.v(TAG, " + " + packageName); 2643 } 2644 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2645 // state w.r.t. the formal app-linkage "no verification attempted" state; 2646 // and then 'always' in the per-user state actually used for intent resolution. 2647 final IntentFilterVerificationInfo ivi; 2648 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2649 new ArrayList<String>(domains)); 2650 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2651 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2652 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2653 } else { 2654 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2655 + "' does not handle web links"); 2656 } 2657 } else { 2658 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2659 } 2660 } 2661 2662 scheduleWritePackageRestrictionsLocked(userId); 2663 scheduleWriteSettingsLocked(); 2664 } 2665 2666 private void applyFactoryDefaultBrowserLPw(int userId) { 2667 // The default browser app's package name is stored in a string resource, 2668 // with a product-specific overlay used for vendor customization. 2669 String browserPkg = mContext.getResources().getString( 2670 com.android.internal.R.string.default_browser); 2671 if (!TextUtils.isEmpty(browserPkg)) { 2672 // non-empty string => required to be a known package 2673 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2674 if (ps == null) { 2675 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2676 browserPkg = null; 2677 } else { 2678 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2679 } 2680 } 2681 2682 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2683 // default. If there's more than one, just leave everything alone. 2684 if (browserPkg == null) { 2685 calculateDefaultBrowserLPw(userId); 2686 } 2687 } 2688 2689 private void calculateDefaultBrowserLPw(int userId) { 2690 List<String> allBrowsers = resolveAllBrowserApps(userId); 2691 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2692 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2693 } 2694 2695 private List<String> resolveAllBrowserApps(int userId) { 2696 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2697 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2698 PackageManager.MATCH_ALL, userId); 2699 2700 final int count = list.size(); 2701 List<String> result = new ArrayList<String>(count); 2702 for (int i=0; i<count; i++) { 2703 ResolveInfo info = list.get(i); 2704 if (info.activityInfo == null 2705 || !info.handleAllWebDataURI 2706 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2707 || result.contains(info.activityInfo.packageName)) { 2708 continue; 2709 } 2710 result.add(info.activityInfo.packageName); 2711 } 2712 2713 return result; 2714 } 2715 2716 private boolean packageIsBrowser(String packageName, int userId) { 2717 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2718 PackageManager.MATCH_ALL, userId); 2719 final int N = list.size(); 2720 for (int i = 0; i < N; i++) { 2721 ResolveInfo info = list.get(i); 2722 if (packageName.equals(info.activityInfo.packageName)) { 2723 return true; 2724 } 2725 } 2726 return false; 2727 } 2728 2729 private void checkDefaultBrowser() { 2730 final int myUserId = UserHandle.myUserId(); 2731 final String packageName = getDefaultBrowserPackageName(myUserId); 2732 if (packageName != null) { 2733 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2734 if (info == null) { 2735 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2736 synchronized (mPackages) { 2737 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2738 } 2739 } 2740 } 2741 } 2742 2743 @Override 2744 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2745 throws RemoteException { 2746 try { 2747 return super.onTransact(code, data, reply, flags); 2748 } catch (RuntimeException e) { 2749 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2750 Slog.wtf(TAG, "Package Manager Crash", e); 2751 } 2752 throw e; 2753 } 2754 } 2755 2756 void cleanupInstallFailedPackage(PackageSetting ps) { 2757 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2758 2759 removeDataDirsLI(ps.volumeUuid, ps.name); 2760 if (ps.codePath != null) { 2761 removeCodePathLI(ps.codePath); 2762 } 2763 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2764 if (ps.resourcePath.isDirectory()) { 2765 FileUtils.deleteContents(ps.resourcePath); 2766 } 2767 ps.resourcePath.delete(); 2768 } 2769 mSettings.removePackageLPw(ps.name); 2770 } 2771 2772 static int[] appendInts(int[] cur, int[] add) { 2773 if (add == null) return cur; 2774 if (cur == null) return add; 2775 final int N = add.length; 2776 for (int i=0; i<N; i++) { 2777 cur = appendInt(cur, add[i]); 2778 } 2779 return cur; 2780 } 2781 2782 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2783 if (!sUserManager.exists(userId)) return null; 2784 final PackageSetting ps = (PackageSetting) p.mExtras; 2785 if (ps == null) { 2786 return null; 2787 } 2788 2789 final PermissionsState permissionsState = ps.getPermissionsState(); 2790 2791 final int[] gids = permissionsState.computeGids(userId); 2792 final Set<String> permissions = permissionsState.getPermissions(userId); 2793 final PackageUserState state = ps.readUserState(userId); 2794 2795 return PackageParser.generatePackageInfo(p, gids, flags, 2796 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2797 } 2798 2799 @Override 2800 public void checkPackageStartable(String packageName, int userId) { 2801 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 2802 2803 synchronized (mPackages) { 2804 final PackageSetting ps = mSettings.mPackages.get(packageName); 2805 if (ps == null) { 2806 throw new SecurityException("Package " + packageName + " was not found!"); 2807 } 2808 2809 if (ps.frozen) { 2810 throw new SecurityException("Package " + packageName + " is currently frozen!"); 2811 } 2812 2813 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware() 2814 || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) { 2815 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 2816 } 2817 } 2818 } 2819 2820 @Override 2821 public boolean isPackageAvailable(String packageName, int userId) { 2822 if (!sUserManager.exists(userId)) return false; 2823 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2824 synchronized (mPackages) { 2825 PackageParser.Package p = mPackages.get(packageName); 2826 if (p != null) { 2827 final PackageSetting ps = (PackageSetting) p.mExtras; 2828 if (ps != null) { 2829 final PackageUserState state = ps.readUserState(userId); 2830 if (state != null) { 2831 return PackageParser.isAvailable(state); 2832 } 2833 } 2834 } 2835 } 2836 return false; 2837 } 2838 2839 @Override 2840 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2841 if (!sUserManager.exists(userId)) return null; 2842 flags = updateFlagsForPackage(flags, userId, packageName); 2843 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2844 // reader 2845 synchronized (mPackages) { 2846 PackageParser.Package p = mPackages.get(packageName); 2847 if (DEBUG_PACKAGE_INFO) 2848 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2849 if (p != null) { 2850 return generatePackageInfo(p, flags, userId); 2851 } 2852 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2853 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2854 } 2855 } 2856 return null; 2857 } 2858 2859 @Override 2860 public String[] currentToCanonicalPackageNames(String[] names) { 2861 String[] out = new String[names.length]; 2862 // reader 2863 synchronized (mPackages) { 2864 for (int i=names.length-1; i>=0; i--) { 2865 PackageSetting ps = mSettings.mPackages.get(names[i]); 2866 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2867 } 2868 } 2869 return out; 2870 } 2871 2872 @Override 2873 public String[] canonicalToCurrentPackageNames(String[] names) { 2874 String[] out = new String[names.length]; 2875 // reader 2876 synchronized (mPackages) { 2877 for (int i=names.length-1; i>=0; i--) { 2878 String cur = mSettings.mRenamedPackages.get(names[i]); 2879 out[i] = cur != null ? cur : names[i]; 2880 } 2881 } 2882 return out; 2883 } 2884 2885 @Override 2886 public int getPackageUid(String packageName, int flags, int userId) { 2887 if (!sUserManager.exists(userId)) return -1; 2888 flags = updateFlagsForPackage(flags, userId, packageName); 2889 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2890 2891 // reader 2892 synchronized (mPackages) { 2893 final PackageParser.Package p = mPackages.get(packageName); 2894 if (p != null && p.isMatch(flags)) { 2895 return UserHandle.getUid(userId, p.applicationInfo.uid); 2896 } 2897 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2898 final PackageSetting ps = mSettings.mPackages.get(packageName); 2899 if (ps != null && ps.isMatch(flags)) { 2900 return UserHandle.getUid(userId, ps.appId); 2901 } 2902 } 2903 } 2904 2905 return -1; 2906 } 2907 2908 @Override 2909 public int[] getPackageGids(String packageName, int flags, int userId) { 2910 if (!sUserManager.exists(userId)) return null; 2911 flags = updateFlagsForPackage(flags, userId, packageName); 2912 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2913 "getPackageGids"); 2914 2915 // reader 2916 synchronized (mPackages) { 2917 final PackageParser.Package p = mPackages.get(packageName); 2918 if (p != null && p.isMatch(flags)) { 2919 PackageSetting ps = (PackageSetting) p.mExtras; 2920 return ps.getPermissionsState().computeGids(userId); 2921 } 2922 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2923 final PackageSetting ps = mSettings.mPackages.get(packageName); 2924 if (ps != null && ps.isMatch(flags)) { 2925 return ps.getPermissionsState().computeGids(userId); 2926 } 2927 } 2928 } 2929 2930 return null; 2931 } 2932 2933 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 2934 if (bp.perm != null) { 2935 return PackageParser.generatePermissionInfo(bp.perm, flags); 2936 } 2937 PermissionInfo pi = new PermissionInfo(); 2938 pi.name = bp.name; 2939 pi.packageName = bp.sourcePackage; 2940 pi.nonLocalizedLabel = bp.name; 2941 pi.protectionLevel = bp.protectionLevel; 2942 return pi; 2943 } 2944 2945 @Override 2946 public PermissionInfo getPermissionInfo(String name, int flags) { 2947 // reader 2948 synchronized (mPackages) { 2949 final BasePermission p = mSettings.mPermissions.get(name); 2950 if (p != null) { 2951 return generatePermissionInfo(p, flags); 2952 } 2953 return null; 2954 } 2955 } 2956 2957 @Override 2958 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2959 // reader 2960 synchronized (mPackages) { 2961 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2962 for (BasePermission p : mSettings.mPermissions.values()) { 2963 if (group == null) { 2964 if (p.perm == null || p.perm.info.group == null) { 2965 out.add(generatePermissionInfo(p, flags)); 2966 } 2967 } else { 2968 if (p.perm != null && group.equals(p.perm.info.group)) { 2969 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2970 } 2971 } 2972 } 2973 2974 if (out.size() > 0) { 2975 return out; 2976 } 2977 return mPermissionGroups.containsKey(group) ? out : null; 2978 } 2979 } 2980 2981 @Override 2982 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2983 // reader 2984 synchronized (mPackages) { 2985 return PackageParser.generatePermissionGroupInfo( 2986 mPermissionGroups.get(name), flags); 2987 } 2988 } 2989 2990 @Override 2991 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2992 // reader 2993 synchronized (mPackages) { 2994 final int N = mPermissionGroups.size(); 2995 ArrayList<PermissionGroupInfo> out 2996 = new ArrayList<PermissionGroupInfo>(N); 2997 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2998 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2999 } 3000 return out; 3001 } 3002 } 3003 3004 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3005 int userId) { 3006 if (!sUserManager.exists(userId)) return null; 3007 PackageSetting ps = mSettings.mPackages.get(packageName); 3008 if (ps != null) { 3009 if (ps.pkg == null) { 3010 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 3011 flags, userId); 3012 if (pInfo != null) { 3013 return pInfo.applicationInfo; 3014 } 3015 return null; 3016 } 3017 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3018 ps.readUserState(userId), userId); 3019 } 3020 return null; 3021 } 3022 3023 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 3024 int userId) { 3025 if (!sUserManager.exists(userId)) return null; 3026 PackageSetting ps = mSettings.mPackages.get(packageName); 3027 if (ps != null) { 3028 PackageParser.Package pkg = ps.pkg; 3029 if (pkg == null) { 3030 if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) { 3031 return null; 3032 } 3033 // Only data remains, so we aren't worried about code paths 3034 pkg = new PackageParser.Package(packageName); 3035 pkg.applicationInfo.packageName = packageName; 3036 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 3037 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 3038 pkg.applicationInfo.uid = ps.appId; 3039 pkg.applicationInfo.initForUser(userId); 3040 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 3041 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 3042 } 3043 return generatePackageInfo(pkg, flags, userId); 3044 } 3045 return null; 3046 } 3047 3048 @Override 3049 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3050 if (!sUserManager.exists(userId)) return null; 3051 flags = updateFlagsForApplication(flags, userId, packageName); 3052 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 3053 // writer 3054 synchronized (mPackages) { 3055 PackageParser.Package p = mPackages.get(packageName); 3056 if (DEBUG_PACKAGE_INFO) Log.v( 3057 TAG, "getApplicationInfo " + packageName 3058 + ": " + p); 3059 if (p != null) { 3060 PackageSetting ps = mSettings.mPackages.get(packageName); 3061 if (ps == null) return null; 3062 // Note: isEnabledLP() does not apply here - always return info 3063 return PackageParser.generateApplicationInfo( 3064 p, flags, ps.readUserState(userId), userId); 3065 } 3066 if ("android".equals(packageName)||"system".equals(packageName)) { 3067 return mAndroidApplication; 3068 } 3069 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3070 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3071 } 3072 } 3073 return null; 3074 } 3075 3076 @Override 3077 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3078 final IPackageDataObserver observer) { 3079 mContext.enforceCallingOrSelfPermission( 3080 android.Manifest.permission.CLEAR_APP_CACHE, null); 3081 // Queue up an async operation since clearing cache may take a little while. 3082 mHandler.post(new Runnable() { 3083 public void run() { 3084 mHandler.removeCallbacks(this); 3085 boolean success = true; 3086 synchronized (mInstallLock) { 3087 try { 3088 mInstaller.freeCache(volumeUuid, freeStorageSize); 3089 } catch (InstallerException e) { 3090 Slog.w(TAG, "Couldn't clear application caches: " + e); 3091 success = false; 3092 } 3093 } 3094 if (observer != null) { 3095 try { 3096 observer.onRemoveCompleted(null, success); 3097 } catch (RemoteException e) { 3098 Slog.w(TAG, "RemoveException when invoking call back"); 3099 } 3100 } 3101 } 3102 }); 3103 } 3104 3105 @Override 3106 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3107 final IntentSender pi) { 3108 mContext.enforceCallingOrSelfPermission( 3109 android.Manifest.permission.CLEAR_APP_CACHE, null); 3110 // Queue up an async operation since clearing cache may take a little while. 3111 mHandler.post(new Runnable() { 3112 public void run() { 3113 mHandler.removeCallbacks(this); 3114 boolean success = true; 3115 synchronized (mInstallLock) { 3116 try { 3117 mInstaller.freeCache(volumeUuid, freeStorageSize); 3118 } catch (InstallerException e) { 3119 Slog.w(TAG, "Couldn't clear application caches: " + e); 3120 success = false; 3121 } 3122 } 3123 if(pi != null) { 3124 try { 3125 // Callback via pending intent 3126 int code = success ? 1 : 0; 3127 pi.sendIntent(null, code, null, 3128 null, null); 3129 } catch (SendIntentException e1) { 3130 Slog.i(TAG, "Failed to send pending intent"); 3131 } 3132 } 3133 } 3134 }); 3135 } 3136 3137 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3138 synchronized (mInstallLock) { 3139 try { 3140 mInstaller.freeCache(volumeUuid, freeStorageSize); 3141 } catch (InstallerException e) { 3142 throw new IOException("Failed to free enough space", e); 3143 } 3144 } 3145 } 3146 3147 /** 3148 * Return if the user key is currently unlocked. 3149 */ 3150 private boolean isUserKeyUnlocked(int userId) { 3151 if (StorageManager.isFileBasedEncryptionEnabled()) { 3152 final IMountService mount = IMountService.Stub 3153 .asInterface(ServiceManager.getService("mount")); 3154 if (mount == null) { 3155 Slog.w(TAG, "Early during boot, assuming locked"); 3156 return false; 3157 } 3158 final long token = Binder.clearCallingIdentity(); 3159 try { 3160 return mount.isUserKeyUnlocked(userId); 3161 } catch (RemoteException e) { 3162 throw e.rethrowAsRuntimeException(); 3163 } finally { 3164 Binder.restoreCallingIdentity(token); 3165 } 3166 } else { 3167 return true; 3168 } 3169 } 3170 3171 /** 3172 * Update given flags based on encryption status of current user. 3173 */ 3174 private int updateFlags(int flags, int userId) { 3175 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3176 | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) { 3177 // Caller expressed an explicit opinion about what encryption 3178 // aware/unaware components they want to see, so fall through and 3179 // give them what they want 3180 } else { 3181 // Caller expressed no opinion, so match based on user state 3182 if (isUserKeyUnlocked(userId)) { 3183 flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE; 3184 } else { 3185 flags |= PackageManager.MATCH_ENCRYPTION_AWARE; 3186 } 3187 } 3188 3189 // Safe mode means we should ignore any third-party apps 3190 if (mSafeMode) { 3191 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3192 } 3193 3194 return flags; 3195 } 3196 3197 /** 3198 * Update given flags when being used to request {@link PackageInfo}. 3199 */ 3200 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3201 boolean triaged = true; 3202 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3203 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3204 // Caller is asking for component details, so they'd better be 3205 // asking for specific encryption matching behavior, or be triaged 3206 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3207 | PackageManager.MATCH_ENCRYPTION_AWARE 3208 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3209 triaged = false; 3210 } 3211 } 3212 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3213 | PackageManager.MATCH_SYSTEM_ONLY 3214 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3215 triaged = false; 3216 } 3217 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3218 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3219 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3220 } 3221 return updateFlags(flags, userId); 3222 } 3223 3224 /** 3225 * Update given flags when being used to request {@link ApplicationInfo}. 3226 */ 3227 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3228 return updateFlagsForPackage(flags, userId, cookie); 3229 } 3230 3231 /** 3232 * Update given flags when being used to request {@link ComponentInfo}. 3233 */ 3234 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3235 if (cookie instanceof Intent) { 3236 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3237 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3238 } 3239 } 3240 3241 boolean triaged = true; 3242 // Caller is asking for component details, so they'd better be 3243 // asking for specific encryption matching behavior, or be triaged 3244 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3245 | PackageManager.MATCH_ENCRYPTION_AWARE 3246 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3247 triaged = false; 3248 } 3249 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3250 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3251 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3252 } 3253 return updateFlags(flags, userId); 3254 } 3255 3256 /** 3257 * Update given flags when being used to request {@link ResolveInfo}. 3258 */ 3259 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3260 return updateFlagsForComponent(flags, userId, cookie); 3261 } 3262 3263 @Override 3264 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3265 if (!sUserManager.exists(userId)) return null; 3266 flags = updateFlagsForComponent(flags, userId, component); 3267 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 3268 synchronized (mPackages) { 3269 PackageParser.Activity a = mActivities.mActivities.get(component); 3270 3271 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3272 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3273 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3274 if (ps == null) return null; 3275 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3276 userId); 3277 } 3278 if (mResolveComponentName.equals(component)) { 3279 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3280 new PackageUserState(), userId); 3281 } 3282 } 3283 return null; 3284 } 3285 3286 @Override 3287 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3288 String resolvedType) { 3289 synchronized (mPackages) { 3290 if (component.equals(mResolveComponentName)) { 3291 // The resolver supports EVERYTHING! 3292 return true; 3293 } 3294 PackageParser.Activity a = mActivities.mActivities.get(component); 3295 if (a == null) { 3296 return false; 3297 } 3298 for (int i=0; i<a.intents.size(); i++) { 3299 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3300 intent.getData(), intent.getCategories(), TAG) >= 0) { 3301 return true; 3302 } 3303 } 3304 return false; 3305 } 3306 } 3307 3308 @Override 3309 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3310 if (!sUserManager.exists(userId)) return null; 3311 flags = updateFlagsForComponent(flags, userId, component); 3312 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3313 synchronized (mPackages) { 3314 PackageParser.Activity a = mReceivers.mActivities.get(component); 3315 if (DEBUG_PACKAGE_INFO) Log.v( 3316 TAG, "getReceiverInfo " + component + ": " + a); 3317 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3318 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3319 if (ps == null) return null; 3320 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3321 userId); 3322 } 3323 } 3324 return null; 3325 } 3326 3327 @Override 3328 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3329 if (!sUserManager.exists(userId)) return null; 3330 flags = updateFlagsForComponent(flags, userId, component); 3331 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3332 synchronized (mPackages) { 3333 PackageParser.Service s = mServices.mServices.get(component); 3334 if (DEBUG_PACKAGE_INFO) Log.v( 3335 TAG, "getServiceInfo " + component + ": " + s); 3336 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3337 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3338 if (ps == null) return null; 3339 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3340 userId); 3341 } 3342 } 3343 return null; 3344 } 3345 3346 @Override 3347 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3348 if (!sUserManager.exists(userId)) return null; 3349 flags = updateFlagsForComponent(flags, userId, component); 3350 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3351 synchronized (mPackages) { 3352 PackageParser.Provider p = mProviders.mProviders.get(component); 3353 if (DEBUG_PACKAGE_INFO) Log.v( 3354 TAG, "getProviderInfo " + component + ": " + p); 3355 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3356 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3357 if (ps == null) return null; 3358 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3359 userId); 3360 } 3361 } 3362 return null; 3363 } 3364 3365 @Override 3366 public String[] getSystemSharedLibraryNames() { 3367 Set<String> libSet; 3368 synchronized (mPackages) { 3369 libSet = mSharedLibraries.keySet(); 3370 int size = libSet.size(); 3371 if (size > 0) { 3372 String[] libs = new String[size]; 3373 libSet.toArray(libs); 3374 return libs; 3375 } 3376 } 3377 return null; 3378 } 3379 3380 /** 3381 * @hide 3382 */ 3383 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3384 synchronized (mPackages) { 3385 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3386 if (lib != null && lib.apk != null) { 3387 return mPackages.get(lib.apk); 3388 } 3389 } 3390 return null; 3391 } 3392 3393 @Override 3394 public FeatureInfo[] getSystemAvailableFeatures() { 3395 Collection<FeatureInfo> featSet; 3396 synchronized (mPackages) { 3397 featSet = mAvailableFeatures.values(); 3398 int size = featSet.size(); 3399 if (size > 0) { 3400 FeatureInfo[] features = new FeatureInfo[size+1]; 3401 featSet.toArray(features); 3402 FeatureInfo fi = new FeatureInfo(); 3403 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3404 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3405 features[size] = fi; 3406 return features; 3407 } 3408 } 3409 return null; 3410 } 3411 3412 @Override 3413 public boolean hasSystemFeature(String name) { 3414 synchronized (mPackages) { 3415 return mAvailableFeatures.containsKey(name); 3416 } 3417 } 3418 3419 @Override 3420 public int checkPermission(String permName, String pkgName, int userId) { 3421 if (!sUserManager.exists(userId)) { 3422 return PackageManager.PERMISSION_DENIED; 3423 } 3424 3425 synchronized (mPackages) { 3426 final PackageParser.Package p = mPackages.get(pkgName); 3427 if (p != null && p.mExtras != null) { 3428 final PackageSetting ps = (PackageSetting) p.mExtras; 3429 final PermissionsState permissionsState = ps.getPermissionsState(); 3430 if (permissionsState.hasPermission(permName, userId)) { 3431 return PackageManager.PERMISSION_GRANTED; 3432 } 3433 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3434 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3435 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3436 return PackageManager.PERMISSION_GRANTED; 3437 } 3438 } 3439 } 3440 3441 return PackageManager.PERMISSION_DENIED; 3442 } 3443 3444 @Override 3445 public int checkUidPermission(String permName, int uid) { 3446 final int userId = UserHandle.getUserId(uid); 3447 3448 if (!sUserManager.exists(userId)) { 3449 return PackageManager.PERMISSION_DENIED; 3450 } 3451 3452 synchronized (mPackages) { 3453 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3454 if (obj != null) { 3455 final SettingBase ps = (SettingBase) obj; 3456 final PermissionsState permissionsState = ps.getPermissionsState(); 3457 if (permissionsState.hasPermission(permName, userId)) { 3458 return PackageManager.PERMISSION_GRANTED; 3459 } 3460 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3461 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3462 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3463 return PackageManager.PERMISSION_GRANTED; 3464 } 3465 } else { 3466 ArraySet<String> perms = mSystemPermissions.get(uid); 3467 if (perms != null) { 3468 if (perms.contains(permName)) { 3469 return PackageManager.PERMISSION_GRANTED; 3470 } 3471 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3472 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3473 return PackageManager.PERMISSION_GRANTED; 3474 } 3475 } 3476 } 3477 } 3478 3479 return PackageManager.PERMISSION_DENIED; 3480 } 3481 3482 @Override 3483 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3484 if (UserHandle.getCallingUserId() != userId) { 3485 mContext.enforceCallingPermission( 3486 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3487 "isPermissionRevokedByPolicy for user " + userId); 3488 } 3489 3490 if (checkPermission(permission, packageName, userId) 3491 == PackageManager.PERMISSION_GRANTED) { 3492 return false; 3493 } 3494 3495 final long identity = Binder.clearCallingIdentity(); 3496 try { 3497 final int flags = getPermissionFlags(permission, packageName, userId); 3498 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3499 } finally { 3500 Binder.restoreCallingIdentity(identity); 3501 } 3502 } 3503 3504 @Override 3505 public String getPermissionControllerPackageName() { 3506 synchronized (mPackages) { 3507 return mRequiredInstallerPackage; 3508 } 3509 } 3510 3511 /** 3512 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3513 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3514 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3515 * @param message the message to log on security exception 3516 */ 3517 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3518 boolean checkShell, String message) { 3519 if (userId < 0) { 3520 throw new IllegalArgumentException("Invalid userId " + userId); 3521 } 3522 if (checkShell) { 3523 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3524 } 3525 if (userId == UserHandle.getUserId(callingUid)) return; 3526 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3527 if (requireFullPermission) { 3528 mContext.enforceCallingOrSelfPermission( 3529 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3530 } else { 3531 try { 3532 mContext.enforceCallingOrSelfPermission( 3533 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3534 } catch (SecurityException se) { 3535 mContext.enforceCallingOrSelfPermission( 3536 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3537 } 3538 } 3539 } 3540 } 3541 3542 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3543 if (callingUid == Process.SHELL_UID) { 3544 if (userHandle >= 0 3545 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3546 throw new SecurityException("Shell does not have permission to access user " 3547 + userHandle); 3548 } else if (userHandle < 0) { 3549 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3550 + Debug.getCallers(3)); 3551 } 3552 } 3553 } 3554 3555 private BasePermission findPermissionTreeLP(String permName) { 3556 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3557 if (permName.startsWith(bp.name) && 3558 permName.length() > bp.name.length() && 3559 permName.charAt(bp.name.length()) == '.') { 3560 return bp; 3561 } 3562 } 3563 return null; 3564 } 3565 3566 private BasePermission checkPermissionTreeLP(String permName) { 3567 if (permName != null) { 3568 BasePermission bp = findPermissionTreeLP(permName); 3569 if (bp != null) { 3570 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3571 return bp; 3572 } 3573 throw new SecurityException("Calling uid " 3574 + Binder.getCallingUid() 3575 + " is not allowed to add to permission tree " 3576 + bp.name + " owned by uid " + bp.uid); 3577 } 3578 } 3579 throw new SecurityException("No permission tree found for " + permName); 3580 } 3581 3582 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3583 if (s1 == null) { 3584 return s2 == null; 3585 } 3586 if (s2 == null) { 3587 return false; 3588 } 3589 if (s1.getClass() != s2.getClass()) { 3590 return false; 3591 } 3592 return s1.equals(s2); 3593 } 3594 3595 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3596 if (pi1.icon != pi2.icon) return false; 3597 if (pi1.logo != pi2.logo) return false; 3598 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3599 if (!compareStrings(pi1.name, pi2.name)) return false; 3600 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3601 // We'll take care of setting this one. 3602 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3603 // These are not currently stored in settings. 3604 //if (!compareStrings(pi1.group, pi2.group)) return false; 3605 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3606 //if (pi1.labelRes != pi2.labelRes) return false; 3607 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3608 return true; 3609 } 3610 3611 int permissionInfoFootprint(PermissionInfo info) { 3612 int size = info.name.length(); 3613 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3614 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3615 return size; 3616 } 3617 3618 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3619 int size = 0; 3620 for (BasePermission perm : mSettings.mPermissions.values()) { 3621 if (perm.uid == tree.uid) { 3622 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3623 } 3624 } 3625 return size; 3626 } 3627 3628 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3629 // We calculate the max size of permissions defined by this uid and throw 3630 // if that plus the size of 'info' would exceed our stated maximum. 3631 if (tree.uid != Process.SYSTEM_UID) { 3632 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3633 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3634 throw new SecurityException("Permission tree size cap exceeded"); 3635 } 3636 } 3637 } 3638 3639 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3640 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3641 throw new SecurityException("Label must be specified in permission"); 3642 } 3643 BasePermission tree = checkPermissionTreeLP(info.name); 3644 BasePermission bp = mSettings.mPermissions.get(info.name); 3645 boolean added = bp == null; 3646 boolean changed = true; 3647 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3648 if (added) { 3649 enforcePermissionCapLocked(info, tree); 3650 bp = new BasePermission(info.name, tree.sourcePackage, 3651 BasePermission.TYPE_DYNAMIC); 3652 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3653 throw new SecurityException( 3654 "Not allowed to modify non-dynamic permission " 3655 + info.name); 3656 } else { 3657 if (bp.protectionLevel == fixedLevel 3658 && bp.perm.owner.equals(tree.perm.owner) 3659 && bp.uid == tree.uid 3660 && comparePermissionInfos(bp.perm.info, info)) { 3661 changed = false; 3662 } 3663 } 3664 bp.protectionLevel = fixedLevel; 3665 info = new PermissionInfo(info); 3666 info.protectionLevel = fixedLevel; 3667 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3668 bp.perm.info.packageName = tree.perm.info.packageName; 3669 bp.uid = tree.uid; 3670 if (added) { 3671 mSettings.mPermissions.put(info.name, bp); 3672 } 3673 if (changed) { 3674 if (!async) { 3675 mSettings.writeLPr(); 3676 } else { 3677 scheduleWriteSettingsLocked(); 3678 } 3679 } 3680 return added; 3681 } 3682 3683 @Override 3684 public boolean addPermission(PermissionInfo info) { 3685 synchronized (mPackages) { 3686 return addPermissionLocked(info, false); 3687 } 3688 } 3689 3690 @Override 3691 public boolean addPermissionAsync(PermissionInfo info) { 3692 synchronized (mPackages) { 3693 return addPermissionLocked(info, true); 3694 } 3695 } 3696 3697 @Override 3698 public void removePermission(String name) { 3699 synchronized (mPackages) { 3700 checkPermissionTreeLP(name); 3701 BasePermission bp = mSettings.mPermissions.get(name); 3702 if (bp != null) { 3703 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3704 throw new SecurityException( 3705 "Not allowed to modify non-dynamic permission " 3706 + name); 3707 } 3708 mSettings.mPermissions.remove(name); 3709 mSettings.writeLPr(); 3710 } 3711 } 3712 } 3713 3714 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3715 BasePermission bp) { 3716 int index = pkg.requestedPermissions.indexOf(bp.name); 3717 if (index == -1) { 3718 throw new SecurityException("Package " + pkg.packageName 3719 + " has not requested permission " + bp.name); 3720 } 3721 if (!bp.isRuntime() && !bp.isDevelopment()) { 3722 throw new SecurityException("Permission " + bp.name 3723 + " is not a changeable permission type"); 3724 } 3725 } 3726 3727 @Override 3728 public void grantRuntimePermission(String packageName, String name, final int userId) { 3729 if (!sUserManager.exists(userId)) { 3730 Log.e(TAG, "No such user:" + userId); 3731 return; 3732 } 3733 3734 mContext.enforceCallingOrSelfPermission( 3735 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3736 "grantRuntimePermission"); 3737 3738 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3739 "grantRuntimePermission"); 3740 3741 final int uid; 3742 final SettingBase sb; 3743 3744 synchronized (mPackages) { 3745 final PackageParser.Package pkg = mPackages.get(packageName); 3746 if (pkg == null) { 3747 throw new IllegalArgumentException("Unknown package: " + packageName); 3748 } 3749 3750 final BasePermission bp = mSettings.mPermissions.get(name); 3751 if (bp == null) { 3752 throw new IllegalArgumentException("Unknown permission: " + name); 3753 } 3754 3755 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3756 3757 // If a permission review is required for legacy apps we represent 3758 // their permissions as always granted runtime ones since we need 3759 // to keep the review required permission flag per user while an 3760 // install permission's state is shared across all users. 3761 if (Build.PERMISSIONS_REVIEW_REQUIRED 3762 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3763 && bp.isRuntime()) { 3764 return; 3765 } 3766 3767 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3768 sb = (SettingBase) pkg.mExtras; 3769 if (sb == null) { 3770 throw new IllegalArgumentException("Unknown package: " + packageName); 3771 } 3772 3773 final PermissionsState permissionsState = sb.getPermissionsState(); 3774 3775 final int flags = permissionsState.getPermissionFlags(name, userId); 3776 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3777 throw new SecurityException("Cannot grant system fixed permission " 3778 + name + " for package " + packageName); 3779 } 3780 3781 if (bp.isDevelopment()) { 3782 // Development permissions must be handled specially, since they are not 3783 // normal runtime permissions. For now they apply to all users. 3784 if (permissionsState.grantInstallPermission(bp) != 3785 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3786 scheduleWriteSettingsLocked(); 3787 } 3788 return; 3789 } 3790 3791 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 3792 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 3793 return; 3794 } 3795 3796 final int result = permissionsState.grantRuntimePermission(bp, userId); 3797 switch (result) { 3798 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3799 return; 3800 } 3801 3802 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3803 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3804 mHandler.post(new Runnable() { 3805 @Override 3806 public void run() { 3807 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3808 } 3809 }); 3810 } 3811 break; 3812 } 3813 3814 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3815 3816 // Not critical if that is lost - app has to request again. 3817 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3818 } 3819 3820 // Only need to do this if user is initialized. Otherwise it's a new user 3821 // and there are no processes running as the user yet and there's no need 3822 // to make an expensive call to remount processes for the changed permissions. 3823 if (READ_EXTERNAL_STORAGE.equals(name) 3824 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3825 final long token = Binder.clearCallingIdentity(); 3826 try { 3827 if (sUserManager.isInitialized(userId)) { 3828 MountServiceInternal mountServiceInternal = LocalServices.getService( 3829 MountServiceInternal.class); 3830 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3831 } 3832 } finally { 3833 Binder.restoreCallingIdentity(token); 3834 } 3835 } 3836 } 3837 3838 @Override 3839 public void revokeRuntimePermission(String packageName, String name, int userId) { 3840 if (!sUserManager.exists(userId)) { 3841 Log.e(TAG, "No such user:" + userId); 3842 return; 3843 } 3844 3845 mContext.enforceCallingOrSelfPermission( 3846 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3847 "revokeRuntimePermission"); 3848 3849 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3850 "revokeRuntimePermission"); 3851 3852 final int appId; 3853 3854 synchronized (mPackages) { 3855 final PackageParser.Package pkg = mPackages.get(packageName); 3856 if (pkg == null) { 3857 throw new IllegalArgumentException("Unknown package: " + packageName); 3858 } 3859 3860 final BasePermission bp = mSettings.mPermissions.get(name); 3861 if (bp == null) { 3862 throw new IllegalArgumentException("Unknown permission: " + name); 3863 } 3864 3865 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3866 3867 // If a permission review is required for legacy apps we represent 3868 // their permissions as always granted runtime ones since we need 3869 // to keep the review required permission flag per user while an 3870 // install permission's state is shared across all users. 3871 if (Build.PERMISSIONS_REVIEW_REQUIRED 3872 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3873 && bp.isRuntime()) { 3874 return; 3875 } 3876 3877 SettingBase sb = (SettingBase) pkg.mExtras; 3878 if (sb == null) { 3879 throw new IllegalArgumentException("Unknown package: " + packageName); 3880 } 3881 3882 final PermissionsState permissionsState = sb.getPermissionsState(); 3883 3884 final int flags = permissionsState.getPermissionFlags(name, userId); 3885 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3886 throw new SecurityException("Cannot revoke system fixed permission " 3887 + name + " for package " + packageName); 3888 } 3889 3890 if (bp.isDevelopment()) { 3891 // Development permissions must be handled specially, since they are not 3892 // normal runtime permissions. For now they apply to all users. 3893 if (permissionsState.revokeInstallPermission(bp) != 3894 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3895 scheduleWriteSettingsLocked(); 3896 } 3897 return; 3898 } 3899 3900 if (permissionsState.revokeRuntimePermission(bp, userId) == 3901 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3902 return; 3903 } 3904 3905 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3906 3907 // Critical, after this call app should never have the permission. 3908 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3909 3910 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3911 } 3912 3913 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3914 } 3915 3916 @Override 3917 public void resetRuntimePermissions() { 3918 mContext.enforceCallingOrSelfPermission( 3919 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3920 "revokeRuntimePermission"); 3921 3922 int callingUid = Binder.getCallingUid(); 3923 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3924 mContext.enforceCallingOrSelfPermission( 3925 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3926 "resetRuntimePermissions"); 3927 } 3928 3929 synchronized (mPackages) { 3930 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3931 for (int userId : UserManagerService.getInstance().getUserIds()) { 3932 final int packageCount = mPackages.size(); 3933 for (int i = 0; i < packageCount; i++) { 3934 PackageParser.Package pkg = mPackages.valueAt(i); 3935 if (!(pkg.mExtras instanceof PackageSetting)) { 3936 continue; 3937 } 3938 PackageSetting ps = (PackageSetting) pkg.mExtras; 3939 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3940 } 3941 } 3942 } 3943 } 3944 3945 @Override 3946 public int getPermissionFlags(String name, String packageName, int userId) { 3947 if (!sUserManager.exists(userId)) { 3948 return 0; 3949 } 3950 3951 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3952 3953 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3954 "getPermissionFlags"); 3955 3956 synchronized (mPackages) { 3957 final PackageParser.Package pkg = mPackages.get(packageName); 3958 if (pkg == null) { 3959 throw new IllegalArgumentException("Unknown package: " + packageName); 3960 } 3961 3962 final BasePermission bp = mSettings.mPermissions.get(name); 3963 if (bp == null) { 3964 throw new IllegalArgumentException("Unknown permission: " + name); 3965 } 3966 3967 SettingBase sb = (SettingBase) pkg.mExtras; 3968 if (sb == null) { 3969 throw new IllegalArgumentException("Unknown package: " + packageName); 3970 } 3971 3972 PermissionsState permissionsState = sb.getPermissionsState(); 3973 return permissionsState.getPermissionFlags(name, userId); 3974 } 3975 } 3976 3977 @Override 3978 public void updatePermissionFlags(String name, String packageName, int flagMask, 3979 int flagValues, int userId) { 3980 if (!sUserManager.exists(userId)) { 3981 return; 3982 } 3983 3984 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3985 3986 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3987 "updatePermissionFlags"); 3988 3989 // Only the system can change these flags and nothing else. 3990 if (getCallingUid() != Process.SYSTEM_UID) { 3991 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3992 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3993 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3994 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3995 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 3996 } 3997 3998 synchronized (mPackages) { 3999 final PackageParser.Package pkg = mPackages.get(packageName); 4000 if (pkg == null) { 4001 throw new IllegalArgumentException("Unknown package: " + packageName); 4002 } 4003 4004 final BasePermission bp = mSettings.mPermissions.get(name); 4005 if (bp == null) { 4006 throw new IllegalArgumentException("Unknown permission: " + name); 4007 } 4008 4009 SettingBase sb = (SettingBase) pkg.mExtras; 4010 if (sb == null) { 4011 throw new IllegalArgumentException("Unknown package: " + packageName); 4012 } 4013 4014 PermissionsState permissionsState = sb.getPermissionsState(); 4015 4016 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4017 4018 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4019 // Install and runtime permissions are stored in different places, 4020 // so figure out what permission changed and persist the change. 4021 if (permissionsState.getInstallPermissionState(name) != null) { 4022 scheduleWriteSettingsLocked(); 4023 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4024 || hadState) { 4025 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4026 } 4027 } 4028 } 4029 } 4030 4031 /** 4032 * Update the permission flags for all packages and runtime permissions of a user in order 4033 * to allow device or profile owner to remove POLICY_FIXED. 4034 */ 4035 @Override 4036 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4037 if (!sUserManager.exists(userId)) { 4038 return; 4039 } 4040 4041 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4042 4043 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 4044 "updatePermissionFlagsForAllApps"); 4045 4046 // Only the system can change system fixed flags. 4047 if (getCallingUid() != Process.SYSTEM_UID) { 4048 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4049 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4050 } 4051 4052 synchronized (mPackages) { 4053 boolean changed = false; 4054 final int packageCount = mPackages.size(); 4055 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4056 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4057 SettingBase sb = (SettingBase) pkg.mExtras; 4058 if (sb == null) { 4059 continue; 4060 } 4061 PermissionsState permissionsState = sb.getPermissionsState(); 4062 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4063 userId, flagMask, flagValues); 4064 } 4065 if (changed) { 4066 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4067 } 4068 } 4069 } 4070 4071 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4072 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4073 != PackageManager.PERMISSION_GRANTED 4074 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4075 != PackageManager.PERMISSION_GRANTED) { 4076 throw new SecurityException(message + " requires " 4077 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4078 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4079 } 4080 } 4081 4082 @Override 4083 public boolean shouldShowRequestPermissionRationale(String permissionName, 4084 String packageName, int userId) { 4085 if (UserHandle.getCallingUserId() != userId) { 4086 mContext.enforceCallingPermission( 4087 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4088 "canShowRequestPermissionRationale for user " + userId); 4089 } 4090 4091 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4092 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4093 return false; 4094 } 4095 4096 if (checkPermission(permissionName, packageName, userId) 4097 == PackageManager.PERMISSION_GRANTED) { 4098 return false; 4099 } 4100 4101 final int flags; 4102 4103 final long identity = Binder.clearCallingIdentity(); 4104 try { 4105 flags = getPermissionFlags(permissionName, 4106 packageName, userId); 4107 } finally { 4108 Binder.restoreCallingIdentity(identity); 4109 } 4110 4111 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4112 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4113 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4114 4115 if ((flags & fixedFlags) != 0) { 4116 return false; 4117 } 4118 4119 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4120 } 4121 4122 @Override 4123 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4124 mContext.enforceCallingOrSelfPermission( 4125 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4126 "addOnPermissionsChangeListener"); 4127 4128 synchronized (mPackages) { 4129 mOnPermissionChangeListeners.addListenerLocked(listener); 4130 } 4131 } 4132 4133 @Override 4134 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4135 synchronized (mPackages) { 4136 mOnPermissionChangeListeners.removeListenerLocked(listener); 4137 } 4138 } 4139 4140 @Override 4141 public boolean isProtectedBroadcast(String actionName) { 4142 synchronized (mPackages) { 4143 if (mProtectedBroadcasts.contains(actionName)) { 4144 return true; 4145 } else if (actionName != null) { 4146 // TODO: remove these terrible hacks 4147 if (actionName.startsWith("android.net.netmon.lingerExpired") 4148 || actionName.startsWith("com.android.server.sip.SipWakeupTimer")) { 4149 return true; 4150 } 4151 } 4152 } 4153 return false; 4154 } 4155 4156 @Override 4157 public int checkSignatures(String pkg1, String pkg2) { 4158 synchronized (mPackages) { 4159 final PackageParser.Package p1 = mPackages.get(pkg1); 4160 final PackageParser.Package p2 = mPackages.get(pkg2); 4161 if (p1 == null || p1.mExtras == null 4162 || p2 == null || p2.mExtras == null) { 4163 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4164 } 4165 return compareSignatures(p1.mSignatures, p2.mSignatures); 4166 } 4167 } 4168 4169 @Override 4170 public int checkUidSignatures(int uid1, int uid2) { 4171 // Map to base uids. 4172 uid1 = UserHandle.getAppId(uid1); 4173 uid2 = UserHandle.getAppId(uid2); 4174 // reader 4175 synchronized (mPackages) { 4176 Signature[] s1; 4177 Signature[] s2; 4178 Object obj = mSettings.getUserIdLPr(uid1); 4179 if (obj != null) { 4180 if (obj instanceof SharedUserSetting) { 4181 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4182 } else if (obj instanceof PackageSetting) { 4183 s1 = ((PackageSetting)obj).signatures.mSignatures; 4184 } else { 4185 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4186 } 4187 } else { 4188 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4189 } 4190 obj = mSettings.getUserIdLPr(uid2); 4191 if (obj != null) { 4192 if (obj instanceof SharedUserSetting) { 4193 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4194 } else if (obj instanceof PackageSetting) { 4195 s2 = ((PackageSetting)obj).signatures.mSignatures; 4196 } else { 4197 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4198 } 4199 } else { 4200 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4201 } 4202 return compareSignatures(s1, s2); 4203 } 4204 } 4205 4206 private void killUid(int appId, int userId, String reason) { 4207 final long identity = Binder.clearCallingIdentity(); 4208 try { 4209 IActivityManager am = ActivityManagerNative.getDefault(); 4210 if (am != null) { 4211 try { 4212 am.killUid(appId, userId, reason); 4213 } catch (RemoteException e) { 4214 /* ignore - same process */ 4215 } 4216 } 4217 } finally { 4218 Binder.restoreCallingIdentity(identity); 4219 } 4220 } 4221 4222 /** 4223 * Compares two sets of signatures. Returns: 4224 * <br /> 4225 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4226 * <br /> 4227 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4228 * <br /> 4229 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4230 * <br /> 4231 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4232 * <br /> 4233 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4234 */ 4235 static int compareSignatures(Signature[] s1, Signature[] s2) { 4236 if (s1 == null) { 4237 return s2 == null 4238 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4239 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4240 } 4241 4242 if (s2 == null) { 4243 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4244 } 4245 4246 if (s1.length != s2.length) { 4247 return PackageManager.SIGNATURE_NO_MATCH; 4248 } 4249 4250 // Since both signature sets are of size 1, we can compare without HashSets. 4251 if (s1.length == 1) { 4252 return s1[0].equals(s2[0]) ? 4253 PackageManager.SIGNATURE_MATCH : 4254 PackageManager.SIGNATURE_NO_MATCH; 4255 } 4256 4257 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4258 for (Signature sig : s1) { 4259 set1.add(sig); 4260 } 4261 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4262 for (Signature sig : s2) { 4263 set2.add(sig); 4264 } 4265 // Make sure s2 contains all signatures in s1. 4266 if (set1.equals(set2)) { 4267 return PackageManager.SIGNATURE_MATCH; 4268 } 4269 return PackageManager.SIGNATURE_NO_MATCH; 4270 } 4271 4272 /** 4273 * If the database version for this type of package (internal storage or 4274 * external storage) is less than the version where package signatures 4275 * were updated, return true. 4276 */ 4277 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4278 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4279 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4280 } 4281 4282 /** 4283 * Used for backward compatibility to make sure any packages with 4284 * certificate chains get upgraded to the new style. {@code existingSigs} 4285 * will be in the old format (since they were stored on disk from before the 4286 * system upgrade) and {@code scannedSigs} will be in the newer format. 4287 */ 4288 private int compareSignaturesCompat(PackageSignatures existingSigs, 4289 PackageParser.Package scannedPkg) { 4290 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4291 return PackageManager.SIGNATURE_NO_MATCH; 4292 } 4293 4294 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4295 for (Signature sig : existingSigs.mSignatures) { 4296 existingSet.add(sig); 4297 } 4298 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4299 for (Signature sig : scannedPkg.mSignatures) { 4300 try { 4301 Signature[] chainSignatures = sig.getChainSignatures(); 4302 for (Signature chainSig : chainSignatures) { 4303 scannedCompatSet.add(chainSig); 4304 } 4305 } catch (CertificateEncodingException e) { 4306 scannedCompatSet.add(sig); 4307 } 4308 } 4309 /* 4310 * Make sure the expanded scanned set contains all signatures in the 4311 * existing one. 4312 */ 4313 if (scannedCompatSet.equals(existingSet)) { 4314 // Migrate the old signatures to the new scheme. 4315 existingSigs.assignSignatures(scannedPkg.mSignatures); 4316 // The new KeySets will be re-added later in the scanning process. 4317 synchronized (mPackages) { 4318 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4319 } 4320 return PackageManager.SIGNATURE_MATCH; 4321 } 4322 return PackageManager.SIGNATURE_NO_MATCH; 4323 } 4324 4325 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4326 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4327 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4328 } 4329 4330 private int compareSignaturesRecover(PackageSignatures existingSigs, 4331 PackageParser.Package scannedPkg) { 4332 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4333 return PackageManager.SIGNATURE_NO_MATCH; 4334 } 4335 4336 String msg = null; 4337 try { 4338 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4339 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4340 + scannedPkg.packageName); 4341 return PackageManager.SIGNATURE_MATCH; 4342 } 4343 } catch (CertificateException e) { 4344 msg = e.getMessage(); 4345 } 4346 4347 logCriticalInfo(Log.INFO, 4348 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4349 return PackageManager.SIGNATURE_NO_MATCH; 4350 } 4351 4352 @Override 4353 public String[] getPackagesForUid(int uid) { 4354 uid = UserHandle.getAppId(uid); 4355 // reader 4356 synchronized (mPackages) { 4357 Object obj = mSettings.getUserIdLPr(uid); 4358 if (obj instanceof SharedUserSetting) { 4359 final SharedUserSetting sus = (SharedUserSetting) obj; 4360 final int N = sus.packages.size(); 4361 final String[] res = new String[N]; 4362 final Iterator<PackageSetting> it = sus.packages.iterator(); 4363 int i = 0; 4364 while (it.hasNext()) { 4365 res[i++] = it.next().name; 4366 } 4367 return res; 4368 } else if (obj instanceof PackageSetting) { 4369 final PackageSetting ps = (PackageSetting) obj; 4370 return new String[] { ps.name }; 4371 } 4372 } 4373 return null; 4374 } 4375 4376 @Override 4377 public String getNameForUid(int uid) { 4378 // reader 4379 synchronized (mPackages) { 4380 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4381 if (obj instanceof SharedUserSetting) { 4382 final SharedUserSetting sus = (SharedUserSetting) obj; 4383 return sus.name + ":" + sus.userId; 4384 } else if (obj instanceof PackageSetting) { 4385 final PackageSetting ps = (PackageSetting) obj; 4386 return ps.name; 4387 } 4388 } 4389 return null; 4390 } 4391 4392 @Override 4393 public int getUidForSharedUser(String sharedUserName) { 4394 if(sharedUserName == null) { 4395 return -1; 4396 } 4397 // reader 4398 synchronized (mPackages) { 4399 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4400 if (suid == null) { 4401 return -1; 4402 } 4403 return suid.userId; 4404 } 4405 } 4406 4407 @Override 4408 public int getFlagsForUid(int uid) { 4409 synchronized (mPackages) { 4410 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4411 if (obj instanceof SharedUserSetting) { 4412 final SharedUserSetting sus = (SharedUserSetting) obj; 4413 return sus.pkgFlags; 4414 } else if (obj instanceof PackageSetting) { 4415 final PackageSetting ps = (PackageSetting) obj; 4416 return ps.pkgFlags; 4417 } 4418 } 4419 return 0; 4420 } 4421 4422 @Override 4423 public int getPrivateFlagsForUid(int uid) { 4424 synchronized (mPackages) { 4425 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4426 if (obj instanceof SharedUserSetting) { 4427 final SharedUserSetting sus = (SharedUserSetting) obj; 4428 return sus.pkgPrivateFlags; 4429 } else if (obj instanceof PackageSetting) { 4430 final PackageSetting ps = (PackageSetting) obj; 4431 return ps.pkgPrivateFlags; 4432 } 4433 } 4434 return 0; 4435 } 4436 4437 @Override 4438 public boolean isUidPrivileged(int uid) { 4439 uid = UserHandle.getAppId(uid); 4440 // reader 4441 synchronized (mPackages) { 4442 Object obj = mSettings.getUserIdLPr(uid); 4443 if (obj instanceof SharedUserSetting) { 4444 final SharedUserSetting sus = (SharedUserSetting) obj; 4445 final Iterator<PackageSetting> it = sus.packages.iterator(); 4446 while (it.hasNext()) { 4447 if (it.next().isPrivileged()) { 4448 return true; 4449 } 4450 } 4451 } else if (obj instanceof PackageSetting) { 4452 final PackageSetting ps = (PackageSetting) obj; 4453 return ps.isPrivileged(); 4454 } 4455 } 4456 return false; 4457 } 4458 4459 @Override 4460 public String[] getAppOpPermissionPackages(String permissionName) { 4461 synchronized (mPackages) { 4462 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4463 if (pkgs == null) { 4464 return null; 4465 } 4466 return pkgs.toArray(new String[pkgs.size()]); 4467 } 4468 } 4469 4470 @Override 4471 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4472 int flags, int userId) { 4473 if (!sUserManager.exists(userId)) return null; 4474 flags = updateFlagsForResolve(flags, userId, intent); 4475 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4476 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4477 final ResolveInfo bestChoice = 4478 chooseBestActivity(intent, resolvedType, flags, query, userId); 4479 4480 if (isEphemeralAllowed(intent, query, userId)) { 4481 final EphemeralResolveInfo ai = 4482 getEphemeralResolveInfo(intent, resolvedType, userId); 4483 if (ai != null) { 4484 if (DEBUG_EPHEMERAL) { 4485 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4486 } 4487 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4488 bestChoice.ephemeralResolveInfo = ai; 4489 } 4490 } 4491 return bestChoice; 4492 } 4493 4494 @Override 4495 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4496 IntentFilter filter, int match, ComponentName activity) { 4497 final int userId = UserHandle.getCallingUserId(); 4498 if (DEBUG_PREFERRED) { 4499 Log.v(TAG, "setLastChosenActivity intent=" + intent 4500 + " resolvedType=" + resolvedType 4501 + " flags=" + flags 4502 + " filter=" + filter 4503 + " match=" + match 4504 + " activity=" + activity); 4505 filter.dump(new PrintStreamPrinter(System.out), " "); 4506 } 4507 intent.setComponent(null); 4508 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4509 // Find any earlier preferred or last chosen entries and nuke them 4510 findPreferredActivity(intent, resolvedType, 4511 flags, query, 0, false, true, false, userId); 4512 // Add the new activity as the last chosen for this filter 4513 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4514 "Setting last chosen"); 4515 } 4516 4517 @Override 4518 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4519 final int userId = UserHandle.getCallingUserId(); 4520 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4521 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4522 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4523 false, false, false, userId); 4524 } 4525 4526 4527 private boolean isEphemeralAllowed( 4528 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4529 // Short circuit and return early if possible. 4530 if (DISABLE_EPHEMERAL_APPS) { 4531 return false; 4532 } 4533 final int callingUser = UserHandle.getCallingUserId(); 4534 if (callingUser != UserHandle.USER_SYSTEM) { 4535 return false; 4536 } 4537 if (mEphemeralResolverConnection == null) { 4538 return false; 4539 } 4540 if (intent.getComponent() != null) { 4541 return false; 4542 } 4543 if (intent.getPackage() != null) { 4544 return false; 4545 } 4546 final boolean isWebUri = hasWebURI(intent); 4547 if (!isWebUri) { 4548 return false; 4549 } 4550 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4551 synchronized (mPackages) { 4552 final int count = resolvedActivites.size(); 4553 for (int n = 0; n < count; n++) { 4554 ResolveInfo info = resolvedActivites.get(n); 4555 String packageName = info.activityInfo.packageName; 4556 PackageSetting ps = mSettings.mPackages.get(packageName); 4557 if (ps != null) { 4558 // Try to get the status from User settings first 4559 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4560 int status = (int) (packedStatus >> 32); 4561 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4562 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4563 if (DEBUG_EPHEMERAL) { 4564 Slog.v(TAG, "DENY ephemeral apps;" 4565 + " pkg: " + packageName + ", status: " + status); 4566 } 4567 return false; 4568 } 4569 } 4570 } 4571 } 4572 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4573 return true; 4574 } 4575 4576 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4577 int userId) { 4578 MessageDigest digest = null; 4579 try { 4580 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4581 } catch (NoSuchAlgorithmException e) { 4582 // If we can't create a digest, ignore ephemeral apps. 4583 return null; 4584 } 4585 4586 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4587 final byte[] digestBytes = digest.digest(hostBytes); 4588 int shaPrefix = 4589 digestBytes[0] << 24 4590 | digestBytes[1] << 16 4591 | digestBytes[2] << 8 4592 | digestBytes[3] << 0; 4593 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4594 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4595 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4596 // No hash prefix match; there are no ephemeral apps for this domain. 4597 return null; 4598 } 4599 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4600 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4601 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4602 continue; 4603 } 4604 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4605 // No filters; this should never happen. 4606 if (filters.isEmpty()) { 4607 continue; 4608 } 4609 // We have a domain match; resolve the filters to see if anything matches. 4610 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4611 for (int j = filters.size() - 1; j >= 0; --j) { 4612 final EphemeralResolveIntentInfo intentInfo = 4613 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4614 ephemeralResolver.addFilter(intentInfo); 4615 } 4616 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4617 intent, resolvedType, false /*defaultOnly*/, userId); 4618 if (!matchedResolveInfoList.isEmpty()) { 4619 return matchedResolveInfoList.get(0); 4620 } 4621 } 4622 // Hash or filter mis-match; no ephemeral apps for this domain. 4623 return null; 4624 } 4625 4626 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4627 int flags, List<ResolveInfo> query, int userId) { 4628 if (query != null) { 4629 final int N = query.size(); 4630 if (N == 1) { 4631 return query.get(0); 4632 } else if (N > 1) { 4633 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4634 // If there is more than one activity with the same priority, 4635 // then let the user decide between them. 4636 ResolveInfo r0 = query.get(0); 4637 ResolveInfo r1 = query.get(1); 4638 if (DEBUG_INTENT_MATCHING || debug) { 4639 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4640 + r1.activityInfo.name + "=" + r1.priority); 4641 } 4642 // If the first activity has a higher priority, or a different 4643 // default, then it is always desirable to pick it. 4644 if (r0.priority != r1.priority 4645 || r0.preferredOrder != r1.preferredOrder 4646 || r0.isDefault != r1.isDefault) { 4647 return query.get(0); 4648 } 4649 // If we have saved a preference for a preferred activity for 4650 // this Intent, use that. 4651 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4652 flags, query, r0.priority, true, false, debug, userId); 4653 if (ri != null) { 4654 return ri; 4655 } 4656 ri = new ResolveInfo(mResolveInfo); 4657 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4658 ri.activityInfo.applicationInfo = new ApplicationInfo( 4659 ri.activityInfo.applicationInfo); 4660 if (userId != 0) { 4661 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4662 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4663 } 4664 // Make sure that the resolver is displayable in car mode 4665 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4666 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4667 return ri; 4668 } 4669 } 4670 return null; 4671 } 4672 4673 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4674 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4675 final int N = query.size(); 4676 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4677 .get(userId); 4678 // Get the list of persistent preferred activities that handle the intent 4679 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4680 List<PersistentPreferredActivity> pprefs = ppir != null 4681 ? ppir.queryIntent(intent, resolvedType, 4682 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4683 : null; 4684 if (pprefs != null && pprefs.size() > 0) { 4685 final int M = pprefs.size(); 4686 for (int i=0; i<M; i++) { 4687 final PersistentPreferredActivity ppa = pprefs.get(i); 4688 if (DEBUG_PREFERRED || debug) { 4689 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4690 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4691 + "\n component=" + ppa.mComponent); 4692 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4693 } 4694 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4695 flags | MATCH_DISABLED_COMPONENTS, userId); 4696 if (DEBUG_PREFERRED || debug) { 4697 Slog.v(TAG, "Found persistent preferred activity:"); 4698 if (ai != null) { 4699 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4700 } else { 4701 Slog.v(TAG, " null"); 4702 } 4703 } 4704 if (ai == null) { 4705 // This previously registered persistent preferred activity 4706 // component is no longer known. Ignore it and do NOT remove it. 4707 continue; 4708 } 4709 for (int j=0; j<N; j++) { 4710 final ResolveInfo ri = query.get(j); 4711 if (!ri.activityInfo.applicationInfo.packageName 4712 .equals(ai.applicationInfo.packageName)) { 4713 continue; 4714 } 4715 if (!ri.activityInfo.name.equals(ai.name)) { 4716 continue; 4717 } 4718 // Found a persistent preference that can handle the intent. 4719 if (DEBUG_PREFERRED || debug) { 4720 Slog.v(TAG, "Returning persistent preferred activity: " + 4721 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4722 } 4723 return ri; 4724 } 4725 } 4726 } 4727 return null; 4728 } 4729 4730 // TODO: handle preferred activities missing while user has amnesia 4731 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4732 List<ResolveInfo> query, int priority, boolean always, 4733 boolean removeMatches, boolean debug, int userId) { 4734 if (!sUserManager.exists(userId)) return null; 4735 flags = updateFlagsForResolve(flags, userId, intent); 4736 // writer 4737 synchronized (mPackages) { 4738 if (intent.getSelector() != null) { 4739 intent = intent.getSelector(); 4740 } 4741 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4742 4743 // Try to find a matching persistent preferred activity. 4744 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4745 debug, userId); 4746 4747 // If a persistent preferred activity matched, use it. 4748 if (pri != null) { 4749 return pri; 4750 } 4751 4752 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4753 // Get the list of preferred activities that handle the intent 4754 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4755 List<PreferredActivity> prefs = pir != null 4756 ? pir.queryIntent(intent, resolvedType, 4757 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4758 : null; 4759 if (prefs != null && prefs.size() > 0) { 4760 boolean changed = false; 4761 try { 4762 // First figure out how good the original match set is. 4763 // We will only allow preferred activities that came 4764 // from the same match quality. 4765 int match = 0; 4766 4767 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4768 4769 final int N = query.size(); 4770 for (int j=0; j<N; j++) { 4771 final ResolveInfo ri = query.get(j); 4772 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4773 + ": 0x" + Integer.toHexString(match)); 4774 if (ri.match > match) { 4775 match = ri.match; 4776 } 4777 } 4778 4779 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4780 + Integer.toHexString(match)); 4781 4782 match &= IntentFilter.MATCH_CATEGORY_MASK; 4783 final int M = prefs.size(); 4784 for (int i=0; i<M; i++) { 4785 final PreferredActivity pa = prefs.get(i); 4786 if (DEBUG_PREFERRED || debug) { 4787 Slog.v(TAG, "Checking PreferredActivity ds=" 4788 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4789 + "\n component=" + pa.mPref.mComponent); 4790 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4791 } 4792 if (pa.mPref.mMatch != match) { 4793 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4794 + Integer.toHexString(pa.mPref.mMatch)); 4795 continue; 4796 } 4797 // If it's not an "always" type preferred activity and that's what we're 4798 // looking for, skip it. 4799 if (always && !pa.mPref.mAlways) { 4800 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4801 continue; 4802 } 4803 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4804 flags | MATCH_DISABLED_COMPONENTS, userId); 4805 if (DEBUG_PREFERRED || debug) { 4806 Slog.v(TAG, "Found preferred activity:"); 4807 if (ai != null) { 4808 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4809 } else { 4810 Slog.v(TAG, " null"); 4811 } 4812 } 4813 if (ai == null) { 4814 // This previously registered preferred activity 4815 // component is no longer known. Most likely an update 4816 // to the app was installed and in the new version this 4817 // component no longer exists. Clean it up by removing 4818 // it from the preferred activities list, and skip it. 4819 Slog.w(TAG, "Removing dangling preferred activity: " 4820 + pa.mPref.mComponent); 4821 pir.removeFilter(pa); 4822 changed = true; 4823 continue; 4824 } 4825 for (int j=0; j<N; j++) { 4826 final ResolveInfo ri = query.get(j); 4827 if (!ri.activityInfo.applicationInfo.packageName 4828 .equals(ai.applicationInfo.packageName)) { 4829 continue; 4830 } 4831 if (!ri.activityInfo.name.equals(ai.name)) { 4832 continue; 4833 } 4834 4835 if (removeMatches) { 4836 pir.removeFilter(pa); 4837 changed = true; 4838 if (DEBUG_PREFERRED) { 4839 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4840 } 4841 break; 4842 } 4843 4844 // Okay we found a previously set preferred or last chosen app. 4845 // If the result set is different from when this 4846 // was created, we need to clear it and re-ask the 4847 // user their preference, if we're looking for an "always" type entry. 4848 if (always && !pa.mPref.sameSet(query)) { 4849 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4850 + intent + " type " + resolvedType); 4851 if (DEBUG_PREFERRED) { 4852 Slog.v(TAG, "Removing preferred activity since set changed " 4853 + pa.mPref.mComponent); 4854 } 4855 pir.removeFilter(pa); 4856 // Re-add the filter as a "last chosen" entry (!always) 4857 PreferredActivity lastChosen = new PreferredActivity( 4858 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4859 pir.addFilter(lastChosen); 4860 changed = true; 4861 return null; 4862 } 4863 4864 // Yay! Either the set matched or we're looking for the last chosen 4865 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4866 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4867 return ri; 4868 } 4869 } 4870 } finally { 4871 if (changed) { 4872 if (DEBUG_PREFERRED) { 4873 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4874 } 4875 scheduleWritePackageRestrictionsLocked(userId); 4876 } 4877 } 4878 } 4879 } 4880 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4881 return null; 4882 } 4883 4884 /* 4885 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4886 */ 4887 @Override 4888 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4889 int targetUserId) { 4890 mContext.enforceCallingOrSelfPermission( 4891 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4892 List<CrossProfileIntentFilter> matches = 4893 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4894 if (matches != null) { 4895 int size = matches.size(); 4896 for (int i = 0; i < size; i++) { 4897 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4898 } 4899 } 4900 if (hasWebURI(intent)) { 4901 // cross-profile app linking works only towards the parent. 4902 final UserInfo parent = getProfileParent(sourceUserId); 4903 synchronized(mPackages) { 4904 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4905 intent, resolvedType, 0, sourceUserId, parent.id); 4906 return xpDomainInfo != null; 4907 } 4908 } 4909 return false; 4910 } 4911 4912 private UserInfo getProfileParent(int userId) { 4913 final long identity = Binder.clearCallingIdentity(); 4914 try { 4915 return sUserManager.getProfileParent(userId); 4916 } finally { 4917 Binder.restoreCallingIdentity(identity); 4918 } 4919 } 4920 4921 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4922 String resolvedType, int userId) { 4923 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4924 if (resolver != null) { 4925 return resolver.queryIntent(intent, resolvedType, false, userId); 4926 } 4927 return null; 4928 } 4929 4930 @Override 4931 public List<ResolveInfo> queryIntentActivities(Intent intent, 4932 String resolvedType, int flags, int userId) { 4933 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4934 flags = updateFlagsForResolve(flags, userId, intent); 4935 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4936 ComponentName comp = intent.getComponent(); 4937 if (comp == null) { 4938 if (intent.getSelector() != null) { 4939 intent = intent.getSelector(); 4940 comp = intent.getComponent(); 4941 } 4942 } 4943 4944 if (comp != null) { 4945 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4946 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4947 if (ai != null) { 4948 final ResolveInfo ri = new ResolveInfo(); 4949 ri.activityInfo = ai; 4950 list.add(ri); 4951 } 4952 return list; 4953 } 4954 4955 // reader 4956 synchronized (mPackages) { 4957 final String pkgName = intent.getPackage(); 4958 if (pkgName == null) { 4959 List<CrossProfileIntentFilter> matchingFilters = 4960 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4961 // Check for results that need to skip the current profile. 4962 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4963 resolvedType, flags, userId); 4964 if (xpResolveInfo != null) { 4965 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4966 result.add(xpResolveInfo); 4967 return filterIfNotSystemUser(result, userId); 4968 } 4969 4970 // Check for results in the current profile. 4971 List<ResolveInfo> result = mActivities.queryIntent( 4972 intent, resolvedType, flags, userId); 4973 result = filterIfNotSystemUser(result, userId); 4974 4975 // Check for cross profile results. 4976 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 4977 xpResolveInfo = queryCrossProfileIntents( 4978 matchingFilters, intent, resolvedType, flags, userId, 4979 hasNonNegativePriorityResult); 4980 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4981 boolean isVisibleToUser = filterIfNotSystemUser( 4982 Collections.singletonList(xpResolveInfo), userId).size() > 0; 4983 if (isVisibleToUser) { 4984 result.add(xpResolveInfo); 4985 Collections.sort(result, mResolvePrioritySorter); 4986 } 4987 } 4988 if (hasWebURI(intent)) { 4989 CrossProfileDomainInfo xpDomainInfo = null; 4990 final UserInfo parent = getProfileParent(userId); 4991 if (parent != null) { 4992 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4993 flags, userId, parent.id); 4994 } 4995 if (xpDomainInfo != null) { 4996 if (xpResolveInfo != null) { 4997 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4998 // in the result. 4999 result.remove(xpResolveInfo); 5000 } 5001 if (result.size() == 0) { 5002 result.add(xpDomainInfo.resolveInfo); 5003 return result; 5004 } 5005 } else if (result.size() <= 1) { 5006 return result; 5007 } 5008 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5009 xpDomainInfo, userId); 5010 Collections.sort(result, mResolvePrioritySorter); 5011 } 5012 return result; 5013 } 5014 final PackageParser.Package pkg = mPackages.get(pkgName); 5015 if (pkg != null) { 5016 return filterIfNotSystemUser( 5017 mActivities.queryIntentForPackage( 5018 intent, resolvedType, flags, pkg.activities, userId), 5019 userId); 5020 } 5021 return new ArrayList<ResolveInfo>(); 5022 } 5023 } 5024 5025 private static class CrossProfileDomainInfo { 5026 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5027 ResolveInfo resolveInfo; 5028 /* Best domain verification status of the activities found in the other profile */ 5029 int bestDomainVerificationStatus; 5030 } 5031 5032 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5033 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5034 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5035 sourceUserId)) { 5036 return null; 5037 } 5038 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5039 resolvedType, flags, parentUserId); 5040 5041 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5042 return null; 5043 } 5044 CrossProfileDomainInfo result = null; 5045 int size = resultTargetUser.size(); 5046 for (int i = 0; i < size; i++) { 5047 ResolveInfo riTargetUser = resultTargetUser.get(i); 5048 // Intent filter verification is only for filters that specify a host. So don't return 5049 // those that handle all web uris. 5050 if (riTargetUser.handleAllWebDataURI) { 5051 continue; 5052 } 5053 String packageName = riTargetUser.activityInfo.packageName; 5054 PackageSetting ps = mSettings.mPackages.get(packageName); 5055 if (ps == null) { 5056 continue; 5057 } 5058 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5059 int status = (int)(verificationState >> 32); 5060 if (result == null) { 5061 result = new CrossProfileDomainInfo(); 5062 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5063 sourceUserId, parentUserId); 5064 result.bestDomainVerificationStatus = status; 5065 } else { 5066 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5067 result.bestDomainVerificationStatus); 5068 } 5069 } 5070 // Don't consider matches with status NEVER across profiles. 5071 if (result != null && result.bestDomainVerificationStatus 5072 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5073 return null; 5074 } 5075 return result; 5076 } 5077 5078 /** 5079 * Verification statuses are ordered from the worse to the best, except for 5080 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5081 */ 5082 private int bestDomainVerificationStatus(int status1, int status2) { 5083 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5084 return status2; 5085 } 5086 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5087 return status1; 5088 } 5089 return (int) MathUtils.max(status1, status2); 5090 } 5091 5092 private boolean isUserEnabled(int userId) { 5093 long callingId = Binder.clearCallingIdentity(); 5094 try { 5095 UserInfo userInfo = sUserManager.getUserInfo(userId); 5096 return userInfo != null && userInfo.isEnabled(); 5097 } finally { 5098 Binder.restoreCallingIdentity(callingId); 5099 } 5100 } 5101 5102 /** 5103 * Filter out activities with systemUserOnly flag set, when current user is not System. 5104 * 5105 * @return filtered list 5106 */ 5107 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5108 if (userId == UserHandle.USER_SYSTEM) { 5109 return resolveInfos; 5110 } 5111 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5112 ResolveInfo info = resolveInfos.get(i); 5113 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5114 resolveInfos.remove(i); 5115 } 5116 } 5117 return resolveInfos; 5118 } 5119 5120 /** 5121 * @param resolveInfos list of resolve infos in descending priority order 5122 * @return if the list contains a resolve info with non-negative priority 5123 */ 5124 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5125 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5126 } 5127 5128 private static boolean hasWebURI(Intent intent) { 5129 if (intent.getData() == null) { 5130 return false; 5131 } 5132 final String scheme = intent.getScheme(); 5133 if (TextUtils.isEmpty(scheme)) { 5134 return false; 5135 } 5136 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5137 } 5138 5139 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5140 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5141 int userId) { 5142 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5143 5144 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5145 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5146 candidates.size()); 5147 } 5148 5149 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5150 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5151 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5152 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5153 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5154 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5155 5156 synchronized (mPackages) { 5157 final int count = candidates.size(); 5158 // First, try to use linked apps. Partition the candidates into four lists: 5159 // one for the final results, one for the "do not use ever", one for "undefined status" 5160 // and finally one for "browser app type". 5161 for (int n=0; n<count; n++) { 5162 ResolveInfo info = candidates.get(n); 5163 String packageName = info.activityInfo.packageName; 5164 PackageSetting ps = mSettings.mPackages.get(packageName); 5165 if (ps != null) { 5166 // Add to the special match all list (Browser use case) 5167 if (info.handleAllWebDataURI) { 5168 matchAllList.add(info); 5169 continue; 5170 } 5171 // Try to get the status from User settings first 5172 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5173 int status = (int)(packedStatus >> 32); 5174 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5175 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5176 if (DEBUG_DOMAIN_VERIFICATION) { 5177 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5178 + " : linkgen=" + linkGeneration); 5179 } 5180 // Use link-enabled generation as preferredOrder, i.e. 5181 // prefer newly-enabled over earlier-enabled. 5182 info.preferredOrder = linkGeneration; 5183 alwaysList.add(info); 5184 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5185 if (DEBUG_DOMAIN_VERIFICATION) { 5186 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5187 } 5188 neverList.add(info); 5189 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5190 if (DEBUG_DOMAIN_VERIFICATION) { 5191 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5192 } 5193 alwaysAskList.add(info); 5194 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5195 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5196 if (DEBUG_DOMAIN_VERIFICATION) { 5197 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5198 } 5199 undefinedList.add(info); 5200 } 5201 } 5202 } 5203 5204 // We'll want to include browser possibilities in a few cases 5205 boolean includeBrowser = false; 5206 5207 // First try to add the "always" resolution(s) for the current user, if any 5208 if (alwaysList.size() > 0) { 5209 result.addAll(alwaysList); 5210 } else { 5211 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5212 result.addAll(undefinedList); 5213 // Maybe add one for the other profile. 5214 if (xpDomainInfo != null && ( 5215 xpDomainInfo.bestDomainVerificationStatus 5216 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5217 result.add(xpDomainInfo.resolveInfo); 5218 } 5219 includeBrowser = true; 5220 } 5221 5222 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5223 // If there were 'always' entries their preferred order has been set, so we also 5224 // back that off to make the alternatives equivalent 5225 if (alwaysAskList.size() > 0) { 5226 for (ResolveInfo i : result) { 5227 i.preferredOrder = 0; 5228 } 5229 result.addAll(alwaysAskList); 5230 includeBrowser = true; 5231 } 5232 5233 if (includeBrowser) { 5234 // Also add browsers (all of them or only the default one) 5235 if (DEBUG_DOMAIN_VERIFICATION) { 5236 Slog.v(TAG, " ...including browsers in candidate set"); 5237 } 5238 if ((matchFlags & MATCH_ALL) != 0) { 5239 result.addAll(matchAllList); 5240 } else { 5241 // Browser/generic handling case. If there's a default browser, go straight 5242 // to that (but only if there is no other higher-priority match). 5243 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5244 int maxMatchPrio = 0; 5245 ResolveInfo defaultBrowserMatch = null; 5246 final int numCandidates = matchAllList.size(); 5247 for (int n = 0; n < numCandidates; n++) { 5248 ResolveInfo info = matchAllList.get(n); 5249 // track the highest overall match priority... 5250 if (info.priority > maxMatchPrio) { 5251 maxMatchPrio = info.priority; 5252 } 5253 // ...and the highest-priority default browser match 5254 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5255 if (defaultBrowserMatch == null 5256 || (defaultBrowserMatch.priority < info.priority)) { 5257 if (debug) { 5258 Slog.v(TAG, "Considering default browser match " + info); 5259 } 5260 defaultBrowserMatch = info; 5261 } 5262 } 5263 } 5264 if (defaultBrowserMatch != null 5265 && defaultBrowserMatch.priority >= maxMatchPrio 5266 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5267 { 5268 if (debug) { 5269 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5270 } 5271 result.add(defaultBrowserMatch); 5272 } else { 5273 result.addAll(matchAllList); 5274 } 5275 } 5276 5277 // If there is nothing selected, add all candidates and remove the ones that the user 5278 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5279 if (result.size() == 0) { 5280 result.addAll(candidates); 5281 result.removeAll(neverList); 5282 } 5283 } 5284 } 5285 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5286 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5287 result.size()); 5288 for (ResolveInfo info : result) { 5289 Slog.v(TAG, " + " + info.activityInfo); 5290 } 5291 } 5292 return result; 5293 } 5294 5295 // Returns a packed value as a long: 5296 // 5297 // high 'int'-sized word: link status: undefined/ask/never/always. 5298 // low 'int'-sized word: relative priority among 'always' results. 5299 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5300 long result = ps.getDomainVerificationStatusForUser(userId); 5301 // if none available, get the master status 5302 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5303 if (ps.getIntentFilterVerificationInfo() != null) { 5304 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5305 } 5306 } 5307 return result; 5308 } 5309 5310 private ResolveInfo querySkipCurrentProfileIntents( 5311 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5312 int flags, int sourceUserId) { 5313 if (matchingFilters != null) { 5314 int size = matchingFilters.size(); 5315 for (int i = 0; i < size; i ++) { 5316 CrossProfileIntentFilter filter = matchingFilters.get(i); 5317 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5318 // Checking if there are activities in the target user that can handle the 5319 // intent. 5320 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5321 resolvedType, flags, sourceUserId); 5322 if (resolveInfo != null) { 5323 return resolveInfo; 5324 } 5325 } 5326 } 5327 } 5328 return null; 5329 } 5330 5331 // Return matching ResolveInfo in target user if any. 5332 private ResolveInfo queryCrossProfileIntents( 5333 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5334 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5335 if (matchingFilters != null) { 5336 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5337 // match the same intent. For performance reasons, it is better not to 5338 // run queryIntent twice for the same userId 5339 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5340 int size = matchingFilters.size(); 5341 for (int i = 0; i < size; i++) { 5342 CrossProfileIntentFilter filter = matchingFilters.get(i); 5343 int targetUserId = filter.getTargetUserId(); 5344 boolean skipCurrentProfile = 5345 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5346 boolean skipCurrentProfileIfNoMatchFound = 5347 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5348 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5349 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5350 // Checking if there are activities in the target user that can handle the 5351 // intent. 5352 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5353 resolvedType, flags, sourceUserId); 5354 if (resolveInfo != null) return resolveInfo; 5355 alreadyTriedUserIds.put(targetUserId, true); 5356 } 5357 } 5358 } 5359 return null; 5360 } 5361 5362 /** 5363 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5364 * will forward the intent to the filter's target user. 5365 * Otherwise, returns null. 5366 */ 5367 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5368 String resolvedType, int flags, int sourceUserId) { 5369 int targetUserId = filter.getTargetUserId(); 5370 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5371 resolvedType, flags, targetUserId); 5372 if (resultTargetUser != null && !resultTargetUser.isEmpty() 5373 && isUserEnabled(targetUserId)) { 5374 return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId); 5375 } 5376 return null; 5377 } 5378 5379 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5380 int sourceUserId, int targetUserId) { 5381 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5382 long ident = Binder.clearCallingIdentity(); 5383 boolean targetIsProfile; 5384 try { 5385 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5386 } finally { 5387 Binder.restoreCallingIdentity(ident); 5388 } 5389 String className; 5390 if (targetIsProfile) { 5391 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5392 } else { 5393 className = FORWARD_INTENT_TO_PARENT; 5394 } 5395 ComponentName forwardingActivityComponentName = new ComponentName( 5396 mAndroidApplication.packageName, className); 5397 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5398 sourceUserId); 5399 if (!targetIsProfile) { 5400 forwardingActivityInfo.showUserIcon = targetUserId; 5401 forwardingResolveInfo.noResourceId = true; 5402 } 5403 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5404 forwardingResolveInfo.priority = 0; 5405 forwardingResolveInfo.preferredOrder = 0; 5406 forwardingResolveInfo.match = 0; 5407 forwardingResolveInfo.isDefault = true; 5408 forwardingResolveInfo.filter = filter; 5409 forwardingResolveInfo.targetUserId = targetUserId; 5410 return forwardingResolveInfo; 5411 } 5412 5413 @Override 5414 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5415 Intent[] specifics, String[] specificTypes, Intent intent, 5416 String resolvedType, int flags, int userId) { 5417 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5418 flags = updateFlagsForResolve(flags, userId, intent); 5419 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 5420 false, "query intent activity options"); 5421 final String resultsAction = intent.getAction(); 5422 5423 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 5424 | PackageManager.GET_RESOLVED_FILTER, userId); 5425 5426 if (DEBUG_INTENT_MATCHING) { 5427 Log.v(TAG, "Query " + intent + ": " + results); 5428 } 5429 5430 int specificsPos = 0; 5431 int N; 5432 5433 // todo: note that the algorithm used here is O(N^2). This 5434 // isn't a problem in our current environment, but if we start running 5435 // into situations where we have more than 5 or 10 matches then this 5436 // should probably be changed to something smarter... 5437 5438 // First we go through and resolve each of the specific items 5439 // that were supplied, taking care of removing any corresponding 5440 // duplicate items in the generic resolve list. 5441 if (specifics != null) { 5442 for (int i=0; i<specifics.length; i++) { 5443 final Intent sintent = specifics[i]; 5444 if (sintent == null) { 5445 continue; 5446 } 5447 5448 if (DEBUG_INTENT_MATCHING) { 5449 Log.v(TAG, "Specific #" + i + ": " + sintent); 5450 } 5451 5452 String action = sintent.getAction(); 5453 if (resultsAction != null && resultsAction.equals(action)) { 5454 // If this action was explicitly requested, then don't 5455 // remove things that have it. 5456 action = null; 5457 } 5458 5459 ResolveInfo ri = null; 5460 ActivityInfo ai = null; 5461 5462 ComponentName comp = sintent.getComponent(); 5463 if (comp == null) { 5464 ri = resolveIntent( 5465 sintent, 5466 specificTypes != null ? specificTypes[i] : null, 5467 flags, userId); 5468 if (ri == null) { 5469 continue; 5470 } 5471 if (ri == mResolveInfo) { 5472 // ACK! Must do something better with this. 5473 } 5474 ai = ri.activityInfo; 5475 comp = new ComponentName(ai.applicationInfo.packageName, 5476 ai.name); 5477 } else { 5478 ai = getActivityInfo(comp, flags, userId); 5479 if (ai == null) { 5480 continue; 5481 } 5482 } 5483 5484 // Look for any generic query activities that are duplicates 5485 // of this specific one, and remove them from the results. 5486 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5487 N = results.size(); 5488 int j; 5489 for (j=specificsPos; j<N; j++) { 5490 ResolveInfo sri = results.get(j); 5491 if ((sri.activityInfo.name.equals(comp.getClassName()) 5492 && sri.activityInfo.applicationInfo.packageName.equals( 5493 comp.getPackageName())) 5494 || (action != null && sri.filter.matchAction(action))) { 5495 results.remove(j); 5496 if (DEBUG_INTENT_MATCHING) Log.v( 5497 TAG, "Removing duplicate item from " + j 5498 + " due to specific " + specificsPos); 5499 if (ri == null) { 5500 ri = sri; 5501 } 5502 j--; 5503 N--; 5504 } 5505 } 5506 5507 // Add this specific item to its proper place. 5508 if (ri == null) { 5509 ri = new ResolveInfo(); 5510 ri.activityInfo = ai; 5511 } 5512 results.add(specificsPos, ri); 5513 ri.specificIndex = i; 5514 specificsPos++; 5515 } 5516 } 5517 5518 // Now we go through the remaining generic results and remove any 5519 // duplicate actions that are found here. 5520 N = results.size(); 5521 for (int i=specificsPos; i<N-1; i++) { 5522 final ResolveInfo rii = results.get(i); 5523 if (rii.filter == null) { 5524 continue; 5525 } 5526 5527 // Iterate over all of the actions of this result's intent 5528 // filter... typically this should be just one. 5529 final Iterator<String> it = rii.filter.actionsIterator(); 5530 if (it == null) { 5531 continue; 5532 } 5533 while (it.hasNext()) { 5534 final String action = it.next(); 5535 if (resultsAction != null && resultsAction.equals(action)) { 5536 // If this action was explicitly requested, then don't 5537 // remove things that have it. 5538 continue; 5539 } 5540 for (int j=i+1; j<N; j++) { 5541 final ResolveInfo rij = results.get(j); 5542 if (rij.filter != null && rij.filter.hasAction(action)) { 5543 results.remove(j); 5544 if (DEBUG_INTENT_MATCHING) Log.v( 5545 TAG, "Removing duplicate item from " + j 5546 + " due to action " + action + " at " + i); 5547 j--; 5548 N--; 5549 } 5550 } 5551 } 5552 5553 // If the caller didn't request filter information, drop it now 5554 // so we don't have to marshall/unmarshall it. 5555 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5556 rii.filter = null; 5557 } 5558 } 5559 5560 // Filter out the caller activity if so requested. 5561 if (caller != null) { 5562 N = results.size(); 5563 for (int i=0; i<N; i++) { 5564 ActivityInfo ainfo = results.get(i).activityInfo; 5565 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5566 && caller.getClassName().equals(ainfo.name)) { 5567 results.remove(i); 5568 break; 5569 } 5570 } 5571 } 5572 5573 // If the caller didn't request filter information, 5574 // drop them now so we don't have to 5575 // marshall/unmarshall it. 5576 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5577 N = results.size(); 5578 for (int i=0; i<N; i++) { 5579 results.get(i).filter = null; 5580 } 5581 } 5582 5583 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5584 return results; 5585 } 5586 5587 @Override 5588 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5589 int userId) { 5590 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5591 flags = updateFlagsForResolve(flags, userId, intent); 5592 ComponentName comp = intent.getComponent(); 5593 if (comp == null) { 5594 if (intent.getSelector() != null) { 5595 intent = intent.getSelector(); 5596 comp = intent.getComponent(); 5597 } 5598 } 5599 if (comp != null) { 5600 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5601 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5602 if (ai != null) { 5603 ResolveInfo ri = new ResolveInfo(); 5604 ri.activityInfo = ai; 5605 list.add(ri); 5606 } 5607 return list; 5608 } 5609 5610 // reader 5611 synchronized (mPackages) { 5612 String pkgName = intent.getPackage(); 5613 if (pkgName == null) { 5614 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5615 } 5616 final PackageParser.Package pkg = mPackages.get(pkgName); 5617 if (pkg != null) { 5618 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5619 userId); 5620 } 5621 return null; 5622 } 5623 } 5624 5625 @Override 5626 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5627 if (!sUserManager.exists(userId)) return null; 5628 flags = updateFlagsForResolve(flags, userId, intent); 5629 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5630 if (query != null) { 5631 if (query.size() >= 1) { 5632 // If there is more than one service with the same priority, 5633 // just arbitrarily pick the first one. 5634 return query.get(0); 5635 } 5636 } 5637 return null; 5638 } 5639 5640 @Override 5641 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5642 int userId) { 5643 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5644 flags = updateFlagsForResolve(flags, userId, intent); 5645 ComponentName comp = intent.getComponent(); 5646 if (comp == null) { 5647 if (intent.getSelector() != null) { 5648 intent = intent.getSelector(); 5649 comp = intent.getComponent(); 5650 } 5651 } 5652 if (comp != null) { 5653 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5654 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5655 if (si != null) { 5656 final ResolveInfo ri = new ResolveInfo(); 5657 ri.serviceInfo = si; 5658 list.add(ri); 5659 } 5660 return list; 5661 } 5662 5663 // reader 5664 synchronized (mPackages) { 5665 String pkgName = intent.getPackage(); 5666 if (pkgName == null) { 5667 return mServices.queryIntent(intent, resolvedType, flags, userId); 5668 } 5669 final PackageParser.Package pkg = mPackages.get(pkgName); 5670 if (pkg != null) { 5671 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5672 userId); 5673 } 5674 return null; 5675 } 5676 } 5677 5678 @Override 5679 public List<ResolveInfo> queryIntentContentProviders( 5680 Intent intent, String resolvedType, int flags, int userId) { 5681 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5682 flags = updateFlagsForResolve(flags, userId, intent); 5683 ComponentName comp = intent.getComponent(); 5684 if (comp == null) { 5685 if (intent.getSelector() != null) { 5686 intent = intent.getSelector(); 5687 comp = intent.getComponent(); 5688 } 5689 } 5690 if (comp != null) { 5691 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5692 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5693 if (pi != null) { 5694 final ResolveInfo ri = new ResolveInfo(); 5695 ri.providerInfo = pi; 5696 list.add(ri); 5697 } 5698 return list; 5699 } 5700 5701 // reader 5702 synchronized (mPackages) { 5703 String pkgName = intent.getPackage(); 5704 if (pkgName == null) { 5705 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5706 } 5707 final PackageParser.Package pkg = mPackages.get(pkgName); 5708 if (pkg != null) { 5709 return mProviders.queryIntentForPackage( 5710 intent, resolvedType, flags, pkg.providers, userId); 5711 } 5712 return null; 5713 } 5714 } 5715 5716 @Override 5717 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5718 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5719 flags = updateFlagsForPackage(flags, userId, null); 5720 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5721 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5722 5723 // writer 5724 synchronized (mPackages) { 5725 ArrayList<PackageInfo> list; 5726 if (listUninstalled) { 5727 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5728 for (PackageSetting ps : mSettings.mPackages.values()) { 5729 PackageInfo pi; 5730 if (ps.pkg != null) { 5731 pi = generatePackageInfo(ps.pkg, flags, userId); 5732 } else { 5733 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5734 } 5735 if (pi != null) { 5736 list.add(pi); 5737 } 5738 } 5739 } else { 5740 list = new ArrayList<PackageInfo>(mPackages.size()); 5741 for (PackageParser.Package p : mPackages.values()) { 5742 PackageInfo pi = generatePackageInfo(p, flags, userId); 5743 if (pi != null) { 5744 list.add(pi); 5745 } 5746 } 5747 } 5748 5749 return new ParceledListSlice<PackageInfo>(list); 5750 } 5751 } 5752 5753 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5754 String[] permissions, boolean[] tmp, int flags, int userId) { 5755 int numMatch = 0; 5756 final PermissionsState permissionsState = ps.getPermissionsState(); 5757 for (int i=0; i<permissions.length; i++) { 5758 final String permission = permissions[i]; 5759 if (permissionsState.hasPermission(permission, userId)) { 5760 tmp[i] = true; 5761 numMatch++; 5762 } else { 5763 tmp[i] = false; 5764 } 5765 } 5766 if (numMatch == 0) { 5767 return; 5768 } 5769 PackageInfo pi; 5770 if (ps.pkg != null) { 5771 pi = generatePackageInfo(ps.pkg, flags, userId); 5772 } else { 5773 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5774 } 5775 // The above might return null in cases of uninstalled apps or install-state 5776 // skew across users/profiles. 5777 if (pi != null) { 5778 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5779 if (numMatch == permissions.length) { 5780 pi.requestedPermissions = permissions; 5781 } else { 5782 pi.requestedPermissions = new String[numMatch]; 5783 numMatch = 0; 5784 for (int i=0; i<permissions.length; i++) { 5785 if (tmp[i]) { 5786 pi.requestedPermissions[numMatch] = permissions[i]; 5787 numMatch++; 5788 } 5789 } 5790 } 5791 } 5792 list.add(pi); 5793 } 5794 } 5795 5796 @Override 5797 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5798 String[] permissions, int flags, int userId) { 5799 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5800 flags = updateFlagsForPackage(flags, userId, permissions); 5801 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5802 5803 // writer 5804 synchronized (mPackages) { 5805 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5806 boolean[] tmpBools = new boolean[permissions.length]; 5807 if (listUninstalled) { 5808 for (PackageSetting ps : mSettings.mPackages.values()) { 5809 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5810 } 5811 } else { 5812 for (PackageParser.Package pkg : mPackages.values()) { 5813 PackageSetting ps = (PackageSetting)pkg.mExtras; 5814 if (ps != null) { 5815 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5816 userId); 5817 } 5818 } 5819 } 5820 5821 return new ParceledListSlice<PackageInfo>(list); 5822 } 5823 } 5824 5825 @Override 5826 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5827 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5828 flags = updateFlagsForApplication(flags, userId, null); 5829 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5830 5831 // writer 5832 synchronized (mPackages) { 5833 ArrayList<ApplicationInfo> list; 5834 if (listUninstalled) { 5835 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5836 for (PackageSetting ps : mSettings.mPackages.values()) { 5837 ApplicationInfo ai; 5838 if (ps.pkg != null) { 5839 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5840 ps.readUserState(userId), userId); 5841 } else { 5842 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5843 } 5844 if (ai != null) { 5845 list.add(ai); 5846 } 5847 } 5848 } else { 5849 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5850 for (PackageParser.Package p : mPackages.values()) { 5851 if (p.mExtras != null) { 5852 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5853 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5854 if (ai != null) { 5855 list.add(ai); 5856 } 5857 } 5858 } 5859 } 5860 5861 return new ParceledListSlice<ApplicationInfo>(list); 5862 } 5863 } 5864 5865 @Override 5866 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 5867 if (DISABLE_EPHEMERAL_APPS) { 5868 return null; 5869 } 5870 5871 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 5872 "getEphemeralApplications"); 5873 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5874 "getEphemeralApplications"); 5875 synchronized (mPackages) { 5876 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 5877 .getEphemeralApplicationsLPw(userId); 5878 if (ephemeralApps != null) { 5879 return new ParceledListSlice<>(ephemeralApps); 5880 } 5881 } 5882 return null; 5883 } 5884 5885 @Override 5886 public boolean isEphemeralApplication(String packageName, int userId) { 5887 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5888 "isEphemeral"); 5889 if (DISABLE_EPHEMERAL_APPS) { 5890 return false; 5891 } 5892 5893 if (!isCallerSameApp(packageName)) { 5894 return false; 5895 } 5896 synchronized (mPackages) { 5897 PackageParser.Package pkg = mPackages.get(packageName); 5898 if (pkg != null) { 5899 return pkg.applicationInfo.isEphemeralApp(); 5900 } 5901 } 5902 return false; 5903 } 5904 5905 @Override 5906 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 5907 if (DISABLE_EPHEMERAL_APPS) { 5908 return null; 5909 } 5910 5911 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5912 "getCookie"); 5913 if (!isCallerSameApp(packageName)) { 5914 return null; 5915 } 5916 synchronized (mPackages) { 5917 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 5918 packageName, userId); 5919 } 5920 } 5921 5922 @Override 5923 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 5924 if (DISABLE_EPHEMERAL_APPS) { 5925 return true; 5926 } 5927 5928 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5929 "setCookie"); 5930 if (!isCallerSameApp(packageName)) { 5931 return false; 5932 } 5933 synchronized (mPackages) { 5934 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 5935 packageName, cookie, userId); 5936 } 5937 } 5938 5939 @Override 5940 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 5941 if (DISABLE_EPHEMERAL_APPS) { 5942 return null; 5943 } 5944 5945 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 5946 "getEphemeralApplicationIcon"); 5947 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5948 "getEphemeralApplicationIcon"); 5949 synchronized (mPackages) { 5950 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 5951 packageName, userId); 5952 } 5953 } 5954 5955 private boolean isCallerSameApp(String packageName) { 5956 PackageParser.Package pkg = mPackages.get(packageName); 5957 return pkg != null 5958 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 5959 } 5960 5961 public List<ApplicationInfo> getPersistentApplications(int flags) { 5962 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5963 5964 // reader 5965 synchronized (mPackages) { 5966 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5967 final int userId = UserHandle.getCallingUserId(); 5968 while (i.hasNext()) { 5969 final PackageParser.Package p = i.next(); 5970 if (p.applicationInfo != null 5971 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5972 && (!mSafeMode || isSystemApp(p))) { 5973 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5974 if (ps != null) { 5975 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5976 ps.readUserState(userId), userId); 5977 if (ai != null) { 5978 finalList.add(ai); 5979 } 5980 } 5981 } 5982 } 5983 } 5984 5985 return finalList; 5986 } 5987 5988 @Override 5989 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5990 if (!sUserManager.exists(userId)) return null; 5991 flags = updateFlagsForComponent(flags, userId, name); 5992 // reader 5993 synchronized (mPackages) { 5994 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5995 PackageSetting ps = provider != null 5996 ? mSettings.mPackages.get(provider.owner.packageName) 5997 : null; 5998 return ps != null 5999 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6000 ? PackageParser.generateProviderInfo(provider, flags, 6001 ps.readUserState(userId), userId) 6002 : null; 6003 } 6004 } 6005 6006 /** 6007 * @deprecated 6008 */ 6009 @Deprecated 6010 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6011 // reader 6012 synchronized (mPackages) { 6013 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6014 .entrySet().iterator(); 6015 final int userId = UserHandle.getCallingUserId(); 6016 while (i.hasNext()) { 6017 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6018 PackageParser.Provider p = entry.getValue(); 6019 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6020 6021 if (ps != null && p.syncable 6022 && (!mSafeMode || (p.info.applicationInfo.flags 6023 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6024 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6025 ps.readUserState(userId), userId); 6026 if (info != null) { 6027 outNames.add(entry.getKey()); 6028 outInfo.add(info); 6029 } 6030 } 6031 } 6032 } 6033 } 6034 6035 @Override 6036 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6037 int uid, int flags) { 6038 final int userId = processName != null ? UserHandle.getUserId(uid) 6039 : UserHandle.getCallingUserId(); 6040 if (!sUserManager.exists(userId)) return null; 6041 flags = updateFlagsForComponent(flags, userId, processName); 6042 6043 ArrayList<ProviderInfo> finalList = null; 6044 // reader 6045 synchronized (mPackages) { 6046 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6047 while (i.hasNext()) { 6048 final PackageParser.Provider p = i.next(); 6049 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6050 if (ps != null && p.info.authority != null 6051 && (processName == null 6052 || (p.info.processName.equals(processName) 6053 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6054 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6055 if (finalList == null) { 6056 finalList = new ArrayList<ProviderInfo>(3); 6057 } 6058 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6059 ps.readUserState(userId), userId); 6060 if (info != null) { 6061 finalList.add(info); 6062 } 6063 } 6064 } 6065 } 6066 6067 if (finalList != null) { 6068 Collections.sort(finalList, mProviderInitOrderSorter); 6069 return new ParceledListSlice<ProviderInfo>(finalList); 6070 } 6071 6072 return null; 6073 } 6074 6075 @Override 6076 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6077 // reader 6078 synchronized (mPackages) { 6079 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6080 return PackageParser.generateInstrumentationInfo(i, flags); 6081 } 6082 } 6083 6084 @Override 6085 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 6086 int flags) { 6087 ArrayList<InstrumentationInfo> finalList = 6088 new ArrayList<InstrumentationInfo>(); 6089 6090 // reader 6091 synchronized (mPackages) { 6092 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6093 while (i.hasNext()) { 6094 final PackageParser.Instrumentation p = i.next(); 6095 if (targetPackage == null 6096 || targetPackage.equals(p.info.targetPackage)) { 6097 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6098 flags); 6099 if (ii != null) { 6100 finalList.add(ii); 6101 } 6102 } 6103 } 6104 } 6105 6106 return finalList; 6107 } 6108 6109 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6110 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6111 if (overlays == null) { 6112 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6113 return; 6114 } 6115 for (PackageParser.Package opkg : overlays.values()) { 6116 // Not much to do if idmap fails: we already logged the error 6117 // and we certainly don't want to abort installation of pkg simply 6118 // because an overlay didn't fit properly. For these reasons, 6119 // ignore the return value of createIdmapForPackagePairLI. 6120 createIdmapForPackagePairLI(pkg, opkg); 6121 } 6122 } 6123 6124 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6125 PackageParser.Package opkg) { 6126 if (!opkg.mTrustedOverlay) { 6127 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6128 opkg.baseCodePath + ": overlay not trusted"); 6129 return false; 6130 } 6131 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6132 if (overlaySet == null) { 6133 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6134 opkg.baseCodePath + " but target package has no known overlays"); 6135 return false; 6136 } 6137 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6138 // TODO: generate idmap for split APKs 6139 try { 6140 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6141 } catch (InstallerException e) { 6142 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6143 + opkg.baseCodePath); 6144 return false; 6145 } 6146 PackageParser.Package[] overlayArray = 6147 overlaySet.values().toArray(new PackageParser.Package[0]); 6148 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6149 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6150 return p1.mOverlayPriority - p2.mOverlayPriority; 6151 } 6152 }; 6153 Arrays.sort(overlayArray, cmp); 6154 6155 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6156 int i = 0; 6157 for (PackageParser.Package p : overlayArray) { 6158 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6159 } 6160 return true; 6161 } 6162 6163 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6164 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6165 try { 6166 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6167 } finally { 6168 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6169 } 6170 } 6171 6172 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6173 final File[] files = dir.listFiles(); 6174 if (ArrayUtils.isEmpty(files)) { 6175 Log.d(TAG, "No files in app dir " + dir); 6176 return; 6177 } 6178 6179 if (DEBUG_PACKAGE_SCANNING) { 6180 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6181 + " flags=0x" + Integer.toHexString(parseFlags)); 6182 } 6183 6184 for (File file : files) { 6185 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6186 && !PackageInstallerService.isStageName(file.getName()); 6187 if (!isPackage) { 6188 // Ignore entries which are not packages 6189 continue; 6190 } 6191 try { 6192 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6193 scanFlags, currentTime, null); 6194 } catch (PackageManagerException e) { 6195 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6196 6197 // Delete invalid userdata apps 6198 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6199 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6200 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6201 removeCodePathLI(file); 6202 } 6203 } 6204 } 6205 } 6206 6207 private static File getSettingsProblemFile() { 6208 File dataDir = Environment.getDataDirectory(); 6209 File systemDir = new File(dataDir, "system"); 6210 File fname = new File(systemDir, "uiderrors.txt"); 6211 return fname; 6212 } 6213 6214 static void reportSettingsProblem(int priority, String msg) { 6215 logCriticalInfo(priority, msg); 6216 } 6217 6218 static void logCriticalInfo(int priority, String msg) { 6219 Slog.println(priority, TAG, msg); 6220 EventLogTags.writePmCriticalInfo(msg); 6221 try { 6222 File fname = getSettingsProblemFile(); 6223 FileOutputStream out = new FileOutputStream(fname, true); 6224 PrintWriter pw = new FastPrintWriter(out); 6225 SimpleDateFormat formatter = new SimpleDateFormat(); 6226 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6227 pw.println(dateString + ": " + msg); 6228 pw.close(); 6229 FileUtils.setPermissions( 6230 fname.toString(), 6231 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6232 -1, -1); 6233 } catch (java.io.IOException e) { 6234 } 6235 } 6236 6237 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 6238 PackageParser.Package pkg, File srcFile, int parseFlags) 6239 throws PackageManagerException { 6240 if (ps != null 6241 && ps.codePath.equals(srcFile) 6242 && ps.timeStamp == srcFile.lastModified() 6243 && !isCompatSignatureUpdateNeeded(pkg) 6244 && !isRecoverSignatureUpdateNeeded(pkg)) { 6245 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6246 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6247 ArraySet<PublicKey> signingKs; 6248 synchronized (mPackages) { 6249 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6250 } 6251 if (ps.signatures.mSignatures != null 6252 && ps.signatures.mSignatures.length != 0 6253 && signingKs != null) { 6254 // Optimization: reuse the existing cached certificates 6255 // if the package appears to be unchanged. 6256 pkg.mSignatures = ps.signatures.mSignatures; 6257 pkg.mSigningKeys = signingKs; 6258 return; 6259 } 6260 6261 Slog.w(TAG, "PackageSetting for " + ps.name 6262 + " is missing signatures. Collecting certs again to recover them."); 6263 } else { 6264 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6265 } 6266 6267 try { 6268 pp.collectCertificates(pkg, parseFlags); 6269 } catch (PackageParserException e) { 6270 throw PackageManagerException.from(e); 6271 } 6272 } 6273 6274 /** 6275 * Traces a package scan. 6276 * @see #scanPackageLI(File, int, int, long, UserHandle) 6277 */ 6278 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6279 long currentTime, UserHandle user) throws PackageManagerException { 6280 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6281 try { 6282 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6283 } finally { 6284 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6285 } 6286 } 6287 6288 /** 6289 * Scans a package and returns the newly parsed package. 6290 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6291 */ 6292 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6293 long currentTime, UserHandle user) throws PackageManagerException { 6294 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6295 parseFlags |= mDefParseFlags; 6296 PackageParser pp = new PackageParser(); 6297 pp.setSeparateProcesses(mSeparateProcesses); 6298 pp.setOnlyCoreApps(mOnlyCore); 6299 pp.setDisplayMetrics(mMetrics); 6300 6301 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6302 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6303 } 6304 6305 final PackageParser.Package pkg; 6306 try { 6307 pkg = pp.parsePackage(scanFile, parseFlags); 6308 } catch (PackageParserException e) { 6309 throw PackageManagerException.from(e); 6310 } 6311 6312 PackageSetting ps = null; 6313 PackageSetting updatedPkg; 6314 // reader 6315 synchronized (mPackages) { 6316 // Look to see if we already know about this package. 6317 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6318 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6319 // This package has been renamed to its original name. Let's 6320 // use that. 6321 ps = mSettings.peekPackageLPr(oldName); 6322 } 6323 // If there was no original package, see one for the real package name. 6324 if (ps == null) { 6325 ps = mSettings.peekPackageLPr(pkg.packageName); 6326 } 6327 // Check to see if this package could be hiding/updating a system 6328 // package. Must look for it either under the original or real 6329 // package name depending on our state. 6330 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6331 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6332 } 6333 boolean updatedPkgBetter = false; 6334 // First check if this is a system package that may involve an update 6335 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6336 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6337 // it needs to drop FLAG_PRIVILEGED. 6338 if (locationIsPrivileged(scanFile)) { 6339 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6340 } else { 6341 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6342 } 6343 6344 if (ps != null && !ps.codePath.equals(scanFile)) { 6345 // The path has changed from what was last scanned... check the 6346 // version of the new path against what we have stored to determine 6347 // what to do. 6348 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6349 if (pkg.mVersionCode <= ps.versionCode) { 6350 // The system package has been updated and the code path does not match 6351 // Ignore entry. Skip it. 6352 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6353 + " ignored: updated version " + ps.versionCode 6354 + " better than this " + pkg.mVersionCode); 6355 if (!updatedPkg.codePath.equals(scanFile)) { 6356 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6357 + ps.name + " changing from " + updatedPkg.codePathString 6358 + " to " + scanFile); 6359 updatedPkg.codePath = scanFile; 6360 updatedPkg.codePathString = scanFile.toString(); 6361 updatedPkg.resourcePath = scanFile; 6362 updatedPkg.resourcePathString = scanFile.toString(); 6363 } 6364 updatedPkg.pkg = pkg; 6365 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6366 "Package " + ps.name + " at " + scanFile 6367 + " ignored: updated version " + ps.versionCode 6368 + " better than this " + pkg.mVersionCode); 6369 } else { 6370 // The current app on the system partition is better than 6371 // what we have updated to on the data partition; switch 6372 // back to the system partition version. 6373 // At this point, its safely assumed that package installation for 6374 // apps in system partition will go through. If not there won't be a working 6375 // version of the app 6376 // writer 6377 synchronized (mPackages) { 6378 // Just remove the loaded entries from package lists. 6379 mPackages.remove(ps.name); 6380 } 6381 6382 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6383 + " reverting from " + ps.codePathString 6384 + ": new version " + pkg.mVersionCode 6385 + " better than installed " + ps.versionCode); 6386 6387 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6388 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6389 synchronized (mInstallLock) { 6390 args.cleanUpResourcesLI(); 6391 } 6392 synchronized (mPackages) { 6393 mSettings.enableSystemPackageLPw(ps.name); 6394 } 6395 updatedPkgBetter = true; 6396 } 6397 } 6398 } 6399 6400 if (updatedPkg != null) { 6401 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6402 // initially 6403 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6404 6405 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6406 // flag set initially 6407 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6408 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6409 } 6410 } 6411 6412 // Verify certificates against what was last scanned 6413 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 6414 6415 /* 6416 * A new system app appeared, but we already had a non-system one of the 6417 * same name installed earlier. 6418 */ 6419 boolean shouldHideSystemApp = false; 6420 if (updatedPkg == null && ps != null 6421 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6422 /* 6423 * Check to make sure the signatures match first. If they don't, 6424 * wipe the installed application and its data. 6425 */ 6426 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6427 != PackageManager.SIGNATURE_MATCH) { 6428 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6429 + " signatures don't match existing userdata copy; removing"); 6430 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 6431 ps = null; 6432 } else { 6433 /* 6434 * If the newly-added system app is an older version than the 6435 * already installed version, hide it. It will be scanned later 6436 * and re-added like an update. 6437 */ 6438 if (pkg.mVersionCode <= ps.versionCode) { 6439 shouldHideSystemApp = true; 6440 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6441 + " but new version " + pkg.mVersionCode + " better than installed " 6442 + ps.versionCode + "; hiding system"); 6443 } else { 6444 /* 6445 * The newly found system app is a newer version that the 6446 * one previously installed. Simply remove the 6447 * already-installed application and replace it with our own 6448 * while keeping the application data. 6449 */ 6450 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6451 + " reverting from " + ps.codePathString + ": new version " 6452 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6453 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6454 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6455 synchronized (mInstallLock) { 6456 args.cleanUpResourcesLI(); 6457 } 6458 } 6459 } 6460 } 6461 6462 // The apk is forward locked (not public) if its code and resources 6463 // are kept in different files. (except for app in either system or 6464 // vendor path). 6465 // TODO grab this value from PackageSettings 6466 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6467 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6468 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6469 } 6470 } 6471 6472 // TODO: extend to support forward-locked splits 6473 String resourcePath = null; 6474 String baseResourcePath = null; 6475 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6476 if (ps != null && ps.resourcePathString != null) { 6477 resourcePath = ps.resourcePathString; 6478 baseResourcePath = ps.resourcePathString; 6479 } else { 6480 // Should not happen at all. Just log an error. 6481 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6482 } 6483 } else { 6484 resourcePath = pkg.codePath; 6485 baseResourcePath = pkg.baseCodePath; 6486 } 6487 6488 // Set application objects path explicitly. 6489 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 6490 pkg.applicationInfo.setCodePath(pkg.codePath); 6491 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 6492 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 6493 pkg.applicationInfo.setResourcePath(resourcePath); 6494 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 6495 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 6496 6497 // Note that we invoke the following method only if we are about to unpack an application 6498 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6499 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6500 6501 /* 6502 * If the system app should be overridden by a previously installed 6503 * data, hide the system app now and let the /data/app scan pick it up 6504 * again. 6505 */ 6506 if (shouldHideSystemApp) { 6507 synchronized (mPackages) { 6508 mSettings.disableSystemPackageLPw(pkg.packageName); 6509 } 6510 } 6511 6512 return scannedPkg; 6513 } 6514 6515 private static String fixProcessName(String defProcessName, 6516 String processName, int uid) { 6517 if (processName == null) { 6518 return defProcessName; 6519 } 6520 return processName; 6521 } 6522 6523 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6524 throws PackageManagerException { 6525 if (pkgSetting.signatures.mSignatures != null) { 6526 // Already existing package. Make sure signatures match 6527 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6528 == PackageManager.SIGNATURE_MATCH; 6529 if (!match) { 6530 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6531 == PackageManager.SIGNATURE_MATCH; 6532 } 6533 if (!match) { 6534 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6535 == PackageManager.SIGNATURE_MATCH; 6536 } 6537 if (!match) { 6538 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6539 + pkg.packageName + " signatures do not match the " 6540 + "previously installed version; ignoring!"); 6541 } 6542 } 6543 6544 // Check for shared user signatures 6545 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6546 // Already existing package. Make sure signatures match 6547 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6548 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6549 if (!match) { 6550 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6551 == PackageManager.SIGNATURE_MATCH; 6552 } 6553 if (!match) { 6554 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6555 == PackageManager.SIGNATURE_MATCH; 6556 } 6557 if (!match) { 6558 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6559 "Package " + pkg.packageName 6560 + " has no signatures that match those in shared user " 6561 + pkgSetting.sharedUser.name + "; ignoring!"); 6562 } 6563 } 6564 } 6565 6566 /** 6567 * Enforces that only the system UID or root's UID can call a method exposed 6568 * via Binder. 6569 * 6570 * @param message used as message if SecurityException is thrown 6571 * @throws SecurityException if the caller is not system or root 6572 */ 6573 private static final void enforceSystemOrRoot(String message) { 6574 final int uid = Binder.getCallingUid(); 6575 if (uid != Process.SYSTEM_UID && uid != 0) { 6576 throw new SecurityException(message); 6577 } 6578 } 6579 6580 @Override 6581 public void performFstrimIfNeeded() { 6582 enforceSystemOrRoot("Only the system can request fstrim"); 6583 6584 // Before everything else, see whether we need to fstrim. 6585 try { 6586 IMountService ms = PackageHelper.getMountService(); 6587 if (ms != null) { 6588 final boolean isUpgrade = isUpgrade(); 6589 boolean doTrim = isUpgrade; 6590 if (doTrim) { 6591 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6592 } else { 6593 final long interval = android.provider.Settings.Global.getLong( 6594 mContext.getContentResolver(), 6595 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6596 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6597 if (interval > 0) { 6598 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6599 if (timeSinceLast > interval) { 6600 doTrim = true; 6601 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6602 + "; running immediately"); 6603 } 6604 } 6605 } 6606 if (doTrim) { 6607 if (!isFirstBoot()) { 6608 try { 6609 ActivityManagerNative.getDefault().showBootMessage( 6610 mContext.getResources().getString( 6611 R.string.android_upgrading_fstrim), true); 6612 } catch (RemoteException e) { 6613 } 6614 } 6615 ms.runMaintenance(); 6616 } 6617 } else { 6618 Slog.e(TAG, "Mount service unavailable!"); 6619 } 6620 } catch (RemoteException e) { 6621 // Can't happen; MountService is local 6622 } 6623 } 6624 6625 @Override 6626 public void extractPackagesIfNeeded() { 6627 enforceSystemOrRoot("Only the system can request package extraction"); 6628 6629 // Extract pacakges only if profile-guided compilation is enabled because 6630 // otherwise BackgroundDexOptService will not dexopt them later. 6631 if (mUseJitProfiles) { 6632 ArraySet<String> pkgs = getOptimizablePackages(); 6633 if (pkgs != null) { 6634 for (String pkg : pkgs) { 6635 performDexOpt(pkg, null /* instructionSet */, false /* useProfiles */, 6636 true /* extractOnly */); 6637 } 6638 } 6639 } 6640 } 6641 6642 private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) { 6643 List<ResolveInfo> ris = null; 6644 try { 6645 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6646 intent, null, 0, userId); 6647 } catch (RemoteException e) { 6648 } 6649 ArraySet<String> pkgNames = new ArraySet<String>(); 6650 if (ris != null) { 6651 for (ResolveInfo ri : ris) { 6652 pkgNames.add(ri.activityInfo.packageName); 6653 } 6654 } 6655 return pkgNames; 6656 } 6657 6658 @Override 6659 public void notifyPackageUse(String packageName) { 6660 synchronized (mPackages) { 6661 PackageParser.Package p = mPackages.get(packageName); 6662 if (p == null) { 6663 return; 6664 } 6665 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6666 } 6667 } 6668 6669 // TODO: this is not used nor needed. Delete it. 6670 @Override 6671 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6672 return performDexOptTraced(packageName, instructionSet, false /* useProfiles */, 6673 false /* extractOnly */); 6674 } 6675 6676 public boolean performDexOpt(String packageName, String instructionSet, boolean useProfiles, 6677 boolean extractOnly) { 6678 return performDexOptTraced(packageName, instructionSet, useProfiles, extractOnly); 6679 } 6680 6681 private boolean performDexOptTraced(String packageName, String instructionSet, 6682 boolean useProfiles, boolean extractOnly) { 6683 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6684 try { 6685 return performDexOptInternal(packageName, instructionSet, useProfiles, extractOnly); 6686 } finally { 6687 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6688 } 6689 } 6690 6691 private boolean performDexOptInternal(String packageName, String instructionSet, 6692 boolean useProfiles, boolean extractOnly) { 6693 PackageParser.Package p; 6694 final String targetInstructionSet; 6695 synchronized (mPackages) { 6696 p = mPackages.get(packageName); 6697 if (p == null) { 6698 return false; 6699 } 6700 mPackageUsage.write(false); 6701 6702 targetInstructionSet = instructionSet != null ? instructionSet : 6703 getPrimaryInstructionSet(p.applicationInfo); 6704 if (!useProfiles && p.mDexOptPerformed.contains(targetInstructionSet)) { 6705 // Skip only if we do not use profiles since they might trigger a recompilation. 6706 return false; 6707 } 6708 } 6709 long callingId = Binder.clearCallingIdentity(); 6710 try { 6711 synchronized (mInstallLock) { 6712 final String[] instructionSets = new String[] { targetInstructionSet }; 6713 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6714 true /* inclDependencies */, useProfiles, extractOnly); 6715 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6716 } 6717 } finally { 6718 Binder.restoreCallingIdentity(callingId); 6719 } 6720 } 6721 6722 public ArraySet<String> getOptimizablePackages() { 6723 ArraySet<String> pkgs = new ArraySet<String>(); 6724 synchronized (mPackages) { 6725 for (PackageParser.Package p : mPackages.values()) { 6726 if (PackageDexOptimizer.canOptimizePackage(p)) { 6727 pkgs.add(p.packageName); 6728 } 6729 } 6730 } 6731 return pkgs; 6732 } 6733 6734 public void shutdown() { 6735 mPackageUsage.write(true); 6736 } 6737 6738 @Override 6739 public void forceDexOpt(String packageName) { 6740 enforceSystemOrRoot("forceDexOpt"); 6741 6742 PackageParser.Package pkg; 6743 synchronized (mPackages) { 6744 pkg = mPackages.get(packageName); 6745 if (pkg == null) { 6746 throw new IllegalArgumentException("Unknown package: " + packageName); 6747 } 6748 } 6749 6750 synchronized (mInstallLock) { 6751 final String[] instructionSets = new String[] { 6752 getPrimaryInstructionSet(pkg.applicationInfo) }; 6753 6754 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6755 6756 // Whoever is calling forceDexOpt wants a fully compiled package. 6757 // Don't use profiles since that may cause compilation to be skipped. 6758 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6759 true /* inclDependencies */, false /* useProfiles */, 6760 false /* extractOnly */); 6761 6762 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6763 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6764 throw new IllegalStateException("Failed to dexopt: " + res); 6765 } 6766 } 6767 } 6768 6769 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6770 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6771 Slog.w(TAG, "Unable to update from " + oldPkg.name 6772 + " to " + newPkg.packageName 6773 + ": old package not in system partition"); 6774 return false; 6775 } else if (mPackages.get(oldPkg.name) != null) { 6776 Slog.w(TAG, "Unable to update from " + oldPkg.name 6777 + " to " + newPkg.packageName 6778 + ": old package still exists"); 6779 return false; 6780 } 6781 return true; 6782 } 6783 6784 private boolean removeDataDirsLI(String volumeUuid, String packageName) { 6785 // TODO: triage flags as part of 26466827 6786 final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 6787 6788 boolean res = true; 6789 final int[] users = sUserManager.getUserIds(); 6790 for (int user : users) { 6791 try { 6792 mInstaller.destroyAppData(volumeUuid, packageName, user, flags); 6793 } catch (InstallerException e) { 6794 Slog.w(TAG, "Failed to delete data directory", e); 6795 res = false; 6796 } 6797 } 6798 return res; 6799 } 6800 6801 void removeCodePathLI(File codePath) { 6802 if (codePath.isDirectory()) { 6803 try { 6804 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 6805 } catch (InstallerException e) { 6806 Slog.w(TAG, "Failed to remove code path", e); 6807 } 6808 } else { 6809 codePath.delete(); 6810 } 6811 } 6812 6813 void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) { 6814 try { 6815 mInstaller.destroyAppData(volumeUuid, packageName, userId, flags); 6816 } catch (InstallerException e) { 6817 Slog.w(TAG, "Failed to destroy app data", e); 6818 } 6819 } 6820 6821 void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags, 6822 int appId, String seinfo) { 6823 try { 6824 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo); 6825 } catch (InstallerException e) { 6826 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 6827 } 6828 } 6829 6830 private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6831 // TODO: triage flags as part of 26466827 6832 final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 6833 6834 final int[] users = sUserManager.getUserIds(); 6835 for (int user : users) { 6836 try { 6837 mInstaller.clearAppData(volumeUuid, packageName, user, 6838 flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 6839 } catch (InstallerException e) { 6840 Slog.w(TAG, "Failed to delete code cache directory", e); 6841 } 6842 } 6843 } 6844 6845 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6846 PackageParser.Package changingLib) { 6847 if (file.path != null) { 6848 usesLibraryFiles.add(file.path); 6849 return; 6850 } 6851 PackageParser.Package p = mPackages.get(file.apk); 6852 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6853 // If we are doing this while in the middle of updating a library apk, 6854 // then we need to make sure to use that new apk for determining the 6855 // dependencies here. (We haven't yet finished committing the new apk 6856 // to the package manager state.) 6857 if (p == null || p.packageName.equals(changingLib.packageName)) { 6858 p = changingLib; 6859 } 6860 } 6861 if (p != null) { 6862 usesLibraryFiles.addAll(p.getAllCodePaths()); 6863 } 6864 } 6865 6866 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6867 PackageParser.Package changingLib) throws PackageManagerException { 6868 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6869 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6870 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6871 for (int i=0; i<N; i++) { 6872 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6873 if (file == null) { 6874 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6875 "Package " + pkg.packageName + " requires unavailable shared library " 6876 + pkg.usesLibraries.get(i) + "; failing!"); 6877 } 6878 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6879 } 6880 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6881 for (int i=0; i<N; i++) { 6882 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6883 if (file == null) { 6884 Slog.w(TAG, "Package " + pkg.packageName 6885 + " desires unavailable shared library " 6886 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6887 } else { 6888 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6889 } 6890 } 6891 N = usesLibraryFiles.size(); 6892 if (N > 0) { 6893 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6894 } else { 6895 pkg.usesLibraryFiles = null; 6896 } 6897 } 6898 } 6899 6900 private static boolean hasString(List<String> list, List<String> which) { 6901 if (list == null) { 6902 return false; 6903 } 6904 for (int i=list.size()-1; i>=0; i--) { 6905 for (int j=which.size()-1; j>=0; j--) { 6906 if (which.get(j).equals(list.get(i))) { 6907 return true; 6908 } 6909 } 6910 } 6911 return false; 6912 } 6913 6914 private void updateAllSharedLibrariesLPw() { 6915 for (PackageParser.Package pkg : mPackages.values()) { 6916 try { 6917 updateSharedLibrariesLPw(pkg, null); 6918 } catch (PackageManagerException e) { 6919 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6920 } 6921 } 6922 } 6923 6924 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6925 PackageParser.Package changingPkg) { 6926 ArrayList<PackageParser.Package> res = null; 6927 for (PackageParser.Package pkg : mPackages.values()) { 6928 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6929 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6930 if (res == null) { 6931 res = new ArrayList<PackageParser.Package>(); 6932 } 6933 res.add(pkg); 6934 try { 6935 updateSharedLibrariesLPw(pkg, changingPkg); 6936 } catch (PackageManagerException e) { 6937 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6938 } 6939 } 6940 } 6941 return res; 6942 } 6943 6944 /** 6945 * Derive the value of the {@code cpuAbiOverride} based on the provided 6946 * value and an optional stored value from the package settings. 6947 */ 6948 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6949 String cpuAbiOverride = null; 6950 6951 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6952 cpuAbiOverride = null; 6953 } else if (abiOverride != null) { 6954 cpuAbiOverride = abiOverride; 6955 } else if (settings != null) { 6956 cpuAbiOverride = settings.cpuAbiOverrideString; 6957 } 6958 6959 return cpuAbiOverride; 6960 } 6961 6962 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 6963 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6964 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6965 try { 6966 return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 6967 } finally { 6968 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6969 } 6970 } 6971 6972 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6973 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6974 boolean success = false; 6975 try { 6976 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6977 currentTime, user); 6978 success = true; 6979 return res; 6980 } finally { 6981 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6982 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6983 } 6984 } 6985 } 6986 6987 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6988 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6989 final File scanFile = new File(pkg.codePath); 6990 if (pkg.applicationInfo.getCodePath() == null || 6991 pkg.applicationInfo.getResourcePath() == null) { 6992 // Bail out. The resource and code paths haven't been set. 6993 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6994 "Code and resource paths haven't been set correctly"); 6995 } 6996 6997 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6998 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6999 } else { 7000 // Only allow system apps to be flagged as core apps. 7001 pkg.coreApp = false; 7002 } 7003 7004 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7005 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7006 } 7007 7008 if (mCustomResolverComponentName != null && 7009 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7010 setUpCustomResolverActivity(pkg); 7011 } 7012 7013 if (pkg.packageName.equals("android")) { 7014 synchronized (mPackages) { 7015 if (mAndroidApplication != null) { 7016 Slog.w(TAG, "*************************************************"); 7017 Slog.w(TAG, "Core android package being redefined. Skipping."); 7018 Slog.w(TAG, " file=" + scanFile); 7019 Slog.w(TAG, "*************************************************"); 7020 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7021 "Core android package being redefined. Skipping."); 7022 } 7023 7024 // Set up information for our fall-back user intent resolution activity. 7025 mPlatformPackage = pkg; 7026 pkg.mVersionCode = mSdkVersion; 7027 mAndroidApplication = pkg.applicationInfo; 7028 7029 if (!mResolverReplaced) { 7030 mResolveActivity.applicationInfo = mAndroidApplication; 7031 mResolveActivity.name = ResolverActivity.class.getName(); 7032 mResolveActivity.packageName = mAndroidApplication.packageName; 7033 mResolveActivity.processName = "system:ui"; 7034 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7035 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7036 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7037 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7038 mResolveActivity.exported = true; 7039 mResolveActivity.enabled = true; 7040 mResolveInfo.activityInfo = mResolveActivity; 7041 mResolveInfo.priority = 0; 7042 mResolveInfo.preferredOrder = 0; 7043 mResolveInfo.match = 0; 7044 mResolveComponentName = new ComponentName( 7045 mAndroidApplication.packageName, mResolveActivity.name); 7046 } 7047 } 7048 } 7049 7050 if (DEBUG_PACKAGE_SCANNING) { 7051 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7052 Log.d(TAG, "Scanning package " + pkg.packageName); 7053 } 7054 7055 if (mPackages.containsKey(pkg.packageName) 7056 || mSharedLibraries.containsKey(pkg.packageName)) { 7057 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7058 "Application package " + pkg.packageName 7059 + " already installed. Skipping duplicate."); 7060 } 7061 7062 // If we're only installing presumed-existing packages, require that the 7063 // scanned APK is both already known and at the path previously established 7064 // for it. Previously unknown packages we pick up normally, but if we have an 7065 // a priori expectation about this package's install presence, enforce it. 7066 // With a singular exception for new system packages. When an OTA contains 7067 // a new system package, we allow the codepath to change from a system location 7068 // to the user-installed location. If we don't allow this change, any newer, 7069 // user-installed version of the application will be ignored. 7070 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7071 if (mExpectingBetter.containsKey(pkg.packageName)) { 7072 logCriticalInfo(Log.WARN, 7073 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7074 } else { 7075 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7076 if (known != null) { 7077 if (DEBUG_PACKAGE_SCANNING) { 7078 Log.d(TAG, "Examining " + pkg.codePath 7079 + " and requiring known paths " + known.codePathString 7080 + " & " + known.resourcePathString); 7081 } 7082 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7083 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 7084 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7085 "Application package " + pkg.packageName 7086 + " found at " + pkg.applicationInfo.getCodePath() 7087 + " but expected at " + known.codePathString + "; ignoring."); 7088 } 7089 } 7090 } 7091 } 7092 7093 // Initialize package source and resource directories 7094 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7095 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7096 7097 SharedUserSetting suid = null; 7098 PackageSetting pkgSetting = null; 7099 7100 if (!isSystemApp(pkg)) { 7101 // Only system apps can use these features. 7102 pkg.mOriginalPackages = null; 7103 pkg.mRealPackage = null; 7104 pkg.mAdoptPermissions = null; 7105 } 7106 7107 // writer 7108 synchronized (mPackages) { 7109 if (pkg.mSharedUserId != null) { 7110 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7111 if (suid == null) { 7112 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7113 "Creating application package " + pkg.packageName 7114 + " for shared user failed"); 7115 } 7116 if (DEBUG_PACKAGE_SCANNING) { 7117 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7118 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7119 + "): packages=" + suid.packages); 7120 } 7121 } 7122 7123 // Check if we are renaming from an original package name. 7124 PackageSetting origPackage = null; 7125 String realName = null; 7126 if (pkg.mOriginalPackages != null) { 7127 // This package may need to be renamed to a previously 7128 // installed name. Let's check on that... 7129 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7130 if (pkg.mOriginalPackages.contains(renamed)) { 7131 // This package had originally been installed as the 7132 // original name, and we have already taken care of 7133 // transitioning to the new one. Just update the new 7134 // one to continue using the old name. 7135 realName = pkg.mRealPackage; 7136 if (!pkg.packageName.equals(renamed)) { 7137 // Callers into this function may have already taken 7138 // care of renaming the package; only do it here if 7139 // it is not already done. 7140 pkg.setPackageName(renamed); 7141 } 7142 7143 } else { 7144 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7145 if ((origPackage = mSettings.peekPackageLPr( 7146 pkg.mOriginalPackages.get(i))) != null) { 7147 // We do have the package already installed under its 7148 // original name... should we use it? 7149 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7150 // New package is not compatible with original. 7151 origPackage = null; 7152 continue; 7153 } else if (origPackage.sharedUser != null) { 7154 // Make sure uid is compatible between packages. 7155 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7156 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7157 + " to " + pkg.packageName + ": old uid " 7158 + origPackage.sharedUser.name 7159 + " differs from " + pkg.mSharedUserId); 7160 origPackage = null; 7161 continue; 7162 } 7163 } else { 7164 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7165 + pkg.packageName + " to old name " + origPackage.name); 7166 } 7167 break; 7168 } 7169 } 7170 } 7171 } 7172 7173 if (mTransferedPackages.contains(pkg.packageName)) { 7174 Slog.w(TAG, "Package " + pkg.packageName 7175 + " was transferred to another, but its .apk remains"); 7176 } 7177 7178 // Just create the setting, don't add it yet. For already existing packages 7179 // the PkgSetting exists already and doesn't have to be created. 7180 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7181 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7182 pkg.applicationInfo.primaryCpuAbi, 7183 pkg.applicationInfo.secondaryCpuAbi, 7184 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7185 user, false); 7186 if (pkgSetting == null) { 7187 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7188 "Creating application package " + pkg.packageName + " failed"); 7189 } 7190 7191 if (pkgSetting.origPackage != null) { 7192 // If we are first transitioning from an original package, 7193 // fix up the new package's name now. We need to do this after 7194 // looking up the package under its new name, so getPackageLP 7195 // can take care of fiddling things correctly. 7196 pkg.setPackageName(origPackage.name); 7197 7198 // File a report about this. 7199 String msg = "New package " + pkgSetting.realName 7200 + " renamed to replace old package " + pkgSetting.name; 7201 reportSettingsProblem(Log.WARN, msg); 7202 7203 // Make a note of it. 7204 mTransferedPackages.add(origPackage.name); 7205 7206 // No longer need to retain this. 7207 pkgSetting.origPackage = null; 7208 } 7209 7210 if (realName != null) { 7211 // Make a note of it. 7212 mTransferedPackages.add(pkg.packageName); 7213 } 7214 7215 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7216 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7217 } 7218 7219 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7220 // Check all shared libraries and map to their actual file path. 7221 // We only do this here for apps not on a system dir, because those 7222 // are the only ones that can fail an install due to this. We 7223 // will take care of the system apps by updating all of their 7224 // library paths after the scan is done. 7225 updateSharedLibrariesLPw(pkg, null); 7226 } 7227 7228 if (mFoundPolicyFile) { 7229 SELinuxMMAC.assignSeinfoValue(pkg); 7230 } 7231 7232 pkg.applicationInfo.uid = pkgSetting.appId; 7233 pkg.mExtras = pkgSetting; 7234 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7235 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7236 // We just determined the app is signed correctly, so bring 7237 // over the latest parsed certs. 7238 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7239 } else { 7240 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7241 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7242 "Package " + pkg.packageName + " upgrade keys do not match the " 7243 + "previously installed version"); 7244 } else { 7245 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7246 String msg = "System package " + pkg.packageName 7247 + " signature changed; retaining data."; 7248 reportSettingsProblem(Log.WARN, msg); 7249 } 7250 } 7251 } else { 7252 try { 7253 verifySignaturesLP(pkgSetting, pkg); 7254 // We just determined the app is signed correctly, so bring 7255 // over the latest parsed certs. 7256 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7257 } catch (PackageManagerException e) { 7258 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7259 throw e; 7260 } 7261 // The signature has changed, but this package is in the system 7262 // image... let's recover! 7263 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7264 // However... if this package is part of a shared user, but it 7265 // doesn't match the signature of the shared user, let's fail. 7266 // What this means is that you can't change the signatures 7267 // associated with an overall shared user, which doesn't seem all 7268 // that unreasonable. 7269 if (pkgSetting.sharedUser != null) { 7270 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7271 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7272 throw new PackageManagerException( 7273 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7274 "Signature mismatch for shared user: " 7275 + pkgSetting.sharedUser); 7276 } 7277 } 7278 // File a report about this. 7279 String msg = "System package " + pkg.packageName 7280 + " signature changed; retaining data."; 7281 reportSettingsProblem(Log.WARN, msg); 7282 } 7283 } 7284 // Verify that this new package doesn't have any content providers 7285 // that conflict with existing packages. Only do this if the 7286 // package isn't already installed, since we don't want to break 7287 // things that are installed. 7288 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7289 final int N = pkg.providers.size(); 7290 int i; 7291 for (i=0; i<N; i++) { 7292 PackageParser.Provider p = pkg.providers.get(i); 7293 if (p.info.authority != null) { 7294 String names[] = p.info.authority.split(";"); 7295 for (int j = 0; j < names.length; j++) { 7296 if (mProvidersByAuthority.containsKey(names[j])) { 7297 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7298 final String otherPackageName = 7299 ((other != null && other.getComponentName() != null) ? 7300 other.getComponentName().getPackageName() : "?"); 7301 throw new PackageManagerException( 7302 INSTALL_FAILED_CONFLICTING_PROVIDER, 7303 "Can't install because provider name " + names[j] 7304 + " (in package " + pkg.applicationInfo.packageName 7305 + ") is already used by " + otherPackageName); 7306 } 7307 } 7308 } 7309 } 7310 } 7311 7312 if (pkg.mAdoptPermissions != null) { 7313 // This package wants to adopt ownership of permissions from 7314 // another package. 7315 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7316 final String origName = pkg.mAdoptPermissions.get(i); 7317 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7318 if (orig != null) { 7319 if (verifyPackageUpdateLPr(orig, pkg)) { 7320 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7321 + pkg.packageName); 7322 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7323 } 7324 } 7325 } 7326 } 7327 } 7328 7329 final String pkgName = pkg.packageName; 7330 7331 final long scanFileTime = scanFile.lastModified(); 7332 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7333 pkg.applicationInfo.processName = fixProcessName( 7334 pkg.applicationInfo.packageName, 7335 pkg.applicationInfo.processName, 7336 pkg.applicationInfo.uid); 7337 7338 if (pkg != mPlatformPackage) { 7339 // Get all of our default paths setup 7340 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7341 } 7342 7343 final String path = scanFile.getPath(); 7344 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7345 7346 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7347 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7348 7349 // Some system apps still use directory structure for native libraries 7350 // in which case we might end up not detecting abi solely based on apk 7351 // structure. Try to detect abi based on directory structure. 7352 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7353 pkg.applicationInfo.primaryCpuAbi == null) { 7354 setBundledAppAbisAndRoots(pkg, pkgSetting); 7355 setNativeLibraryPaths(pkg); 7356 } 7357 7358 } else { 7359 if ((scanFlags & SCAN_MOVE) != 0) { 7360 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7361 // but we already have this packages package info in the PackageSetting. We just 7362 // use that and derive the native library path based on the new codepath. 7363 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7364 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7365 } 7366 7367 // Set native library paths again. For moves, the path will be updated based on the 7368 // ABIs we've determined above. For non-moves, the path will be updated based on the 7369 // ABIs we determined during compilation, but the path will depend on the final 7370 // package path (after the rename away from the stage path). 7371 setNativeLibraryPaths(pkg); 7372 } 7373 7374 // This is a special case for the "system" package, where the ABI is 7375 // dictated by the zygote configuration (and init.rc). We should keep track 7376 // of this ABI so that we can deal with "normal" applications that run under 7377 // the same UID correctly. 7378 if (mPlatformPackage == pkg) { 7379 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7380 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7381 } 7382 7383 // If there's a mismatch between the abi-override in the package setting 7384 // and the abiOverride specified for the install. Warn about this because we 7385 // would've already compiled the app without taking the package setting into 7386 // account. 7387 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7388 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7389 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7390 " for package " + pkg.packageName); 7391 } 7392 } 7393 7394 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7395 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7396 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7397 7398 // Copy the derived override back to the parsed package, so that we can 7399 // update the package settings accordingly. 7400 pkg.cpuAbiOverride = cpuAbiOverride; 7401 7402 if (DEBUG_ABI_SELECTION) { 7403 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7404 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7405 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7406 } 7407 7408 // Push the derived path down into PackageSettings so we know what to 7409 // clean up at uninstall time. 7410 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7411 7412 if (DEBUG_ABI_SELECTION) { 7413 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7414 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7415 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7416 } 7417 7418 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7419 // We don't do this here during boot because we can do it all 7420 // at once after scanning all existing packages. 7421 // 7422 // We also do this *before* we perform dexopt on this package, so that 7423 // we can avoid redundant dexopts, and also to make sure we've got the 7424 // code and package path correct. 7425 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7426 pkg, true /* boot complete */); 7427 } 7428 7429 if (mFactoryTest && pkg.requestedPermissions.contains( 7430 android.Manifest.permission.FACTORY_TEST)) { 7431 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7432 } 7433 7434 ArrayList<PackageParser.Package> clientLibPkgs = null; 7435 7436 // writer 7437 synchronized (mPackages) { 7438 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7439 // Only system apps can add new shared libraries. 7440 if (pkg.libraryNames != null) { 7441 for (int i=0; i<pkg.libraryNames.size(); i++) { 7442 String name = pkg.libraryNames.get(i); 7443 boolean allowed = false; 7444 if (pkg.isUpdatedSystemApp()) { 7445 // New library entries can only be added through the 7446 // system image. This is important to get rid of a lot 7447 // of nasty edge cases: for example if we allowed a non- 7448 // system update of the app to add a library, then uninstalling 7449 // the update would make the library go away, and assumptions 7450 // we made such as through app install filtering would now 7451 // have allowed apps on the device which aren't compatible 7452 // with it. Better to just have the restriction here, be 7453 // conservative, and create many fewer cases that can negatively 7454 // impact the user experience. 7455 final PackageSetting sysPs = mSettings 7456 .getDisabledSystemPkgLPr(pkg.packageName); 7457 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7458 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7459 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7460 allowed = true; 7461 break; 7462 } 7463 } 7464 } 7465 } else { 7466 allowed = true; 7467 } 7468 if (allowed) { 7469 if (!mSharedLibraries.containsKey(name)) { 7470 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7471 } else if (!name.equals(pkg.packageName)) { 7472 Slog.w(TAG, "Package " + pkg.packageName + " library " 7473 + name + " already exists; skipping"); 7474 } 7475 } else { 7476 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7477 + name + " that is not declared on system image; skipping"); 7478 } 7479 } 7480 if ((scanFlags & SCAN_BOOTING) == 0) { 7481 // If we are not booting, we need to update any applications 7482 // that are clients of our shared library. If we are booting, 7483 // this will all be done once the scan is complete. 7484 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7485 } 7486 } 7487 } 7488 } 7489 7490 // Request the ActivityManager to kill the process(only for existing packages) 7491 // so that we do not end up in a confused state while the user is still using the older 7492 // version of the application while the new one gets installed. 7493 if ((scanFlags & SCAN_REPLACING) != 0) { 7494 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7495 7496 killApplication(pkg.applicationInfo.packageName, 7497 pkg.applicationInfo.uid, "replace pkg"); 7498 7499 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7500 } 7501 7502 // Also need to kill any apps that are dependent on the library. 7503 if (clientLibPkgs != null) { 7504 for (int i=0; i<clientLibPkgs.size(); i++) { 7505 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7506 killApplication(clientPkg.applicationInfo.packageName, 7507 clientPkg.applicationInfo.uid, "update lib"); 7508 } 7509 } 7510 7511 // Make sure we're not adding any bogus keyset info 7512 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7513 ksms.assertScannedPackageValid(pkg); 7514 7515 // writer 7516 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7517 7518 boolean createIdmapFailed = false; 7519 synchronized (mPackages) { 7520 // We don't expect installation to fail beyond this point 7521 7522 // Add the new setting to mSettings 7523 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7524 // Add the new setting to mPackages 7525 mPackages.put(pkg.applicationInfo.packageName, pkg); 7526 // Make sure we don't accidentally delete its data. 7527 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7528 while (iter.hasNext()) { 7529 PackageCleanItem item = iter.next(); 7530 if (pkgName.equals(item.packageName)) { 7531 iter.remove(); 7532 } 7533 } 7534 7535 // Take care of first install / last update times. 7536 if (currentTime != 0) { 7537 if (pkgSetting.firstInstallTime == 0) { 7538 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7539 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7540 pkgSetting.lastUpdateTime = currentTime; 7541 } 7542 } else if (pkgSetting.firstInstallTime == 0) { 7543 // We need *something*. Take time time stamp of the file. 7544 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7545 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7546 if (scanFileTime != pkgSetting.timeStamp) { 7547 // A package on the system image has changed; consider this 7548 // to be an update. 7549 pkgSetting.lastUpdateTime = scanFileTime; 7550 } 7551 } 7552 7553 // Add the package's KeySets to the global KeySetManagerService 7554 ksms.addScannedPackageLPw(pkg); 7555 7556 int N = pkg.providers.size(); 7557 StringBuilder r = null; 7558 int i; 7559 for (i=0; i<N; i++) { 7560 PackageParser.Provider p = pkg.providers.get(i); 7561 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7562 p.info.processName, pkg.applicationInfo.uid); 7563 mProviders.addProvider(p); 7564 p.syncable = p.info.isSyncable; 7565 if (p.info.authority != null) { 7566 String names[] = p.info.authority.split(";"); 7567 p.info.authority = null; 7568 for (int j = 0; j < names.length; j++) { 7569 if (j == 1 && p.syncable) { 7570 // We only want the first authority for a provider to possibly be 7571 // syncable, so if we already added this provider using a different 7572 // authority clear the syncable flag. We copy the provider before 7573 // changing it because the mProviders object contains a reference 7574 // to a provider that we don't want to change. 7575 // Only do this for the second authority since the resulting provider 7576 // object can be the same for all future authorities for this provider. 7577 p = new PackageParser.Provider(p); 7578 p.syncable = false; 7579 } 7580 if (!mProvidersByAuthority.containsKey(names[j])) { 7581 mProvidersByAuthority.put(names[j], p); 7582 if (p.info.authority == null) { 7583 p.info.authority = names[j]; 7584 } else { 7585 p.info.authority = p.info.authority + ";" + names[j]; 7586 } 7587 if (DEBUG_PACKAGE_SCANNING) { 7588 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7589 Log.d(TAG, "Registered content provider: " + names[j] 7590 + ", className = " + p.info.name + ", isSyncable = " 7591 + p.info.isSyncable); 7592 } 7593 } else { 7594 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7595 Slog.w(TAG, "Skipping provider name " + names[j] + 7596 " (in package " + pkg.applicationInfo.packageName + 7597 "): name already used by " 7598 + ((other != null && other.getComponentName() != null) 7599 ? other.getComponentName().getPackageName() : "?")); 7600 } 7601 } 7602 } 7603 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7604 if (r == null) { 7605 r = new StringBuilder(256); 7606 } else { 7607 r.append(' '); 7608 } 7609 r.append(p.info.name); 7610 } 7611 } 7612 if (r != null) { 7613 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7614 } 7615 7616 N = pkg.services.size(); 7617 r = null; 7618 for (i=0; i<N; i++) { 7619 PackageParser.Service s = pkg.services.get(i); 7620 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7621 s.info.processName, pkg.applicationInfo.uid); 7622 mServices.addService(s); 7623 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7624 if (r == null) { 7625 r = new StringBuilder(256); 7626 } else { 7627 r.append(' '); 7628 } 7629 r.append(s.info.name); 7630 } 7631 } 7632 if (r != null) { 7633 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7634 } 7635 7636 N = pkg.receivers.size(); 7637 r = null; 7638 for (i=0; i<N; i++) { 7639 PackageParser.Activity a = pkg.receivers.get(i); 7640 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7641 a.info.processName, pkg.applicationInfo.uid); 7642 mReceivers.addActivity(a, "receiver"); 7643 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7644 if (r == null) { 7645 r = new StringBuilder(256); 7646 } else { 7647 r.append(' '); 7648 } 7649 r.append(a.info.name); 7650 } 7651 } 7652 if (r != null) { 7653 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7654 } 7655 7656 N = pkg.activities.size(); 7657 r = null; 7658 for (i=0; i<N; i++) { 7659 PackageParser.Activity a = pkg.activities.get(i); 7660 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7661 a.info.processName, pkg.applicationInfo.uid); 7662 mActivities.addActivity(a, "activity"); 7663 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7664 if (r == null) { 7665 r = new StringBuilder(256); 7666 } else { 7667 r.append(' '); 7668 } 7669 r.append(a.info.name); 7670 } 7671 } 7672 if (r != null) { 7673 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7674 } 7675 7676 N = pkg.permissionGroups.size(); 7677 r = null; 7678 for (i=0; i<N; i++) { 7679 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7680 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7681 if (cur == null) { 7682 mPermissionGroups.put(pg.info.name, pg); 7683 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7684 if (r == null) { 7685 r = new StringBuilder(256); 7686 } else { 7687 r.append(' '); 7688 } 7689 r.append(pg.info.name); 7690 } 7691 } else { 7692 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7693 + pg.info.packageName + " ignored: original from " 7694 + cur.info.packageName); 7695 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7696 if (r == null) { 7697 r = new StringBuilder(256); 7698 } else { 7699 r.append(' '); 7700 } 7701 r.append("DUP:"); 7702 r.append(pg.info.name); 7703 } 7704 } 7705 } 7706 if (r != null) { 7707 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7708 } 7709 7710 N = pkg.permissions.size(); 7711 r = null; 7712 for (i=0; i<N; i++) { 7713 PackageParser.Permission p = pkg.permissions.get(i); 7714 7715 // Assume by default that we did not install this permission into the system. 7716 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7717 7718 // Now that permission groups have a special meaning, we ignore permission 7719 // groups for legacy apps to prevent unexpected behavior. In particular, 7720 // permissions for one app being granted to someone just becuase they happen 7721 // to be in a group defined by another app (before this had no implications). 7722 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7723 p.group = mPermissionGroups.get(p.info.group); 7724 // Warn for a permission in an unknown group. 7725 if (p.info.group != null && p.group == null) { 7726 Slog.w(TAG, "Permission " + p.info.name + " from package " 7727 + p.info.packageName + " in an unknown group " + p.info.group); 7728 } 7729 } 7730 7731 ArrayMap<String, BasePermission> permissionMap = 7732 p.tree ? mSettings.mPermissionTrees 7733 : mSettings.mPermissions; 7734 BasePermission bp = permissionMap.get(p.info.name); 7735 7736 // Allow system apps to redefine non-system permissions 7737 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7738 final boolean currentOwnerIsSystem = (bp.perm != null 7739 && isSystemApp(bp.perm.owner)); 7740 if (isSystemApp(p.owner)) { 7741 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7742 // It's a built-in permission and no owner, take ownership now 7743 bp.packageSetting = pkgSetting; 7744 bp.perm = p; 7745 bp.uid = pkg.applicationInfo.uid; 7746 bp.sourcePackage = p.info.packageName; 7747 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7748 } else if (!currentOwnerIsSystem) { 7749 String msg = "New decl " + p.owner + " of permission " 7750 + p.info.name + " is system; overriding " + bp.sourcePackage; 7751 reportSettingsProblem(Log.WARN, msg); 7752 bp = null; 7753 } 7754 } 7755 } 7756 7757 if (bp == null) { 7758 bp = new BasePermission(p.info.name, p.info.packageName, 7759 BasePermission.TYPE_NORMAL); 7760 permissionMap.put(p.info.name, bp); 7761 } 7762 7763 if (bp.perm == null) { 7764 if (bp.sourcePackage == null 7765 || bp.sourcePackage.equals(p.info.packageName)) { 7766 BasePermission tree = findPermissionTreeLP(p.info.name); 7767 if (tree == null 7768 || tree.sourcePackage.equals(p.info.packageName)) { 7769 bp.packageSetting = pkgSetting; 7770 bp.perm = p; 7771 bp.uid = pkg.applicationInfo.uid; 7772 bp.sourcePackage = p.info.packageName; 7773 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7774 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7775 if (r == null) { 7776 r = new StringBuilder(256); 7777 } else { 7778 r.append(' '); 7779 } 7780 r.append(p.info.name); 7781 } 7782 } else { 7783 Slog.w(TAG, "Permission " + p.info.name + " from package " 7784 + p.info.packageName + " ignored: base tree " 7785 + tree.name + " is from package " 7786 + tree.sourcePackage); 7787 } 7788 } else { 7789 Slog.w(TAG, "Permission " + p.info.name + " from package " 7790 + p.info.packageName + " ignored: original from " 7791 + bp.sourcePackage); 7792 } 7793 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7794 if (r == null) { 7795 r = new StringBuilder(256); 7796 } else { 7797 r.append(' '); 7798 } 7799 r.append("DUP:"); 7800 r.append(p.info.name); 7801 } 7802 if (bp.perm == p) { 7803 bp.protectionLevel = p.info.protectionLevel; 7804 } 7805 } 7806 7807 if (r != null) { 7808 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7809 } 7810 7811 N = pkg.instrumentation.size(); 7812 r = null; 7813 for (i=0; i<N; i++) { 7814 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7815 a.info.packageName = pkg.applicationInfo.packageName; 7816 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7817 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7818 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7819 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7820 a.info.dataDir = pkg.applicationInfo.dataDir; 7821 a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir; 7822 a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir; 7823 7824 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7825 // need other information about the application, like the ABI and what not ? 7826 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7827 mInstrumentation.put(a.getComponentName(), a); 7828 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7829 if (r == null) { 7830 r = new StringBuilder(256); 7831 } else { 7832 r.append(' '); 7833 } 7834 r.append(a.info.name); 7835 } 7836 } 7837 if (r != null) { 7838 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7839 } 7840 7841 if (pkg.protectedBroadcasts != null) { 7842 N = pkg.protectedBroadcasts.size(); 7843 for (i=0; i<N; i++) { 7844 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7845 } 7846 } 7847 7848 pkgSetting.setTimeStamp(scanFileTime); 7849 7850 // Create idmap files for pairs of (packages, overlay packages). 7851 // Note: "android", ie framework-res.apk, is handled by native layers. 7852 if (pkg.mOverlayTarget != null) { 7853 // This is an overlay package. 7854 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7855 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7856 mOverlays.put(pkg.mOverlayTarget, 7857 new ArrayMap<String, PackageParser.Package>()); 7858 } 7859 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7860 map.put(pkg.packageName, pkg); 7861 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7862 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7863 createIdmapFailed = true; 7864 } 7865 } 7866 } else if (mOverlays.containsKey(pkg.packageName) && 7867 !pkg.packageName.equals("android")) { 7868 // This is a regular package, with one or more known overlay packages. 7869 createIdmapsForPackageLI(pkg); 7870 } 7871 } 7872 7873 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7874 7875 if (createIdmapFailed) { 7876 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7877 "scanPackageLI failed to createIdmap"); 7878 } 7879 return pkg; 7880 } 7881 7882 /** 7883 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7884 * is derived purely on the basis of the contents of {@code scanFile} and 7885 * {@code cpuAbiOverride}. 7886 * 7887 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7888 */ 7889 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7890 String cpuAbiOverride, boolean extractLibs) 7891 throws PackageManagerException { 7892 // TODO: We can probably be smarter about this stuff. For installed apps, 7893 // we can calculate this information at install time once and for all. For 7894 // system apps, we can probably assume that this information doesn't change 7895 // after the first boot scan. As things stand, we do lots of unnecessary work. 7896 7897 // Give ourselves some initial paths; we'll come back for another 7898 // pass once we've determined ABI below. 7899 setNativeLibraryPaths(pkg); 7900 7901 // We would never need to extract libs for forward-locked and external packages, 7902 // since the container service will do it for us. We shouldn't attempt to 7903 // extract libs from system app when it was not updated. 7904 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 7905 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 7906 extractLibs = false; 7907 } 7908 7909 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7910 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7911 7912 NativeLibraryHelper.Handle handle = null; 7913 try { 7914 handle = NativeLibraryHelper.Handle.create(pkg); 7915 // TODO(multiArch): This can be null for apps that didn't go through the 7916 // usual installation process. We can calculate it again, like we 7917 // do during install time. 7918 // 7919 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7920 // unnecessary. 7921 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7922 7923 // Null out the abis so that they can be recalculated. 7924 pkg.applicationInfo.primaryCpuAbi = null; 7925 pkg.applicationInfo.secondaryCpuAbi = null; 7926 if (isMultiArch(pkg.applicationInfo)) { 7927 // Warn if we've set an abiOverride for multi-lib packages.. 7928 // By definition, we need to copy both 32 and 64 bit libraries for 7929 // such packages. 7930 if (pkg.cpuAbiOverride != null 7931 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7932 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7933 } 7934 7935 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7936 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7937 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7938 if (extractLibs) { 7939 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7940 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7941 useIsaSpecificSubdirs); 7942 } else { 7943 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7944 } 7945 } 7946 7947 maybeThrowExceptionForMultiArchCopy( 7948 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7949 7950 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7951 if (extractLibs) { 7952 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7953 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7954 useIsaSpecificSubdirs); 7955 } else { 7956 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7957 } 7958 } 7959 7960 maybeThrowExceptionForMultiArchCopy( 7961 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7962 7963 if (abi64 >= 0) { 7964 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7965 } 7966 7967 if (abi32 >= 0) { 7968 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7969 if (abi64 >= 0) { 7970 pkg.applicationInfo.secondaryCpuAbi = abi; 7971 } else { 7972 pkg.applicationInfo.primaryCpuAbi = abi; 7973 } 7974 } 7975 if (cpuAbiOverride != null && 7976 cpuAbiOverride.equals(pkg.applicationInfo.secondaryCpuAbi)) { 7977 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 7978 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7979 } 7980 } else { 7981 String[] abiList = (cpuAbiOverride != null) ? 7982 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7983 7984 // Enable gross and lame hacks for apps that are built with old 7985 // SDK tools. We must scan their APKs for renderscript bitcode and 7986 // not launch them if it's present. Don't bother checking on devices 7987 // that don't have 64 bit support. 7988 boolean needsRenderScriptOverride = false; 7989 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7990 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7991 abiList = Build.SUPPORTED_32_BIT_ABIS; 7992 needsRenderScriptOverride = true; 7993 } 7994 7995 final int copyRet; 7996 if (extractLibs) { 7997 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7998 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7999 } else { 8000 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8001 } 8002 8003 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8004 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8005 "Error unpackaging native libs for app, errorCode=" + copyRet); 8006 } 8007 8008 if (copyRet >= 0) { 8009 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8010 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8011 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8012 } else if (needsRenderScriptOverride) { 8013 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8014 } 8015 } 8016 } catch (IOException ioe) { 8017 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8018 } finally { 8019 IoUtils.closeQuietly(handle); 8020 } 8021 8022 // Now that we've calculated the ABIs and determined if it's an internal app, 8023 // we will go ahead and populate the nativeLibraryPath. 8024 setNativeLibraryPaths(pkg); 8025 } 8026 8027 /** 8028 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8029 * i.e, so that all packages can be run inside a single process if required. 8030 * 8031 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8032 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8033 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8034 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8035 * updating a package that belongs to a shared user. 8036 * 8037 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8038 * adds unnecessary complexity. 8039 */ 8040 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8041 PackageParser.Package scannedPackage, boolean bootComplete) { 8042 String requiredInstructionSet = null; 8043 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8044 requiredInstructionSet = VMRuntime.getInstructionSet( 8045 scannedPackage.applicationInfo.primaryCpuAbi); 8046 } 8047 8048 PackageSetting requirer = null; 8049 for (PackageSetting ps : packagesForUser) { 8050 // If packagesForUser contains scannedPackage, we skip it. This will happen 8051 // when scannedPackage is an update of an existing package. Without this check, 8052 // we will never be able to change the ABI of any package belonging to a shared 8053 // user, even if it's compatible with other packages. 8054 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8055 if (ps.primaryCpuAbiString == null) { 8056 continue; 8057 } 8058 8059 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8060 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8061 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8062 // this but there's not much we can do. 8063 String errorMessage = "Instruction set mismatch, " 8064 + ((requirer == null) ? "[caller]" : requirer) 8065 + " requires " + requiredInstructionSet + " whereas " + ps 8066 + " requires " + instructionSet; 8067 Slog.w(TAG, errorMessage); 8068 } 8069 8070 if (requiredInstructionSet == null) { 8071 requiredInstructionSet = instructionSet; 8072 requirer = ps; 8073 } 8074 } 8075 } 8076 8077 if (requiredInstructionSet != null) { 8078 String adjustedAbi; 8079 if (requirer != null) { 8080 // requirer != null implies that either scannedPackage was null or that scannedPackage 8081 // did not require an ABI, in which case we have to adjust scannedPackage to match 8082 // the ABI of the set (which is the same as requirer's ABI) 8083 adjustedAbi = requirer.primaryCpuAbiString; 8084 if (scannedPackage != null) { 8085 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8086 } 8087 } else { 8088 // requirer == null implies that we're updating all ABIs in the set to 8089 // match scannedPackage. 8090 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8091 } 8092 8093 for (PackageSetting ps : packagesForUser) { 8094 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8095 if (ps.primaryCpuAbiString != null) { 8096 continue; 8097 } 8098 8099 ps.primaryCpuAbiString = adjustedAbi; 8100 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 8101 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8102 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi); 8103 try { 8104 mInstaller.rmdex(ps.codePathString, 8105 getDexCodeInstructionSet(getPreferredInstructionSet())); 8106 } catch (InstallerException ignored) { 8107 } 8108 } 8109 } 8110 } 8111 } 8112 } 8113 8114 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8115 synchronized (mPackages) { 8116 mResolverReplaced = true; 8117 // Set up information for custom user intent resolution activity. 8118 mResolveActivity.applicationInfo = pkg.applicationInfo; 8119 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8120 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8121 mResolveActivity.processName = pkg.applicationInfo.packageName; 8122 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8123 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8124 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8125 mResolveActivity.theme = 0; 8126 mResolveActivity.exported = true; 8127 mResolveActivity.enabled = true; 8128 mResolveInfo.activityInfo = mResolveActivity; 8129 mResolveInfo.priority = 0; 8130 mResolveInfo.preferredOrder = 0; 8131 mResolveInfo.match = 0; 8132 mResolveComponentName = mCustomResolverComponentName; 8133 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8134 mResolveComponentName); 8135 } 8136 } 8137 8138 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8139 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8140 8141 // Set up information for ephemeral installer activity 8142 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8143 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8144 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8145 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8146 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8147 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8148 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8149 mEphemeralInstallerActivity.theme = 0; 8150 mEphemeralInstallerActivity.exported = true; 8151 mEphemeralInstallerActivity.enabled = true; 8152 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8153 mEphemeralInstallerInfo.priority = 0; 8154 mEphemeralInstallerInfo.preferredOrder = 0; 8155 mEphemeralInstallerInfo.match = 0; 8156 8157 if (DEBUG_EPHEMERAL) { 8158 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8159 } 8160 } 8161 8162 private static String calculateBundledApkRoot(final String codePathString) { 8163 final File codePath = new File(codePathString); 8164 final File codeRoot; 8165 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8166 codeRoot = Environment.getRootDirectory(); 8167 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8168 codeRoot = Environment.getOemDirectory(); 8169 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8170 codeRoot = Environment.getVendorDirectory(); 8171 } else { 8172 // Unrecognized code path; take its top real segment as the apk root: 8173 // e.g. /something/app/blah.apk => /something 8174 try { 8175 File f = codePath.getCanonicalFile(); 8176 File parent = f.getParentFile(); // non-null because codePath is a file 8177 File tmp; 8178 while ((tmp = parent.getParentFile()) != null) { 8179 f = parent; 8180 parent = tmp; 8181 } 8182 codeRoot = f; 8183 Slog.w(TAG, "Unrecognized code path " 8184 + codePath + " - using " + codeRoot); 8185 } catch (IOException e) { 8186 // Can't canonicalize the code path -- shenanigans? 8187 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8188 return Environment.getRootDirectory().getPath(); 8189 } 8190 } 8191 return codeRoot.getPath(); 8192 } 8193 8194 /** 8195 * Derive and set the location of native libraries for the given package, 8196 * which varies depending on where and how the package was installed. 8197 */ 8198 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8199 final ApplicationInfo info = pkg.applicationInfo; 8200 final String codePath = pkg.codePath; 8201 final File codeFile = new File(codePath); 8202 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8203 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8204 8205 info.nativeLibraryRootDir = null; 8206 info.nativeLibraryRootRequiresIsa = false; 8207 info.nativeLibraryDir = null; 8208 info.secondaryNativeLibraryDir = null; 8209 8210 if (isApkFile(codeFile)) { 8211 // Monolithic install 8212 if (bundledApp) { 8213 // If "/system/lib64/apkname" exists, assume that is the per-package 8214 // native library directory to use; otherwise use "/system/lib/apkname". 8215 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8216 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8217 getPrimaryInstructionSet(info)); 8218 8219 // This is a bundled system app so choose the path based on the ABI. 8220 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8221 // is just the default path. 8222 final String apkName = deriveCodePathName(codePath); 8223 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8224 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8225 apkName).getAbsolutePath(); 8226 8227 if (info.secondaryCpuAbi != null) { 8228 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8229 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8230 secondaryLibDir, apkName).getAbsolutePath(); 8231 } 8232 } else if (asecApp) { 8233 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8234 .getAbsolutePath(); 8235 } else { 8236 final String apkName = deriveCodePathName(codePath); 8237 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8238 .getAbsolutePath(); 8239 } 8240 8241 info.nativeLibraryRootRequiresIsa = false; 8242 info.nativeLibraryDir = info.nativeLibraryRootDir; 8243 } else { 8244 // Cluster install 8245 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8246 info.nativeLibraryRootRequiresIsa = true; 8247 8248 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8249 getPrimaryInstructionSet(info)).getAbsolutePath(); 8250 8251 if (info.secondaryCpuAbi != null) { 8252 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8253 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8254 } 8255 } 8256 } 8257 8258 /** 8259 * Calculate the abis and roots for a bundled app. These can uniquely 8260 * be determined from the contents of the system partition, i.e whether 8261 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8262 * of this information, and instead assume that the system was built 8263 * sensibly. 8264 */ 8265 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8266 PackageSetting pkgSetting) { 8267 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8268 8269 // If "/system/lib64/apkname" exists, assume that is the per-package 8270 // native library directory to use; otherwise use "/system/lib/apkname". 8271 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8272 setBundledAppAbi(pkg, apkRoot, apkName); 8273 // pkgSetting might be null during rescan following uninstall of updates 8274 // to a bundled app, so accommodate that possibility. The settings in 8275 // that case will be established later from the parsed package. 8276 // 8277 // If the settings aren't null, sync them up with what we've just derived. 8278 // note that apkRoot isn't stored in the package settings. 8279 if (pkgSetting != null) { 8280 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8281 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8282 } 8283 } 8284 8285 /** 8286 * Deduces the ABI of a bundled app and sets the relevant fields on the 8287 * parsed pkg object. 8288 * 8289 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8290 * under which system libraries are installed. 8291 * @param apkName the name of the installed package. 8292 */ 8293 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8294 final File codeFile = new File(pkg.codePath); 8295 8296 final boolean has64BitLibs; 8297 final boolean has32BitLibs; 8298 if (isApkFile(codeFile)) { 8299 // Monolithic install 8300 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8301 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8302 } else { 8303 // Cluster install 8304 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8305 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8306 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8307 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8308 has64BitLibs = (new File(rootDir, isa)).exists(); 8309 } else { 8310 has64BitLibs = false; 8311 } 8312 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8313 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8314 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8315 has32BitLibs = (new File(rootDir, isa)).exists(); 8316 } else { 8317 has32BitLibs = false; 8318 } 8319 } 8320 8321 if (has64BitLibs && !has32BitLibs) { 8322 // The package has 64 bit libs, but not 32 bit libs. Its primary 8323 // ABI should be 64 bit. We can safely assume here that the bundled 8324 // native libraries correspond to the most preferred ABI in the list. 8325 8326 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8327 pkg.applicationInfo.secondaryCpuAbi = null; 8328 } else if (has32BitLibs && !has64BitLibs) { 8329 // The package has 32 bit libs but not 64 bit libs. Its primary 8330 // ABI should be 32 bit. 8331 8332 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8333 pkg.applicationInfo.secondaryCpuAbi = null; 8334 } else if (has32BitLibs && has64BitLibs) { 8335 // The application has both 64 and 32 bit bundled libraries. We check 8336 // here that the app declares multiArch support, and warn if it doesn't. 8337 // 8338 // We will be lenient here and record both ABIs. The primary will be the 8339 // ABI that's higher on the list, i.e, a device that's configured to prefer 8340 // 64 bit apps will see a 64 bit primary ABI, 8341 8342 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8343 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 8344 } 8345 8346 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8347 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8348 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8349 } else { 8350 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8351 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8352 } 8353 } else { 8354 pkg.applicationInfo.primaryCpuAbi = null; 8355 pkg.applicationInfo.secondaryCpuAbi = null; 8356 } 8357 } 8358 8359 private void killApplication(String pkgName, int appId, String reason) { 8360 // Request the ActivityManager to kill the process(only for existing packages) 8361 // so that we do not end up in a confused state while the user is still using the older 8362 // version of the application while the new one gets installed. 8363 IActivityManager am = ActivityManagerNative.getDefault(); 8364 if (am != null) { 8365 try { 8366 am.killApplicationWithAppId(pkgName, appId, reason); 8367 } catch (RemoteException e) { 8368 } 8369 } 8370 } 8371 8372 void removePackageLI(PackageSetting ps, boolean chatty) { 8373 if (DEBUG_INSTALL) { 8374 if (chatty) 8375 Log.d(TAG, "Removing package " + ps.name); 8376 } 8377 8378 // writer 8379 synchronized (mPackages) { 8380 mPackages.remove(ps.name); 8381 final PackageParser.Package pkg = ps.pkg; 8382 if (pkg != null) { 8383 cleanPackageDataStructuresLILPw(pkg, chatty); 8384 } 8385 } 8386 } 8387 8388 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8389 if (DEBUG_INSTALL) { 8390 if (chatty) 8391 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8392 } 8393 8394 // writer 8395 synchronized (mPackages) { 8396 mPackages.remove(pkg.applicationInfo.packageName); 8397 cleanPackageDataStructuresLILPw(pkg, chatty); 8398 } 8399 } 8400 8401 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8402 int N = pkg.providers.size(); 8403 StringBuilder r = null; 8404 int i; 8405 for (i=0; i<N; i++) { 8406 PackageParser.Provider p = pkg.providers.get(i); 8407 mProviders.removeProvider(p); 8408 if (p.info.authority == null) { 8409 8410 /* There was another ContentProvider with this authority when 8411 * this app was installed so this authority is null, 8412 * Ignore it as we don't have to unregister the provider. 8413 */ 8414 continue; 8415 } 8416 String names[] = p.info.authority.split(";"); 8417 for (int j = 0; j < names.length; j++) { 8418 if (mProvidersByAuthority.get(names[j]) == p) { 8419 mProvidersByAuthority.remove(names[j]); 8420 if (DEBUG_REMOVE) { 8421 if (chatty) 8422 Log.d(TAG, "Unregistered content provider: " + names[j] 8423 + ", className = " + p.info.name + ", isSyncable = " 8424 + p.info.isSyncable); 8425 } 8426 } 8427 } 8428 if (DEBUG_REMOVE && chatty) { 8429 if (r == null) { 8430 r = new StringBuilder(256); 8431 } else { 8432 r.append(' '); 8433 } 8434 r.append(p.info.name); 8435 } 8436 } 8437 if (r != null) { 8438 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8439 } 8440 8441 N = pkg.services.size(); 8442 r = null; 8443 for (i=0; i<N; i++) { 8444 PackageParser.Service s = pkg.services.get(i); 8445 mServices.removeService(s); 8446 if (chatty) { 8447 if (r == null) { 8448 r = new StringBuilder(256); 8449 } else { 8450 r.append(' '); 8451 } 8452 r.append(s.info.name); 8453 } 8454 } 8455 if (r != null) { 8456 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8457 } 8458 8459 N = pkg.receivers.size(); 8460 r = null; 8461 for (i=0; i<N; i++) { 8462 PackageParser.Activity a = pkg.receivers.get(i); 8463 mReceivers.removeActivity(a, "receiver"); 8464 if (DEBUG_REMOVE && chatty) { 8465 if (r == null) { 8466 r = new StringBuilder(256); 8467 } else { 8468 r.append(' '); 8469 } 8470 r.append(a.info.name); 8471 } 8472 } 8473 if (r != null) { 8474 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8475 } 8476 8477 N = pkg.activities.size(); 8478 r = null; 8479 for (i=0; i<N; i++) { 8480 PackageParser.Activity a = pkg.activities.get(i); 8481 mActivities.removeActivity(a, "activity"); 8482 if (DEBUG_REMOVE && chatty) { 8483 if (r == null) { 8484 r = new StringBuilder(256); 8485 } else { 8486 r.append(' '); 8487 } 8488 r.append(a.info.name); 8489 } 8490 } 8491 if (r != null) { 8492 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8493 } 8494 8495 N = pkg.permissions.size(); 8496 r = null; 8497 for (i=0; i<N; i++) { 8498 PackageParser.Permission p = pkg.permissions.get(i); 8499 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8500 if (bp == null) { 8501 bp = mSettings.mPermissionTrees.get(p.info.name); 8502 } 8503 if (bp != null && bp.perm == p) { 8504 bp.perm = null; 8505 if (DEBUG_REMOVE && chatty) { 8506 if (r == null) { 8507 r = new StringBuilder(256); 8508 } else { 8509 r.append(' '); 8510 } 8511 r.append(p.info.name); 8512 } 8513 } 8514 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8515 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 8516 if (appOpPkgs != null) { 8517 appOpPkgs.remove(pkg.packageName); 8518 } 8519 } 8520 } 8521 if (r != null) { 8522 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8523 } 8524 8525 N = pkg.requestedPermissions.size(); 8526 r = null; 8527 for (i=0; i<N; i++) { 8528 String perm = pkg.requestedPermissions.get(i); 8529 BasePermission bp = mSettings.mPermissions.get(perm); 8530 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8531 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 8532 if (appOpPkgs != null) { 8533 appOpPkgs.remove(pkg.packageName); 8534 if (appOpPkgs.isEmpty()) { 8535 mAppOpPermissionPackages.remove(perm); 8536 } 8537 } 8538 } 8539 } 8540 if (r != null) { 8541 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8542 } 8543 8544 N = pkg.instrumentation.size(); 8545 r = null; 8546 for (i=0; i<N; i++) { 8547 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8548 mInstrumentation.remove(a.getComponentName()); 8549 if (DEBUG_REMOVE && chatty) { 8550 if (r == null) { 8551 r = new StringBuilder(256); 8552 } else { 8553 r.append(' '); 8554 } 8555 r.append(a.info.name); 8556 } 8557 } 8558 if (r != null) { 8559 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8560 } 8561 8562 r = null; 8563 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8564 // Only system apps can hold shared libraries. 8565 if (pkg.libraryNames != null) { 8566 for (i=0; i<pkg.libraryNames.size(); i++) { 8567 String name = pkg.libraryNames.get(i); 8568 SharedLibraryEntry cur = mSharedLibraries.get(name); 8569 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8570 mSharedLibraries.remove(name); 8571 if (DEBUG_REMOVE && chatty) { 8572 if (r == null) { 8573 r = new StringBuilder(256); 8574 } else { 8575 r.append(' '); 8576 } 8577 r.append(name); 8578 } 8579 } 8580 } 8581 } 8582 } 8583 if (r != null) { 8584 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8585 } 8586 } 8587 8588 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8589 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8590 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8591 return true; 8592 } 8593 } 8594 return false; 8595 } 8596 8597 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8598 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8599 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8600 8601 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 8602 int flags) { 8603 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 8604 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 8605 } 8606 8607 private void updatePermissionsLPw(String changingPkg, 8608 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 8609 // Make sure there are no dangling permission trees. 8610 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8611 while (it.hasNext()) { 8612 final BasePermission bp = it.next(); 8613 if (bp.packageSetting == null) { 8614 // We may not yet have parsed the package, so just see if 8615 // we still know about its settings. 8616 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8617 } 8618 if (bp.packageSetting == null) { 8619 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8620 + " from package " + bp.sourcePackage); 8621 it.remove(); 8622 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8623 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8624 Slog.i(TAG, "Removing old permission tree: " + bp.name 8625 + " from package " + bp.sourcePackage); 8626 flags |= UPDATE_PERMISSIONS_ALL; 8627 it.remove(); 8628 } 8629 } 8630 } 8631 8632 // Make sure all dynamic permissions have been assigned to a package, 8633 // and make sure there are no dangling permissions. 8634 it = mSettings.mPermissions.values().iterator(); 8635 while (it.hasNext()) { 8636 final BasePermission bp = it.next(); 8637 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8638 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8639 + bp.name + " pkg=" + bp.sourcePackage 8640 + " info=" + bp.pendingInfo); 8641 if (bp.packageSetting == null && bp.pendingInfo != null) { 8642 final BasePermission tree = findPermissionTreeLP(bp.name); 8643 if (tree != null && tree.perm != null) { 8644 bp.packageSetting = tree.packageSetting; 8645 bp.perm = new PackageParser.Permission(tree.perm.owner, 8646 new PermissionInfo(bp.pendingInfo)); 8647 bp.perm.info.packageName = tree.perm.info.packageName; 8648 bp.perm.info.name = bp.name; 8649 bp.uid = tree.uid; 8650 } 8651 } 8652 } 8653 if (bp.packageSetting == null) { 8654 // We may not yet have parsed the package, so just see if 8655 // we still know about its settings. 8656 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8657 } 8658 if (bp.packageSetting == null) { 8659 Slog.w(TAG, "Removing dangling permission: " + bp.name 8660 + " from package " + bp.sourcePackage); 8661 it.remove(); 8662 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8663 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8664 Slog.i(TAG, "Removing old permission: " + bp.name 8665 + " from package " + bp.sourcePackage); 8666 flags |= UPDATE_PERMISSIONS_ALL; 8667 it.remove(); 8668 } 8669 } 8670 } 8671 8672 // Now update the permissions for all packages, in particular 8673 // replace the granted permissions of the system packages. 8674 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8675 for (PackageParser.Package pkg : mPackages.values()) { 8676 if (pkg != pkgInfo) { 8677 // Only replace for packages on requested volume 8678 final String volumeUuid = getVolumeUuidForPackage(pkg); 8679 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 8680 && Objects.equals(replaceVolumeUuid, volumeUuid); 8681 grantPermissionsLPw(pkg, replace, changingPkg); 8682 } 8683 } 8684 } 8685 8686 if (pkgInfo != null) { 8687 // Only replace for packages on requested volume 8688 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 8689 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 8690 && Objects.equals(replaceVolumeUuid, volumeUuid); 8691 grantPermissionsLPw(pkgInfo, replace, changingPkg); 8692 } 8693 } 8694 8695 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8696 String packageOfInterest) { 8697 // IMPORTANT: There are two types of permissions: install and runtime. 8698 // Install time permissions are granted when the app is installed to 8699 // all device users and users added in the future. Runtime permissions 8700 // are granted at runtime explicitly to specific users. Normal and signature 8701 // protected permissions are install time permissions. Dangerous permissions 8702 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8703 // otherwise they are runtime permissions. This function does not manage 8704 // runtime permissions except for the case an app targeting Lollipop MR1 8705 // being upgraded to target a newer SDK, in which case dangerous permissions 8706 // are transformed from install time to runtime ones. 8707 8708 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8709 if (ps == null) { 8710 return; 8711 } 8712 8713 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 8714 8715 PermissionsState permissionsState = ps.getPermissionsState(); 8716 PermissionsState origPermissions = permissionsState; 8717 8718 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8719 8720 boolean runtimePermissionsRevoked = false; 8721 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8722 8723 boolean changedInstallPermission = false; 8724 8725 if (replace) { 8726 ps.installPermissionsFixed = false; 8727 if (!ps.isSharedUser()) { 8728 origPermissions = new PermissionsState(permissionsState); 8729 permissionsState.reset(); 8730 } else { 8731 // We need to know only about runtime permission changes since the 8732 // calling code always writes the install permissions state but 8733 // the runtime ones are written only if changed. The only cases of 8734 // changed runtime permissions here are promotion of an install to 8735 // runtime and revocation of a runtime from a shared user. 8736 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 8737 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 8738 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 8739 runtimePermissionsRevoked = true; 8740 } 8741 } 8742 } 8743 8744 permissionsState.setGlobalGids(mGlobalGids); 8745 8746 final int N = pkg.requestedPermissions.size(); 8747 for (int i=0; i<N; i++) { 8748 final String name = pkg.requestedPermissions.get(i); 8749 final BasePermission bp = mSettings.mPermissions.get(name); 8750 8751 if (DEBUG_INSTALL) { 8752 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8753 } 8754 8755 if (bp == null || bp.packageSetting == null) { 8756 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8757 Slog.w(TAG, "Unknown permission " + name 8758 + " in package " + pkg.packageName); 8759 } 8760 continue; 8761 } 8762 8763 final String perm = bp.name; 8764 boolean allowedSig = false; 8765 int grant = GRANT_DENIED; 8766 8767 // Keep track of app op permissions. 8768 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8769 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8770 if (pkgs == null) { 8771 pkgs = new ArraySet<>(); 8772 mAppOpPermissionPackages.put(bp.name, pkgs); 8773 } 8774 pkgs.add(pkg.packageName); 8775 } 8776 8777 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8778 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 8779 >= Build.VERSION_CODES.M; 8780 switch (level) { 8781 case PermissionInfo.PROTECTION_NORMAL: { 8782 // For all apps normal permissions are install time ones. 8783 grant = GRANT_INSTALL; 8784 } break; 8785 8786 case PermissionInfo.PROTECTION_DANGEROUS: { 8787 // If a permission review is required for legacy apps we represent 8788 // their permissions as always granted runtime ones since we need 8789 // to keep the review required permission flag per user while an 8790 // install permission's state is shared across all users. 8791 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 8792 // For legacy apps dangerous permissions are install time ones. 8793 grant = GRANT_INSTALL; 8794 } else if (origPermissions.hasInstallPermission(bp.name)) { 8795 // For legacy apps that became modern, install becomes runtime. 8796 grant = GRANT_UPGRADE; 8797 } else if (mPromoteSystemApps 8798 && isSystemApp(ps) 8799 && mExistingSystemPackages.contains(ps.name)) { 8800 // For legacy system apps, install becomes runtime. 8801 // We cannot check hasInstallPermission() for system apps since those 8802 // permissions were granted implicitly and not persisted pre-M. 8803 grant = GRANT_UPGRADE; 8804 } else { 8805 // For modern apps keep runtime permissions unchanged. 8806 grant = GRANT_RUNTIME; 8807 } 8808 } break; 8809 8810 case PermissionInfo.PROTECTION_SIGNATURE: { 8811 // For all apps signature permissions are install time ones. 8812 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8813 if (allowedSig) { 8814 grant = GRANT_INSTALL; 8815 } 8816 } break; 8817 } 8818 8819 if (DEBUG_INSTALL) { 8820 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8821 } 8822 8823 if (grant != GRANT_DENIED) { 8824 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8825 // If this is an existing, non-system package, then 8826 // we can't add any new permissions to it. 8827 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8828 // Except... if this is a permission that was added 8829 // to the platform (note: need to only do this when 8830 // updating the platform). 8831 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8832 grant = GRANT_DENIED; 8833 } 8834 } 8835 } 8836 8837 switch (grant) { 8838 case GRANT_INSTALL: { 8839 // Revoke this as runtime permission to handle the case of 8840 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 8841 for (int userId : UserManagerService.getInstance().getUserIds()) { 8842 if (origPermissions.getRuntimePermissionState( 8843 bp.name, userId) != null) { 8844 // Revoke the runtime permission and clear the flags. 8845 origPermissions.revokeRuntimePermission(bp, userId); 8846 origPermissions.updatePermissionFlags(bp, userId, 8847 PackageManager.MASK_PERMISSION_FLAGS, 0); 8848 // If we revoked a permission permission, we have to write. 8849 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8850 changedRuntimePermissionUserIds, userId); 8851 } 8852 } 8853 // Grant an install permission. 8854 if (permissionsState.grantInstallPermission(bp) != 8855 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8856 changedInstallPermission = true; 8857 } 8858 } break; 8859 8860 case GRANT_RUNTIME: { 8861 // Grant previously granted runtime permissions. 8862 for (int userId : UserManagerService.getInstance().getUserIds()) { 8863 PermissionState permissionState = origPermissions 8864 .getRuntimePermissionState(bp.name, userId); 8865 int flags = permissionState != null 8866 ? permissionState.getFlags() : 0; 8867 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8868 if (permissionsState.grantRuntimePermission(bp, userId) == 8869 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8870 // If we cannot put the permission as it was, we have to write. 8871 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8872 changedRuntimePermissionUserIds, userId); 8873 } 8874 // If the app supports runtime permissions no need for a review. 8875 if (Build.PERMISSIONS_REVIEW_REQUIRED 8876 && appSupportsRuntimePermissions 8877 && (flags & PackageManager 8878 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 8879 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 8880 // Since we changed the flags, we have to write. 8881 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8882 changedRuntimePermissionUserIds, userId); 8883 } 8884 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 8885 && !appSupportsRuntimePermissions) { 8886 // For legacy apps that need a permission review, every new 8887 // runtime permission is granted but it is pending a review. 8888 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 8889 permissionsState.grantRuntimePermission(bp, userId); 8890 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 8891 // We changed the permission and flags, hence have to write. 8892 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8893 changedRuntimePermissionUserIds, userId); 8894 } 8895 } 8896 // Propagate the permission flags. 8897 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8898 } 8899 } break; 8900 8901 case GRANT_UPGRADE: { 8902 // Grant runtime permissions for a previously held install permission. 8903 PermissionState permissionState = origPermissions 8904 .getInstallPermissionState(bp.name); 8905 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8906 8907 if (origPermissions.revokeInstallPermission(bp) 8908 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8909 // We will be transferring the permission flags, so clear them. 8910 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8911 PackageManager.MASK_PERMISSION_FLAGS, 0); 8912 changedInstallPermission = true; 8913 } 8914 8915 // If the permission is not to be promoted to runtime we ignore it and 8916 // also its other flags as they are not applicable to install permissions. 8917 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8918 for (int userId : currentUserIds) { 8919 if (permissionsState.grantRuntimePermission(bp, userId) != 8920 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8921 // Transfer the permission flags. 8922 permissionsState.updatePermissionFlags(bp, userId, 8923 flags, flags); 8924 // If we granted the permission, we have to write. 8925 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8926 changedRuntimePermissionUserIds, userId); 8927 } 8928 } 8929 } 8930 } break; 8931 8932 default: { 8933 if (packageOfInterest == null 8934 || packageOfInterest.equals(pkg.packageName)) { 8935 Slog.w(TAG, "Not granting permission " + perm 8936 + " to package " + pkg.packageName 8937 + " because it was previously installed without"); 8938 } 8939 } break; 8940 } 8941 } else { 8942 if (permissionsState.revokeInstallPermission(bp) != 8943 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8944 // Also drop the permission flags. 8945 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8946 PackageManager.MASK_PERMISSION_FLAGS, 0); 8947 changedInstallPermission = true; 8948 Slog.i(TAG, "Un-granting permission " + perm 8949 + " from package " + pkg.packageName 8950 + " (protectionLevel=" + bp.protectionLevel 8951 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8952 + ")"); 8953 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8954 // Don't print warning for app op permissions, since it is fine for them 8955 // not to be granted, there is a UI for the user to decide. 8956 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8957 Slog.w(TAG, "Not granting permission " + perm 8958 + " to package " + pkg.packageName 8959 + " (protectionLevel=" + bp.protectionLevel 8960 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8961 + ")"); 8962 } 8963 } 8964 } 8965 } 8966 8967 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8968 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8969 // This is the first that we have heard about this package, so the 8970 // permissions we have now selected are fixed until explicitly 8971 // changed. 8972 ps.installPermissionsFixed = true; 8973 } 8974 8975 // Persist the runtime permissions state for users with changes. If permissions 8976 // were revoked because no app in the shared user declares them we have to 8977 // write synchronously to avoid losing runtime permissions state. 8978 for (int userId : changedRuntimePermissionUserIds) { 8979 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 8980 } 8981 8982 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8983 } 8984 8985 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8986 boolean allowed = false; 8987 final int NP = PackageParser.NEW_PERMISSIONS.length; 8988 for (int ip=0; ip<NP; ip++) { 8989 final PackageParser.NewPermissionInfo npi 8990 = PackageParser.NEW_PERMISSIONS[ip]; 8991 if (npi.name.equals(perm) 8992 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8993 allowed = true; 8994 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8995 + pkg.packageName); 8996 break; 8997 } 8998 } 8999 return allowed; 9000 } 9001 9002 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9003 BasePermission bp, PermissionsState origPermissions) { 9004 boolean allowed; 9005 allowed = (compareSignatures( 9006 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9007 == PackageManager.SIGNATURE_MATCH) 9008 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9009 == PackageManager.SIGNATURE_MATCH); 9010 if (!allowed && (bp.protectionLevel 9011 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9012 if (isSystemApp(pkg)) { 9013 // For updated system applications, a system permission 9014 // is granted only if it had been defined by the original application. 9015 if (pkg.isUpdatedSystemApp()) { 9016 final PackageSetting sysPs = mSettings 9017 .getDisabledSystemPkgLPr(pkg.packageName); 9018 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 9019 // If the original was granted this permission, we take 9020 // that grant decision as read and propagate it to the 9021 // update. 9022 if (sysPs.isPrivileged()) { 9023 allowed = true; 9024 } 9025 } else { 9026 // The system apk may have been updated with an older 9027 // version of the one on the data partition, but which 9028 // granted a new system permission that it didn't have 9029 // before. In this case we do want to allow the app to 9030 // now get the new permission if the ancestral apk is 9031 // privileged to get it. 9032 if (sysPs.pkg != null && sysPs.isPrivileged()) { 9033 for (int j=0; 9034 j<sysPs.pkg.requestedPermissions.size(); j++) { 9035 if (perm.equals( 9036 sysPs.pkg.requestedPermissions.get(j))) { 9037 allowed = true; 9038 break; 9039 } 9040 } 9041 } 9042 } 9043 } else { 9044 allowed = isPrivilegedApp(pkg); 9045 } 9046 } 9047 } 9048 if (!allowed) { 9049 if (!allowed && (bp.protectionLevel 9050 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9051 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9052 // If this was a previously normal/dangerous permission that got moved 9053 // to a system permission as part of the runtime permission redesign, then 9054 // we still want to blindly grant it to old apps. 9055 allowed = true; 9056 } 9057 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9058 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9059 // If this permission is to be granted to the system installer and 9060 // this app is an installer, then it gets the permission. 9061 allowed = true; 9062 } 9063 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9064 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9065 // If this permission is to be granted to the system verifier and 9066 // this app is a verifier, then it gets the permission. 9067 allowed = true; 9068 } 9069 if (!allowed && (bp.protectionLevel 9070 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9071 && isSystemApp(pkg)) { 9072 // Any pre-installed system app is allowed to get this permission. 9073 allowed = true; 9074 } 9075 if (!allowed && (bp.protectionLevel 9076 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9077 // For development permissions, a development permission 9078 // is granted only if it was already granted. 9079 allowed = origPermissions.hasInstallPermission(perm); 9080 } 9081 } 9082 return allowed; 9083 } 9084 9085 final class ActivityIntentResolver 9086 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9087 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9088 boolean defaultOnly, int userId) { 9089 if (!sUserManager.exists(userId)) return null; 9090 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9091 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9092 } 9093 9094 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9095 int userId) { 9096 if (!sUserManager.exists(userId)) return null; 9097 mFlags = flags; 9098 return super.queryIntent(intent, resolvedType, 9099 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9100 } 9101 9102 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9103 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9104 if (!sUserManager.exists(userId)) return null; 9105 if (packageActivities == null) { 9106 return null; 9107 } 9108 mFlags = flags; 9109 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9110 final int N = packageActivities.size(); 9111 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9112 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9113 9114 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9115 for (int i = 0; i < N; ++i) { 9116 intentFilters = packageActivities.get(i).intents; 9117 if (intentFilters != null && intentFilters.size() > 0) { 9118 PackageParser.ActivityIntentInfo[] array = 9119 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9120 intentFilters.toArray(array); 9121 listCut.add(array); 9122 } 9123 } 9124 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9125 } 9126 9127 public final void addActivity(PackageParser.Activity a, String type) { 9128 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 9129 mActivities.put(a.getComponentName(), a); 9130 if (DEBUG_SHOW_INFO) 9131 Log.v( 9132 TAG, " " + type + " " + 9133 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 9134 if (DEBUG_SHOW_INFO) 9135 Log.v(TAG, " Class=" + a.info.name); 9136 final int NI = a.intents.size(); 9137 for (int j=0; j<NI; j++) { 9138 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9139 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 9140 intent.setPriority(0); 9141 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 9142 + a.className + " with priority > 0, forcing to 0"); 9143 } 9144 if (DEBUG_SHOW_INFO) { 9145 Log.v(TAG, " IntentFilter:"); 9146 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9147 } 9148 if (!intent.debugCheck()) { 9149 Log.w(TAG, "==> For Activity " + a.info.name); 9150 } 9151 addFilter(intent); 9152 } 9153 } 9154 9155 public final void removeActivity(PackageParser.Activity a, String type) { 9156 mActivities.remove(a.getComponentName()); 9157 if (DEBUG_SHOW_INFO) { 9158 Log.v(TAG, " " + type + " " 9159 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 9160 : a.info.name) + ":"); 9161 Log.v(TAG, " Class=" + a.info.name); 9162 } 9163 final int NI = a.intents.size(); 9164 for (int j=0; j<NI; j++) { 9165 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9166 if (DEBUG_SHOW_INFO) { 9167 Log.v(TAG, " IntentFilter:"); 9168 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9169 } 9170 removeFilter(intent); 9171 } 9172 } 9173 9174 @Override 9175 protected boolean allowFilterResult( 9176 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 9177 ActivityInfo filterAi = filter.activity.info; 9178 for (int i=dest.size()-1; i>=0; i--) { 9179 ActivityInfo destAi = dest.get(i).activityInfo; 9180 if (destAi.name == filterAi.name 9181 && destAi.packageName == filterAi.packageName) { 9182 return false; 9183 } 9184 } 9185 return true; 9186 } 9187 9188 @Override 9189 protected ActivityIntentInfo[] newArray(int size) { 9190 return new ActivityIntentInfo[size]; 9191 } 9192 9193 @Override 9194 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 9195 if (!sUserManager.exists(userId)) return true; 9196 PackageParser.Package p = filter.activity.owner; 9197 if (p != null) { 9198 PackageSetting ps = (PackageSetting)p.mExtras; 9199 if (ps != null) { 9200 // System apps are never considered stopped for purposes of 9201 // filtering, because there may be no way for the user to 9202 // actually re-launch them. 9203 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 9204 && ps.getStopped(userId); 9205 } 9206 } 9207 return false; 9208 } 9209 9210 @Override 9211 protected boolean isPackageForFilter(String packageName, 9212 PackageParser.ActivityIntentInfo info) { 9213 return packageName.equals(info.activity.owner.packageName); 9214 } 9215 9216 @Override 9217 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 9218 int match, int userId) { 9219 if (!sUserManager.exists(userId)) return null; 9220 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 9221 return null; 9222 } 9223 final PackageParser.Activity activity = info.activity; 9224 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 9225 if (ps == null) { 9226 return null; 9227 } 9228 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 9229 ps.readUserState(userId), userId); 9230 if (ai == null) { 9231 return null; 9232 } 9233 final ResolveInfo res = new ResolveInfo(); 9234 res.activityInfo = ai; 9235 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9236 res.filter = info; 9237 } 9238 if (info != null) { 9239 res.handleAllWebDataURI = info.handleAllWebDataURI(); 9240 } 9241 res.priority = info.getPriority(); 9242 res.preferredOrder = activity.owner.mPreferredOrder; 9243 //System.out.println("Result: " + res.activityInfo.className + 9244 // " = " + res.priority); 9245 res.match = match; 9246 res.isDefault = info.hasDefault; 9247 res.labelRes = info.labelRes; 9248 res.nonLocalizedLabel = info.nonLocalizedLabel; 9249 if (userNeedsBadging(userId)) { 9250 res.noResourceId = true; 9251 } else { 9252 res.icon = info.icon; 9253 } 9254 res.iconResourceId = info.icon; 9255 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9256 return res; 9257 } 9258 9259 @Override 9260 protected void sortResults(List<ResolveInfo> results) { 9261 Collections.sort(results, mResolvePrioritySorter); 9262 } 9263 9264 @Override 9265 protected void dumpFilter(PrintWriter out, String prefix, 9266 PackageParser.ActivityIntentInfo filter) { 9267 out.print(prefix); out.print( 9268 Integer.toHexString(System.identityHashCode(filter.activity))); 9269 out.print(' '); 9270 filter.activity.printComponentShortName(out); 9271 out.print(" filter "); 9272 out.println(Integer.toHexString(System.identityHashCode(filter))); 9273 } 9274 9275 @Override 9276 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9277 return filter.activity; 9278 } 9279 9280 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9281 PackageParser.Activity activity = (PackageParser.Activity)label; 9282 out.print(prefix); out.print( 9283 Integer.toHexString(System.identityHashCode(activity))); 9284 out.print(' '); 9285 activity.printComponentShortName(out); 9286 if (count > 1) { 9287 out.print(" ("); out.print(count); out.print(" filters)"); 9288 } 9289 out.println(); 9290 } 9291 9292// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9293// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9294// final List<ResolveInfo> retList = Lists.newArrayList(); 9295// while (i.hasNext()) { 9296// final ResolveInfo resolveInfo = i.next(); 9297// if (isEnabledLP(resolveInfo.activityInfo)) { 9298// retList.add(resolveInfo); 9299// } 9300// } 9301// return retList; 9302// } 9303 9304 // Keys are String (activity class name), values are Activity. 9305 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9306 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9307 private int mFlags; 9308 } 9309 9310 private final class ServiceIntentResolver 9311 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9312 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9313 boolean defaultOnly, int userId) { 9314 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9315 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9316 } 9317 9318 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9319 int userId) { 9320 if (!sUserManager.exists(userId)) return null; 9321 mFlags = flags; 9322 return super.queryIntent(intent, resolvedType, 9323 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9324 } 9325 9326 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9327 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9328 if (!sUserManager.exists(userId)) return null; 9329 if (packageServices == null) { 9330 return null; 9331 } 9332 mFlags = flags; 9333 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9334 final int N = packageServices.size(); 9335 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9336 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9337 9338 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9339 for (int i = 0; i < N; ++i) { 9340 intentFilters = packageServices.get(i).intents; 9341 if (intentFilters != null && intentFilters.size() > 0) { 9342 PackageParser.ServiceIntentInfo[] array = 9343 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9344 intentFilters.toArray(array); 9345 listCut.add(array); 9346 } 9347 } 9348 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9349 } 9350 9351 public final void addService(PackageParser.Service s) { 9352 mServices.put(s.getComponentName(), s); 9353 if (DEBUG_SHOW_INFO) { 9354 Log.v(TAG, " " 9355 + (s.info.nonLocalizedLabel != null 9356 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9357 Log.v(TAG, " Class=" + s.info.name); 9358 } 9359 final int NI = s.intents.size(); 9360 int j; 9361 for (j=0; j<NI; j++) { 9362 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9363 if (DEBUG_SHOW_INFO) { 9364 Log.v(TAG, " IntentFilter:"); 9365 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9366 } 9367 if (!intent.debugCheck()) { 9368 Log.w(TAG, "==> For Service " + s.info.name); 9369 } 9370 addFilter(intent); 9371 } 9372 } 9373 9374 public final void removeService(PackageParser.Service s) { 9375 mServices.remove(s.getComponentName()); 9376 if (DEBUG_SHOW_INFO) { 9377 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9378 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9379 Log.v(TAG, " Class=" + s.info.name); 9380 } 9381 final int NI = s.intents.size(); 9382 int j; 9383 for (j=0; j<NI; j++) { 9384 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9385 if (DEBUG_SHOW_INFO) { 9386 Log.v(TAG, " IntentFilter:"); 9387 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9388 } 9389 removeFilter(intent); 9390 } 9391 } 9392 9393 @Override 9394 protected boolean allowFilterResult( 9395 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9396 ServiceInfo filterSi = filter.service.info; 9397 for (int i=dest.size()-1; i>=0; i--) { 9398 ServiceInfo destAi = dest.get(i).serviceInfo; 9399 if (destAi.name == filterSi.name 9400 && destAi.packageName == filterSi.packageName) { 9401 return false; 9402 } 9403 } 9404 return true; 9405 } 9406 9407 @Override 9408 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9409 return new PackageParser.ServiceIntentInfo[size]; 9410 } 9411 9412 @Override 9413 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9414 if (!sUserManager.exists(userId)) return true; 9415 PackageParser.Package p = filter.service.owner; 9416 if (p != null) { 9417 PackageSetting ps = (PackageSetting)p.mExtras; 9418 if (ps != null) { 9419 // System apps are never considered stopped for purposes of 9420 // filtering, because there may be no way for the user to 9421 // actually re-launch them. 9422 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9423 && ps.getStopped(userId); 9424 } 9425 } 9426 return false; 9427 } 9428 9429 @Override 9430 protected boolean isPackageForFilter(String packageName, 9431 PackageParser.ServiceIntentInfo info) { 9432 return packageName.equals(info.service.owner.packageName); 9433 } 9434 9435 @Override 9436 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9437 int match, int userId) { 9438 if (!sUserManager.exists(userId)) return null; 9439 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9440 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 9441 return null; 9442 } 9443 final PackageParser.Service service = info.service; 9444 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9445 if (ps == null) { 9446 return null; 9447 } 9448 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9449 ps.readUserState(userId), userId); 9450 if (si == null) { 9451 return null; 9452 } 9453 final ResolveInfo res = new ResolveInfo(); 9454 res.serviceInfo = si; 9455 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9456 res.filter = filter; 9457 } 9458 res.priority = info.getPriority(); 9459 res.preferredOrder = service.owner.mPreferredOrder; 9460 res.match = match; 9461 res.isDefault = info.hasDefault; 9462 res.labelRes = info.labelRes; 9463 res.nonLocalizedLabel = info.nonLocalizedLabel; 9464 res.icon = info.icon; 9465 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9466 return res; 9467 } 9468 9469 @Override 9470 protected void sortResults(List<ResolveInfo> results) { 9471 Collections.sort(results, mResolvePrioritySorter); 9472 } 9473 9474 @Override 9475 protected void dumpFilter(PrintWriter out, String prefix, 9476 PackageParser.ServiceIntentInfo filter) { 9477 out.print(prefix); out.print( 9478 Integer.toHexString(System.identityHashCode(filter.service))); 9479 out.print(' '); 9480 filter.service.printComponentShortName(out); 9481 out.print(" filter "); 9482 out.println(Integer.toHexString(System.identityHashCode(filter))); 9483 } 9484 9485 @Override 9486 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9487 return filter.service; 9488 } 9489 9490 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9491 PackageParser.Service service = (PackageParser.Service)label; 9492 out.print(prefix); out.print( 9493 Integer.toHexString(System.identityHashCode(service))); 9494 out.print(' '); 9495 service.printComponentShortName(out); 9496 if (count > 1) { 9497 out.print(" ("); out.print(count); out.print(" filters)"); 9498 } 9499 out.println(); 9500 } 9501 9502// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9503// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9504// final List<ResolveInfo> retList = Lists.newArrayList(); 9505// while (i.hasNext()) { 9506// final ResolveInfo resolveInfo = (ResolveInfo) i; 9507// if (isEnabledLP(resolveInfo.serviceInfo)) { 9508// retList.add(resolveInfo); 9509// } 9510// } 9511// return retList; 9512// } 9513 9514 // Keys are String (activity class name), values are Activity. 9515 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9516 = new ArrayMap<ComponentName, PackageParser.Service>(); 9517 private int mFlags; 9518 }; 9519 9520 private final class ProviderIntentResolver 9521 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9522 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9523 boolean defaultOnly, int userId) { 9524 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9525 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9526 } 9527 9528 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9529 int userId) { 9530 if (!sUserManager.exists(userId)) 9531 return null; 9532 mFlags = flags; 9533 return super.queryIntent(intent, resolvedType, 9534 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9535 } 9536 9537 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9538 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9539 if (!sUserManager.exists(userId)) 9540 return null; 9541 if (packageProviders == null) { 9542 return null; 9543 } 9544 mFlags = flags; 9545 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9546 final int N = packageProviders.size(); 9547 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9548 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9549 9550 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9551 for (int i = 0; i < N; ++i) { 9552 intentFilters = packageProviders.get(i).intents; 9553 if (intentFilters != null && intentFilters.size() > 0) { 9554 PackageParser.ProviderIntentInfo[] array = 9555 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9556 intentFilters.toArray(array); 9557 listCut.add(array); 9558 } 9559 } 9560 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9561 } 9562 9563 public final void addProvider(PackageParser.Provider p) { 9564 if (mProviders.containsKey(p.getComponentName())) { 9565 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9566 return; 9567 } 9568 9569 mProviders.put(p.getComponentName(), p); 9570 if (DEBUG_SHOW_INFO) { 9571 Log.v(TAG, " " 9572 + (p.info.nonLocalizedLabel != null 9573 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9574 Log.v(TAG, " Class=" + p.info.name); 9575 } 9576 final int NI = p.intents.size(); 9577 int j; 9578 for (j = 0; j < NI; j++) { 9579 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9580 if (DEBUG_SHOW_INFO) { 9581 Log.v(TAG, " IntentFilter:"); 9582 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9583 } 9584 if (!intent.debugCheck()) { 9585 Log.w(TAG, "==> For Provider " + p.info.name); 9586 } 9587 addFilter(intent); 9588 } 9589 } 9590 9591 public final void removeProvider(PackageParser.Provider p) { 9592 mProviders.remove(p.getComponentName()); 9593 if (DEBUG_SHOW_INFO) { 9594 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9595 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9596 Log.v(TAG, " Class=" + p.info.name); 9597 } 9598 final int NI = p.intents.size(); 9599 int j; 9600 for (j = 0; j < NI; j++) { 9601 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9602 if (DEBUG_SHOW_INFO) { 9603 Log.v(TAG, " IntentFilter:"); 9604 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9605 } 9606 removeFilter(intent); 9607 } 9608 } 9609 9610 @Override 9611 protected boolean allowFilterResult( 9612 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9613 ProviderInfo filterPi = filter.provider.info; 9614 for (int i = dest.size() - 1; i >= 0; i--) { 9615 ProviderInfo destPi = dest.get(i).providerInfo; 9616 if (destPi.name == filterPi.name 9617 && destPi.packageName == filterPi.packageName) { 9618 return false; 9619 } 9620 } 9621 return true; 9622 } 9623 9624 @Override 9625 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9626 return new PackageParser.ProviderIntentInfo[size]; 9627 } 9628 9629 @Override 9630 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9631 if (!sUserManager.exists(userId)) 9632 return true; 9633 PackageParser.Package p = filter.provider.owner; 9634 if (p != null) { 9635 PackageSetting ps = (PackageSetting) p.mExtras; 9636 if (ps != null) { 9637 // System apps are never considered stopped for purposes of 9638 // filtering, because there may be no way for the user to 9639 // actually re-launch them. 9640 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9641 && ps.getStopped(userId); 9642 } 9643 } 9644 return false; 9645 } 9646 9647 @Override 9648 protected boolean isPackageForFilter(String packageName, 9649 PackageParser.ProviderIntentInfo info) { 9650 return packageName.equals(info.provider.owner.packageName); 9651 } 9652 9653 @Override 9654 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9655 int match, int userId) { 9656 if (!sUserManager.exists(userId)) 9657 return null; 9658 final PackageParser.ProviderIntentInfo info = filter; 9659 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 9660 return null; 9661 } 9662 final PackageParser.Provider provider = info.provider; 9663 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9664 if (ps == null) { 9665 return null; 9666 } 9667 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9668 ps.readUserState(userId), userId); 9669 if (pi == null) { 9670 return null; 9671 } 9672 final ResolveInfo res = new ResolveInfo(); 9673 res.providerInfo = pi; 9674 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9675 res.filter = filter; 9676 } 9677 res.priority = info.getPriority(); 9678 res.preferredOrder = provider.owner.mPreferredOrder; 9679 res.match = match; 9680 res.isDefault = info.hasDefault; 9681 res.labelRes = info.labelRes; 9682 res.nonLocalizedLabel = info.nonLocalizedLabel; 9683 res.icon = info.icon; 9684 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9685 return res; 9686 } 9687 9688 @Override 9689 protected void sortResults(List<ResolveInfo> results) { 9690 Collections.sort(results, mResolvePrioritySorter); 9691 } 9692 9693 @Override 9694 protected void dumpFilter(PrintWriter out, String prefix, 9695 PackageParser.ProviderIntentInfo filter) { 9696 out.print(prefix); 9697 out.print( 9698 Integer.toHexString(System.identityHashCode(filter.provider))); 9699 out.print(' '); 9700 filter.provider.printComponentShortName(out); 9701 out.print(" filter "); 9702 out.println(Integer.toHexString(System.identityHashCode(filter))); 9703 } 9704 9705 @Override 9706 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9707 return filter.provider; 9708 } 9709 9710 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9711 PackageParser.Provider provider = (PackageParser.Provider)label; 9712 out.print(prefix); out.print( 9713 Integer.toHexString(System.identityHashCode(provider))); 9714 out.print(' '); 9715 provider.printComponentShortName(out); 9716 if (count > 1) { 9717 out.print(" ("); out.print(count); out.print(" filters)"); 9718 } 9719 out.println(); 9720 } 9721 9722 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9723 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9724 private int mFlags; 9725 } 9726 9727 private static final class EphemeralIntentResolver 9728 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 9729 @Override 9730 protected EphemeralResolveIntentInfo[] newArray(int size) { 9731 return new EphemeralResolveIntentInfo[size]; 9732 } 9733 9734 @Override 9735 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 9736 return true; 9737 } 9738 9739 @Override 9740 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 9741 int userId) { 9742 if (!sUserManager.exists(userId)) { 9743 return null; 9744 } 9745 return info.getEphemeralResolveInfo(); 9746 } 9747 } 9748 9749 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9750 new Comparator<ResolveInfo>() { 9751 public int compare(ResolveInfo r1, ResolveInfo r2) { 9752 int v1 = r1.priority; 9753 int v2 = r2.priority; 9754 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9755 if (v1 != v2) { 9756 return (v1 > v2) ? -1 : 1; 9757 } 9758 v1 = r1.preferredOrder; 9759 v2 = r2.preferredOrder; 9760 if (v1 != v2) { 9761 return (v1 > v2) ? -1 : 1; 9762 } 9763 if (r1.isDefault != r2.isDefault) { 9764 return r1.isDefault ? -1 : 1; 9765 } 9766 v1 = r1.match; 9767 v2 = r2.match; 9768 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9769 if (v1 != v2) { 9770 return (v1 > v2) ? -1 : 1; 9771 } 9772 if (r1.system != r2.system) { 9773 return r1.system ? -1 : 1; 9774 } 9775 if (r1.activityInfo != null) { 9776 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 9777 } 9778 if (r1.serviceInfo != null) { 9779 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 9780 } 9781 if (r1.providerInfo != null) { 9782 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 9783 } 9784 return 0; 9785 } 9786 }; 9787 9788 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9789 new Comparator<ProviderInfo>() { 9790 public int compare(ProviderInfo p1, ProviderInfo p2) { 9791 final int v1 = p1.initOrder; 9792 final int v2 = p2.initOrder; 9793 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9794 } 9795 }; 9796 9797 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 9798 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 9799 final int[] userIds) { 9800 mHandler.post(new Runnable() { 9801 @Override 9802 public void run() { 9803 try { 9804 final IActivityManager am = ActivityManagerNative.getDefault(); 9805 if (am == null) return; 9806 final int[] resolvedUserIds; 9807 if (userIds == null) { 9808 resolvedUserIds = am.getRunningUserIds(); 9809 } else { 9810 resolvedUserIds = userIds; 9811 } 9812 for (int id : resolvedUserIds) { 9813 final Intent intent = new Intent(action, 9814 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9815 if (extras != null) { 9816 intent.putExtras(extras); 9817 } 9818 if (targetPkg != null) { 9819 intent.setPackage(targetPkg); 9820 } 9821 // Modify the UID when posting to other users 9822 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9823 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9824 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9825 intent.putExtra(Intent.EXTRA_UID, uid); 9826 } 9827 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9828 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 9829 if (DEBUG_BROADCASTS) { 9830 RuntimeException here = new RuntimeException("here"); 9831 here.fillInStackTrace(); 9832 Slog.d(TAG, "Sending to user " + id + ": " 9833 + intent.toShortString(false, true, false, false) 9834 + " " + intent.getExtras(), here); 9835 } 9836 am.broadcastIntent(null, intent, null, finishedReceiver, 9837 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9838 null, finishedReceiver != null, false, id); 9839 } 9840 } catch (RemoteException ex) { 9841 } 9842 } 9843 }); 9844 } 9845 9846 /** 9847 * Check if the external storage media is available. This is true if there 9848 * is a mounted external storage medium or if the external storage is 9849 * emulated. 9850 */ 9851 private boolean isExternalMediaAvailable() { 9852 return mMediaMounted || Environment.isExternalStorageEmulated(); 9853 } 9854 9855 @Override 9856 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9857 // writer 9858 synchronized (mPackages) { 9859 if (!isExternalMediaAvailable()) { 9860 // If the external storage is no longer mounted at this point, 9861 // the caller may not have been able to delete all of this 9862 // packages files and can not delete any more. Bail. 9863 return null; 9864 } 9865 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9866 if (lastPackage != null) { 9867 pkgs.remove(lastPackage); 9868 } 9869 if (pkgs.size() > 0) { 9870 return pkgs.get(0); 9871 } 9872 } 9873 return null; 9874 } 9875 9876 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9877 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9878 userId, andCode ? 1 : 0, packageName); 9879 if (mSystemReady) { 9880 msg.sendToTarget(); 9881 } else { 9882 if (mPostSystemReadyMessages == null) { 9883 mPostSystemReadyMessages = new ArrayList<>(); 9884 } 9885 mPostSystemReadyMessages.add(msg); 9886 } 9887 } 9888 9889 void startCleaningPackages() { 9890 // reader 9891 synchronized (mPackages) { 9892 if (!isExternalMediaAvailable()) { 9893 return; 9894 } 9895 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9896 return; 9897 } 9898 } 9899 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9900 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9901 IActivityManager am = ActivityManagerNative.getDefault(); 9902 if (am != null) { 9903 try { 9904 am.startService(null, intent, null, mContext.getOpPackageName(), 9905 UserHandle.USER_SYSTEM); 9906 } catch (RemoteException e) { 9907 } 9908 } 9909 } 9910 9911 @Override 9912 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9913 int installFlags, String installerPackageName, VerificationParams verificationParams, 9914 String packageAbiOverride) { 9915 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9916 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9917 } 9918 9919 @Override 9920 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9921 int installFlags, String installerPackageName, VerificationParams verificationParams, 9922 String packageAbiOverride, int userId) { 9923 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9924 9925 final int callingUid = Binder.getCallingUid(); 9926 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9927 9928 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9929 try { 9930 if (observer != null) { 9931 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9932 } 9933 } catch (RemoteException re) { 9934 } 9935 return; 9936 } 9937 9938 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9939 installFlags |= PackageManager.INSTALL_FROM_ADB; 9940 9941 } else { 9942 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9943 // about installerPackageName. 9944 9945 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9946 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9947 } 9948 9949 UserHandle user; 9950 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9951 user = UserHandle.ALL; 9952 } else { 9953 user = new UserHandle(userId); 9954 } 9955 9956 // Only system components can circumvent runtime permissions when installing. 9957 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9958 && mContext.checkCallingOrSelfPermission(Manifest.permission 9959 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9960 throw new SecurityException("You need the " 9961 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9962 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9963 } 9964 9965 verificationParams.setInstallerUid(callingUid); 9966 9967 final File originFile = new File(originPath); 9968 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9969 9970 final Message msg = mHandler.obtainMessage(INIT_COPY); 9971 final InstallParams params = new InstallParams(origin, null, observer, installFlags, 9972 installerPackageName, null, verificationParams, user, packageAbiOverride, null); 9973 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 9974 msg.obj = params; 9975 9976 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 9977 System.identityHashCode(msg.obj)); 9978 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9979 System.identityHashCode(msg.obj)); 9980 9981 mHandler.sendMessage(msg); 9982 } 9983 9984 void installStage(String packageName, File stagedDir, String stagedCid, 9985 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 9986 String installerPackageName, int installerUid, UserHandle user) { 9987 if (DEBUG_EPHEMERAL) { 9988 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 9989 Slog.d(TAG, "Ephemeral install of " + packageName); 9990 } 9991 } 9992 final VerificationParams verifParams = new VerificationParams( 9993 null, sessionParams.originatingUri, sessionParams.referrerUri, 9994 sessionParams.originatingUid); 9995 verifParams.setInstallerUid(installerUid); 9996 9997 final OriginInfo origin; 9998 if (stagedDir != null) { 9999 origin = OriginInfo.fromStagedFile(stagedDir); 10000 } else { 10001 origin = OriginInfo.fromStagedContainer(stagedCid); 10002 } 10003 10004 final Message msg = mHandler.obtainMessage(INIT_COPY); 10005 final InstallParams params = new InstallParams(origin, null, observer, 10006 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 10007 verifParams, user, sessionParams.abiOverride, 10008 sessionParams.grantedRuntimePermissions); 10009 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 10010 msg.obj = params; 10011 10012 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 10013 System.identityHashCode(msg.obj)); 10014 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10015 System.identityHashCode(msg.obj)); 10016 10017 mHandler.sendMessage(msg); 10018 } 10019 10020 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 10021 Bundle extras = new Bundle(1); 10022 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 10023 10024 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 10025 packageName, extras, 0, null, null, new int[] {userId}); 10026 try { 10027 IActivityManager am = ActivityManagerNative.getDefault(); 10028 final boolean isSystem = 10029 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 10030 if (isSystem && am.isUserRunning(userId, 0)) { 10031 // The just-installed/enabled app is bundled on the system, so presumed 10032 // to be able to run automatically without needing an explicit launch. 10033 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 10034 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 10035 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 10036 .setPackage(packageName); 10037 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 10038 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 10039 } 10040 } catch (RemoteException e) { 10041 // shouldn't happen 10042 Slog.w(TAG, "Unable to bootstrap installed package", e); 10043 } 10044 } 10045 10046 @Override 10047 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 10048 int userId) { 10049 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10050 PackageSetting pkgSetting; 10051 final int uid = Binder.getCallingUid(); 10052 enforceCrossUserPermission(uid, userId, true, true, 10053 "setApplicationHiddenSetting for user " + userId); 10054 10055 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 10056 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 10057 return false; 10058 } 10059 10060 long callingId = Binder.clearCallingIdentity(); 10061 try { 10062 boolean sendAdded = false; 10063 boolean sendRemoved = false; 10064 // writer 10065 synchronized (mPackages) { 10066 pkgSetting = mSettings.mPackages.get(packageName); 10067 if (pkgSetting == null) { 10068 return false; 10069 } 10070 if (pkgSetting.getHidden(userId) != hidden) { 10071 pkgSetting.setHidden(hidden, userId); 10072 mSettings.writePackageRestrictionsLPr(userId); 10073 if (hidden) { 10074 sendRemoved = true; 10075 } else { 10076 sendAdded = true; 10077 } 10078 } 10079 } 10080 if (sendAdded) { 10081 sendPackageAddedForUser(packageName, pkgSetting, userId); 10082 return true; 10083 } 10084 if (sendRemoved) { 10085 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 10086 "hiding pkg"); 10087 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 10088 return true; 10089 } 10090 } finally { 10091 Binder.restoreCallingIdentity(callingId); 10092 } 10093 return false; 10094 } 10095 10096 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 10097 int userId) { 10098 final PackageRemovedInfo info = new PackageRemovedInfo(); 10099 info.removedPackage = packageName; 10100 info.removedUsers = new int[] {userId}; 10101 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 10102 info.sendBroadcast(false, false, false); 10103 } 10104 10105 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 10106 if (pkgList.length > 0) { 10107 Bundle extras = new Bundle(1); 10108 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 10109 10110 sendPackageBroadcast( 10111 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 10112 : Intent.ACTION_PACKAGES_UNSUSPENDED, 10113 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 10114 new int[] {userId}); 10115 } 10116 } 10117 10118 /** 10119 * Returns true if application is not found or there was an error. Otherwise it returns 10120 * the hidden state of the package for the given user. 10121 */ 10122 @Override 10123 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 10124 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10125 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 10126 false, "getApplicationHidden for user " + userId); 10127 PackageSetting pkgSetting; 10128 long callingId = Binder.clearCallingIdentity(); 10129 try { 10130 // writer 10131 synchronized (mPackages) { 10132 pkgSetting = mSettings.mPackages.get(packageName); 10133 if (pkgSetting == null) { 10134 return true; 10135 } 10136 return pkgSetting.getHidden(userId); 10137 } 10138 } finally { 10139 Binder.restoreCallingIdentity(callingId); 10140 } 10141 } 10142 10143 /** 10144 * @hide 10145 */ 10146 @Override 10147 public int installExistingPackageAsUser(String packageName, int userId) { 10148 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 10149 null); 10150 PackageSetting pkgSetting; 10151 final int uid = Binder.getCallingUid(); 10152 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 10153 + userId); 10154 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10155 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 10156 } 10157 10158 long callingId = Binder.clearCallingIdentity(); 10159 try { 10160 boolean installed = false; 10161 10162 // writer 10163 synchronized (mPackages) { 10164 pkgSetting = mSettings.mPackages.get(packageName); 10165 if (pkgSetting == null) { 10166 return PackageManager.INSTALL_FAILED_INVALID_URI; 10167 } 10168 if (!pkgSetting.getInstalled(userId)) { 10169 pkgSetting.setInstalled(true, userId); 10170 pkgSetting.setHidden(false, userId); 10171 mSettings.writePackageRestrictionsLPr(userId); 10172 if (pkgSetting.pkg != null) { 10173 prepareAppDataAfterInstall(pkgSetting.pkg); 10174 } 10175 installed = true; 10176 } 10177 } 10178 10179 if (installed) { 10180 sendPackageAddedForUser(packageName, pkgSetting, userId); 10181 } 10182 } finally { 10183 Binder.restoreCallingIdentity(callingId); 10184 } 10185 10186 return PackageManager.INSTALL_SUCCEEDED; 10187 } 10188 10189 boolean isUserRestricted(int userId, String restrictionKey) { 10190 Bundle restrictions = sUserManager.getUserRestrictions(userId); 10191 if (restrictions.getBoolean(restrictionKey, false)) { 10192 Log.w(TAG, "User is restricted: " + restrictionKey); 10193 return true; 10194 } 10195 return false; 10196 } 10197 10198 @Override 10199 public boolean setPackageSuspendedAsUser(String packageName, boolean suspended, int userId) { 10200 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10201 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true, 10202 "setPackageSuspended for user " + userId); 10203 10204 // TODO: investigate and add more restrictions for suspending crucial packages. 10205 if (isPackageDeviceAdmin(packageName, userId)) { 10206 Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName 10207 + "\": has active device admin"); 10208 return false; 10209 } 10210 10211 long callingId = Binder.clearCallingIdentity(); 10212 try { 10213 boolean changed = false; 10214 boolean success = false; 10215 int appId = -1; 10216 synchronized (mPackages) { 10217 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10218 if (pkgSetting != null) { 10219 if (pkgSetting.getSuspended(userId) != suspended) { 10220 pkgSetting.setSuspended(suspended, userId); 10221 mSettings.writePackageRestrictionsLPr(userId); 10222 appId = pkgSetting.appId; 10223 changed = true; 10224 } 10225 success = true; 10226 } 10227 } 10228 10229 if (changed) { 10230 sendPackagesSuspendedForUser(new String[]{packageName}, userId, suspended); 10231 if (suspended) { 10232 killApplication(packageName, UserHandle.getUid(userId, appId), 10233 "suspending package"); 10234 } 10235 } 10236 return success; 10237 } finally { 10238 Binder.restoreCallingIdentity(callingId); 10239 } 10240 } 10241 10242 @Override 10243 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 10244 mContext.enforceCallingOrSelfPermission( 10245 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10246 "Only package verification agents can verify applications"); 10247 10248 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10249 final PackageVerificationResponse response = new PackageVerificationResponse( 10250 verificationCode, Binder.getCallingUid()); 10251 msg.arg1 = id; 10252 msg.obj = response; 10253 mHandler.sendMessage(msg); 10254 } 10255 10256 @Override 10257 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 10258 long millisecondsToDelay) { 10259 mContext.enforceCallingOrSelfPermission( 10260 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10261 "Only package verification agents can extend verification timeouts"); 10262 10263 final PackageVerificationState state = mPendingVerification.get(id); 10264 final PackageVerificationResponse response = new PackageVerificationResponse( 10265 verificationCodeAtTimeout, Binder.getCallingUid()); 10266 10267 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 10268 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 10269 } 10270 if (millisecondsToDelay < 0) { 10271 millisecondsToDelay = 0; 10272 } 10273 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 10274 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 10275 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 10276 } 10277 10278 if ((state != null) && !state.timeoutExtended()) { 10279 state.extendTimeout(); 10280 10281 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10282 msg.arg1 = id; 10283 msg.obj = response; 10284 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 10285 } 10286 } 10287 10288 private void broadcastPackageVerified(int verificationId, Uri packageUri, 10289 int verificationCode, UserHandle user) { 10290 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 10291 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 10292 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10293 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10294 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 10295 10296 mContext.sendBroadcastAsUser(intent, user, 10297 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 10298 } 10299 10300 private ComponentName matchComponentForVerifier(String packageName, 10301 List<ResolveInfo> receivers) { 10302 ActivityInfo targetReceiver = null; 10303 10304 final int NR = receivers.size(); 10305 for (int i = 0; i < NR; i++) { 10306 final ResolveInfo info = receivers.get(i); 10307 if (info.activityInfo == null) { 10308 continue; 10309 } 10310 10311 if (packageName.equals(info.activityInfo.packageName)) { 10312 targetReceiver = info.activityInfo; 10313 break; 10314 } 10315 } 10316 10317 if (targetReceiver == null) { 10318 return null; 10319 } 10320 10321 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 10322 } 10323 10324 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 10325 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 10326 if (pkgInfo.verifiers.length == 0) { 10327 return null; 10328 } 10329 10330 final int N = pkgInfo.verifiers.length; 10331 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 10332 for (int i = 0; i < N; i++) { 10333 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 10334 10335 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 10336 receivers); 10337 if (comp == null) { 10338 continue; 10339 } 10340 10341 final int verifierUid = getUidForVerifier(verifierInfo); 10342 if (verifierUid == -1) { 10343 continue; 10344 } 10345 10346 if (DEBUG_VERIFY) { 10347 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 10348 + " with the correct signature"); 10349 } 10350 sufficientVerifiers.add(comp); 10351 verificationState.addSufficientVerifier(verifierUid); 10352 } 10353 10354 return sufficientVerifiers; 10355 } 10356 10357 private int getUidForVerifier(VerifierInfo verifierInfo) { 10358 synchronized (mPackages) { 10359 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 10360 if (pkg == null) { 10361 return -1; 10362 } else if (pkg.mSignatures.length != 1) { 10363 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10364 + " has more than one signature; ignoring"); 10365 return -1; 10366 } 10367 10368 /* 10369 * If the public key of the package's signature does not match 10370 * our expected public key, then this is a different package and 10371 * we should skip. 10372 */ 10373 10374 final byte[] expectedPublicKey; 10375 try { 10376 final Signature verifierSig = pkg.mSignatures[0]; 10377 final PublicKey publicKey = verifierSig.getPublicKey(); 10378 expectedPublicKey = publicKey.getEncoded(); 10379 } catch (CertificateException e) { 10380 return -1; 10381 } 10382 10383 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 10384 10385 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 10386 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10387 + " does not have the expected public key; ignoring"); 10388 return -1; 10389 } 10390 10391 return pkg.applicationInfo.uid; 10392 } 10393 } 10394 10395 @Override 10396 public void finishPackageInstall(int token) { 10397 enforceSystemOrRoot("Only the system is allowed to finish installs"); 10398 10399 if (DEBUG_INSTALL) { 10400 Slog.v(TAG, "BM finishing package install for " + token); 10401 } 10402 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10403 10404 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10405 mHandler.sendMessage(msg); 10406 } 10407 10408 /** 10409 * Get the verification agent timeout. 10410 * 10411 * @return verification timeout in milliseconds 10412 */ 10413 private long getVerificationTimeout() { 10414 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 10415 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 10416 DEFAULT_VERIFICATION_TIMEOUT); 10417 } 10418 10419 /** 10420 * Get the default verification agent response code. 10421 * 10422 * @return default verification response code 10423 */ 10424 private int getDefaultVerificationResponse() { 10425 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10426 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 10427 DEFAULT_VERIFICATION_RESPONSE); 10428 } 10429 10430 /** 10431 * Check whether or not package verification has been enabled. 10432 * 10433 * @return true if verification should be performed 10434 */ 10435 private boolean isVerificationEnabled(int userId, int installFlags) { 10436 if (!DEFAULT_VERIFY_ENABLE) { 10437 return false; 10438 } 10439 // Ephemeral apps don't get the full verification treatment 10440 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10441 if (DEBUG_EPHEMERAL) { 10442 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 10443 } 10444 return false; 10445 } 10446 10447 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 10448 10449 // Check if installing from ADB 10450 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 10451 // Do not run verification in a test harness environment 10452 if (ActivityManager.isRunningInTestHarness()) { 10453 return false; 10454 } 10455 if (ensureVerifyAppsEnabled) { 10456 return true; 10457 } 10458 // Check if the developer does not want package verification for ADB installs 10459 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10460 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 10461 return false; 10462 } 10463 } 10464 10465 if (ensureVerifyAppsEnabled) { 10466 return true; 10467 } 10468 10469 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10470 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 10471 } 10472 10473 @Override 10474 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 10475 throws RemoteException { 10476 mContext.enforceCallingOrSelfPermission( 10477 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 10478 "Only intentfilter verification agents can verify applications"); 10479 10480 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 10481 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 10482 Binder.getCallingUid(), verificationCode, failedDomains); 10483 msg.arg1 = id; 10484 msg.obj = response; 10485 mHandler.sendMessage(msg); 10486 } 10487 10488 @Override 10489 public int getIntentVerificationStatus(String packageName, int userId) { 10490 synchronized (mPackages) { 10491 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10492 } 10493 } 10494 10495 @Override 10496 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10497 mContext.enforceCallingOrSelfPermission( 10498 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10499 10500 boolean result = false; 10501 synchronized (mPackages) { 10502 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10503 } 10504 if (result) { 10505 scheduleWritePackageRestrictionsLocked(userId); 10506 } 10507 return result; 10508 } 10509 10510 @Override 10511 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10512 synchronized (mPackages) { 10513 return mSettings.getIntentFilterVerificationsLPr(packageName); 10514 } 10515 } 10516 10517 @Override 10518 public List<IntentFilter> getAllIntentFilters(String packageName) { 10519 if (TextUtils.isEmpty(packageName)) { 10520 return Collections.<IntentFilter>emptyList(); 10521 } 10522 synchronized (mPackages) { 10523 PackageParser.Package pkg = mPackages.get(packageName); 10524 if (pkg == null || pkg.activities == null) { 10525 return Collections.<IntentFilter>emptyList(); 10526 } 10527 final int count = pkg.activities.size(); 10528 ArrayList<IntentFilter> result = new ArrayList<>(); 10529 for (int n=0; n<count; n++) { 10530 PackageParser.Activity activity = pkg.activities.get(n); 10531 if (activity.intents != null && activity.intents.size() > 0) { 10532 result.addAll(activity.intents); 10533 } 10534 } 10535 return result; 10536 } 10537 } 10538 10539 @Override 10540 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10541 mContext.enforceCallingOrSelfPermission( 10542 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10543 10544 synchronized (mPackages) { 10545 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10546 if (packageName != null) { 10547 result |= updateIntentVerificationStatus(packageName, 10548 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10549 userId); 10550 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10551 packageName, userId); 10552 } 10553 return result; 10554 } 10555 } 10556 10557 @Override 10558 public String getDefaultBrowserPackageName(int userId) { 10559 synchronized (mPackages) { 10560 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10561 } 10562 } 10563 10564 /** 10565 * Get the "allow unknown sources" setting. 10566 * 10567 * @return the current "allow unknown sources" setting 10568 */ 10569 private int getUnknownSourcesSettings() { 10570 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10571 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10572 -1); 10573 } 10574 10575 @Override 10576 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10577 final int uid = Binder.getCallingUid(); 10578 // writer 10579 synchronized (mPackages) { 10580 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10581 if (targetPackageSetting == null) { 10582 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10583 } 10584 10585 PackageSetting installerPackageSetting; 10586 if (installerPackageName != null) { 10587 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10588 if (installerPackageSetting == null) { 10589 throw new IllegalArgumentException("Unknown installer package: " 10590 + installerPackageName); 10591 } 10592 } else { 10593 installerPackageSetting = null; 10594 } 10595 10596 Signature[] callerSignature; 10597 Object obj = mSettings.getUserIdLPr(uid); 10598 if (obj != null) { 10599 if (obj instanceof SharedUserSetting) { 10600 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10601 } else if (obj instanceof PackageSetting) { 10602 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10603 } else { 10604 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10605 } 10606 } else { 10607 throw new SecurityException("Unknown calling UID: " + uid); 10608 } 10609 10610 // Verify: can't set installerPackageName to a package that is 10611 // not signed with the same cert as the caller. 10612 if (installerPackageSetting != null) { 10613 if (compareSignatures(callerSignature, 10614 installerPackageSetting.signatures.mSignatures) 10615 != PackageManager.SIGNATURE_MATCH) { 10616 throw new SecurityException( 10617 "Caller does not have same cert as new installer package " 10618 + installerPackageName); 10619 } 10620 } 10621 10622 // Verify: if target already has an installer package, it must 10623 // be signed with the same cert as the caller. 10624 if (targetPackageSetting.installerPackageName != null) { 10625 PackageSetting setting = mSettings.mPackages.get( 10626 targetPackageSetting.installerPackageName); 10627 // If the currently set package isn't valid, then it's always 10628 // okay to change it. 10629 if (setting != null) { 10630 if (compareSignatures(callerSignature, 10631 setting.signatures.mSignatures) 10632 != PackageManager.SIGNATURE_MATCH) { 10633 throw new SecurityException( 10634 "Caller does not have same cert as old installer package " 10635 + targetPackageSetting.installerPackageName); 10636 } 10637 } 10638 } 10639 10640 // Okay! 10641 targetPackageSetting.installerPackageName = installerPackageName; 10642 scheduleWriteSettingsLocked(); 10643 } 10644 } 10645 10646 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10647 // Queue up an async operation since the package installation may take a little while. 10648 mHandler.post(new Runnable() { 10649 public void run() { 10650 mHandler.removeCallbacks(this); 10651 // Result object to be returned 10652 PackageInstalledInfo res = new PackageInstalledInfo(); 10653 res.returnCode = currentStatus; 10654 res.uid = -1; 10655 res.pkg = null; 10656 res.removedInfo = new PackageRemovedInfo(); 10657 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10658 args.doPreInstall(res.returnCode); 10659 synchronized (mInstallLock) { 10660 installPackageTracedLI(args, res); 10661 } 10662 args.doPostInstall(res.returnCode, res.uid); 10663 } 10664 10665 // A restore should be performed at this point if (a) the install 10666 // succeeded, (b) the operation is not an update, and (c) the new 10667 // package has not opted out of backup participation. 10668 final boolean update = res.removedInfo.removedPackage != null; 10669 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10670 boolean doRestore = !update 10671 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10672 10673 // Set up the post-install work request bookkeeping. This will be used 10674 // and cleaned up by the post-install event handling regardless of whether 10675 // there's a restore pass performed. Token values are >= 1. 10676 int token; 10677 if (mNextInstallToken < 0) mNextInstallToken = 1; 10678 token = mNextInstallToken++; 10679 10680 PostInstallData data = new PostInstallData(args, res); 10681 mRunningInstalls.put(token, data); 10682 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10683 10684 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10685 // Pass responsibility to the Backup Manager. It will perform a 10686 // restore if appropriate, then pass responsibility back to the 10687 // Package Manager to run the post-install observer callbacks 10688 // and broadcasts. 10689 IBackupManager bm = IBackupManager.Stub.asInterface( 10690 ServiceManager.getService(Context.BACKUP_SERVICE)); 10691 if (bm != null) { 10692 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10693 + " to BM for possible restore"); 10694 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10695 try { 10696 // TODO: http://b/22388012 10697 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 10698 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10699 } else { 10700 doRestore = false; 10701 } 10702 } catch (RemoteException e) { 10703 // can't happen; the backup manager is local 10704 } catch (Exception e) { 10705 Slog.e(TAG, "Exception trying to enqueue restore", e); 10706 doRestore = false; 10707 } 10708 } else { 10709 Slog.e(TAG, "Backup Manager not found!"); 10710 doRestore = false; 10711 } 10712 } 10713 10714 if (!doRestore) { 10715 // No restore possible, or the Backup Manager was mysteriously not 10716 // available -- just fire the post-install work request directly. 10717 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10718 10719 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 10720 10721 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10722 mHandler.sendMessage(msg); 10723 } 10724 } 10725 }); 10726 } 10727 10728 private abstract class HandlerParams { 10729 private static final int MAX_RETRIES = 4; 10730 10731 /** 10732 * Number of times startCopy() has been attempted and had a non-fatal 10733 * error. 10734 */ 10735 private int mRetries = 0; 10736 10737 /** User handle for the user requesting the information or installation. */ 10738 private final UserHandle mUser; 10739 String traceMethod; 10740 int traceCookie; 10741 10742 HandlerParams(UserHandle user) { 10743 mUser = user; 10744 } 10745 10746 UserHandle getUser() { 10747 return mUser; 10748 } 10749 10750 HandlerParams setTraceMethod(String traceMethod) { 10751 this.traceMethod = traceMethod; 10752 return this; 10753 } 10754 10755 HandlerParams setTraceCookie(int traceCookie) { 10756 this.traceCookie = traceCookie; 10757 return this; 10758 } 10759 10760 final boolean startCopy() { 10761 boolean res; 10762 try { 10763 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10764 10765 if (++mRetries > MAX_RETRIES) { 10766 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10767 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10768 handleServiceError(); 10769 return false; 10770 } else { 10771 handleStartCopy(); 10772 res = true; 10773 } 10774 } catch (RemoteException e) { 10775 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10776 mHandler.sendEmptyMessage(MCS_RECONNECT); 10777 res = false; 10778 } 10779 handleReturnCode(); 10780 return res; 10781 } 10782 10783 final void serviceError() { 10784 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10785 handleServiceError(); 10786 handleReturnCode(); 10787 } 10788 10789 abstract void handleStartCopy() throws RemoteException; 10790 abstract void handleServiceError(); 10791 abstract void handleReturnCode(); 10792 } 10793 10794 class MeasureParams extends HandlerParams { 10795 private final PackageStats mStats; 10796 private boolean mSuccess; 10797 10798 private final IPackageStatsObserver mObserver; 10799 10800 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10801 super(new UserHandle(stats.userHandle)); 10802 mObserver = observer; 10803 mStats = stats; 10804 } 10805 10806 @Override 10807 public String toString() { 10808 return "MeasureParams{" 10809 + Integer.toHexString(System.identityHashCode(this)) 10810 + " " + mStats.packageName + "}"; 10811 } 10812 10813 @Override 10814 void handleStartCopy() throws RemoteException { 10815 synchronized (mInstallLock) { 10816 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10817 } 10818 10819 if (mSuccess) { 10820 final boolean mounted; 10821 if (Environment.isExternalStorageEmulated()) { 10822 mounted = true; 10823 } else { 10824 final String status = Environment.getExternalStorageState(); 10825 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10826 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10827 } 10828 10829 if (mounted) { 10830 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10831 10832 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10833 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10834 10835 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10836 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10837 10838 // Always subtract cache size, since it's a subdirectory 10839 mStats.externalDataSize -= mStats.externalCacheSize; 10840 10841 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10842 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10843 10844 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10845 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10846 } 10847 } 10848 } 10849 10850 @Override 10851 void handleReturnCode() { 10852 if (mObserver != null) { 10853 try { 10854 mObserver.onGetStatsCompleted(mStats, mSuccess); 10855 } catch (RemoteException e) { 10856 Slog.i(TAG, "Observer no longer exists."); 10857 } 10858 } 10859 } 10860 10861 @Override 10862 void handleServiceError() { 10863 Slog.e(TAG, "Could not measure application " + mStats.packageName 10864 + " external storage"); 10865 } 10866 } 10867 10868 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10869 throws RemoteException { 10870 long result = 0; 10871 for (File path : paths) { 10872 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10873 } 10874 return result; 10875 } 10876 10877 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10878 for (File path : paths) { 10879 try { 10880 mcs.clearDirectory(path.getAbsolutePath()); 10881 } catch (RemoteException e) { 10882 } 10883 } 10884 } 10885 10886 static class OriginInfo { 10887 /** 10888 * Location where install is coming from, before it has been 10889 * copied/renamed into place. This could be a single monolithic APK 10890 * file, or a cluster directory. This location may be untrusted. 10891 */ 10892 final File file; 10893 final String cid; 10894 10895 /** 10896 * Flag indicating that {@link #file} or {@link #cid} has already been 10897 * staged, meaning downstream users don't need to defensively copy the 10898 * contents. 10899 */ 10900 final boolean staged; 10901 10902 /** 10903 * Flag indicating that {@link #file} or {@link #cid} is an already 10904 * installed app that is being moved. 10905 */ 10906 final boolean existing; 10907 10908 final String resolvedPath; 10909 final File resolvedFile; 10910 10911 static OriginInfo fromNothing() { 10912 return new OriginInfo(null, null, false, false); 10913 } 10914 10915 static OriginInfo fromUntrustedFile(File file) { 10916 return new OriginInfo(file, null, false, false); 10917 } 10918 10919 static OriginInfo fromExistingFile(File file) { 10920 return new OriginInfo(file, null, false, true); 10921 } 10922 10923 static OriginInfo fromStagedFile(File file) { 10924 return new OriginInfo(file, null, true, false); 10925 } 10926 10927 static OriginInfo fromStagedContainer(String cid) { 10928 return new OriginInfo(null, cid, true, false); 10929 } 10930 10931 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10932 this.file = file; 10933 this.cid = cid; 10934 this.staged = staged; 10935 this.existing = existing; 10936 10937 if (cid != null) { 10938 resolvedPath = PackageHelper.getSdDir(cid); 10939 resolvedFile = new File(resolvedPath); 10940 } else if (file != null) { 10941 resolvedPath = file.getAbsolutePath(); 10942 resolvedFile = file; 10943 } else { 10944 resolvedPath = null; 10945 resolvedFile = null; 10946 } 10947 } 10948 } 10949 10950 static class MoveInfo { 10951 final int moveId; 10952 final String fromUuid; 10953 final String toUuid; 10954 final String packageName; 10955 final String dataAppName; 10956 final int appId; 10957 final String seinfo; 10958 final int targetSdkVersion; 10959 10960 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10961 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 10962 this.moveId = moveId; 10963 this.fromUuid = fromUuid; 10964 this.toUuid = toUuid; 10965 this.packageName = packageName; 10966 this.dataAppName = dataAppName; 10967 this.appId = appId; 10968 this.seinfo = seinfo; 10969 this.targetSdkVersion = targetSdkVersion; 10970 } 10971 } 10972 10973 class InstallParams extends HandlerParams { 10974 final OriginInfo origin; 10975 final MoveInfo move; 10976 final IPackageInstallObserver2 observer; 10977 int installFlags; 10978 final String installerPackageName; 10979 final String volumeUuid; 10980 final VerificationParams verificationParams; 10981 private InstallArgs mArgs; 10982 private int mRet; 10983 final String packageAbiOverride; 10984 final String[] grantedRuntimePermissions; 10985 10986 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10987 int installFlags, String installerPackageName, String volumeUuid, 10988 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10989 String[] grantedPermissions) { 10990 super(user); 10991 this.origin = origin; 10992 this.move = move; 10993 this.observer = observer; 10994 this.installFlags = installFlags; 10995 this.installerPackageName = installerPackageName; 10996 this.volumeUuid = volumeUuid; 10997 this.verificationParams = verificationParams; 10998 this.packageAbiOverride = packageAbiOverride; 10999 this.grantedRuntimePermissions = grantedPermissions; 11000 } 11001 11002 @Override 11003 public String toString() { 11004 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 11005 + " file=" + origin.file + " cid=" + origin.cid + "}"; 11006 } 11007 11008 private int installLocationPolicy(PackageInfoLite pkgLite) { 11009 String packageName = pkgLite.packageName; 11010 int installLocation = pkgLite.installLocation; 11011 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11012 // reader 11013 synchronized (mPackages) { 11014 PackageParser.Package pkg = mPackages.get(packageName); 11015 if (pkg != null) { 11016 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11017 // Check for downgrading. 11018 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 11019 try { 11020 checkDowngrade(pkg, pkgLite); 11021 } catch (PackageManagerException e) { 11022 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 11023 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 11024 } 11025 } 11026 // Check for updated system application. 11027 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11028 if (onSd) { 11029 Slog.w(TAG, "Cannot install update to system app on sdcard"); 11030 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 11031 } 11032 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11033 } else { 11034 if (onSd) { 11035 // Install flag overrides everything. 11036 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11037 } 11038 // If current upgrade specifies particular preference 11039 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 11040 // Application explicitly specified internal. 11041 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11042 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 11043 // App explictly prefers external. Let policy decide 11044 } else { 11045 // Prefer previous location 11046 if (isExternal(pkg)) { 11047 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11048 } 11049 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11050 } 11051 } 11052 } else { 11053 // Invalid install. Return error code 11054 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 11055 } 11056 } 11057 } 11058 // All the special cases have been taken care of. 11059 // Return result based on recommended install location. 11060 if (onSd) { 11061 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11062 } 11063 return pkgLite.recommendedInstallLocation; 11064 } 11065 11066 /* 11067 * Invoke remote method to get package information and install 11068 * location values. Override install location based on default 11069 * policy if needed and then create install arguments based 11070 * on the install location. 11071 */ 11072 public void handleStartCopy() throws RemoteException { 11073 int ret = PackageManager.INSTALL_SUCCEEDED; 11074 11075 // If we're already staged, we've firmly committed to an install location 11076 if (origin.staged) { 11077 if (origin.file != null) { 11078 installFlags |= PackageManager.INSTALL_INTERNAL; 11079 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11080 } else if (origin.cid != null) { 11081 installFlags |= PackageManager.INSTALL_EXTERNAL; 11082 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11083 } else { 11084 throw new IllegalStateException("Invalid stage location"); 11085 } 11086 } 11087 11088 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11089 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 11090 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11091 PackageInfoLite pkgLite = null; 11092 11093 if (onInt && onSd) { 11094 // Check if both bits are set. 11095 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 11096 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11097 } else if (onSd && ephemeral) { 11098 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 11099 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11100 } else { 11101 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 11102 packageAbiOverride); 11103 11104 if (DEBUG_EPHEMERAL && ephemeral) { 11105 Slog.v(TAG, "pkgLite for install: " + pkgLite); 11106 } 11107 11108 /* 11109 * If we have too little free space, try to free cache 11110 * before giving up. 11111 */ 11112 if (!origin.staged && pkgLite.recommendedInstallLocation 11113 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11114 // TODO: focus freeing disk space on the target device 11115 final StorageManager storage = StorageManager.from(mContext); 11116 final long lowThreshold = storage.getStorageLowBytes( 11117 Environment.getDataDirectory()); 11118 11119 final long sizeBytes = mContainerService.calculateInstalledSize( 11120 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 11121 11122 try { 11123 mInstaller.freeCache(null, sizeBytes + lowThreshold); 11124 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 11125 installFlags, packageAbiOverride); 11126 } catch (InstallerException e) { 11127 Slog.w(TAG, "Failed to free cache", e); 11128 } 11129 11130 /* 11131 * The cache free must have deleted the file we 11132 * downloaded to install. 11133 * 11134 * TODO: fix the "freeCache" call to not delete 11135 * the file we care about. 11136 */ 11137 if (pkgLite.recommendedInstallLocation 11138 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11139 pkgLite.recommendedInstallLocation 11140 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 11141 } 11142 } 11143 } 11144 11145 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11146 int loc = pkgLite.recommendedInstallLocation; 11147 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 11148 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11149 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 11150 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 11151 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11152 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11153 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 11154 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 11155 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11156 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 11157 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 11158 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 11159 } else { 11160 // Override with defaults if needed. 11161 loc = installLocationPolicy(pkgLite); 11162 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 11163 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 11164 } else if (!onSd && !onInt) { 11165 // Override install location with flags 11166 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 11167 // Set the flag to install on external media. 11168 installFlags |= PackageManager.INSTALL_EXTERNAL; 11169 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11170 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 11171 if (DEBUG_EPHEMERAL) { 11172 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 11173 } 11174 installFlags |= PackageManager.INSTALL_EPHEMERAL; 11175 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 11176 |PackageManager.INSTALL_INTERNAL); 11177 } else { 11178 // Make sure the flag for installing on external 11179 // media is unset 11180 installFlags |= PackageManager.INSTALL_INTERNAL; 11181 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11182 } 11183 } 11184 } 11185 } 11186 11187 final InstallArgs args = createInstallArgs(this); 11188 mArgs = args; 11189 11190 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11191 // TODO: http://b/22976637 11192 // Apps installed for "all" users use the device owner to verify the app 11193 UserHandle verifierUser = getUser(); 11194 if (verifierUser == UserHandle.ALL) { 11195 verifierUser = UserHandle.SYSTEM; 11196 } 11197 11198 /* 11199 * Determine if we have any installed package verifiers. If we 11200 * do, then we'll defer to them to verify the packages. 11201 */ 11202 final int requiredUid = mRequiredVerifierPackage == null ? -1 11203 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 11204 verifierUser.getIdentifier()); 11205 if (!origin.existing && requiredUid != -1 11206 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 11207 final Intent verification = new Intent( 11208 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 11209 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 11210 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 11211 PACKAGE_MIME_TYPE); 11212 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11213 11214 // Query all live verifiers based on current user state 11215 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 11216 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 11217 11218 if (DEBUG_VERIFY) { 11219 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 11220 + verification.toString() + " with " + pkgLite.verifiers.length 11221 + " optional verifiers"); 11222 } 11223 11224 final int verificationId = mPendingVerificationToken++; 11225 11226 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11227 11228 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 11229 installerPackageName); 11230 11231 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 11232 installFlags); 11233 11234 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 11235 pkgLite.packageName); 11236 11237 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 11238 pkgLite.versionCode); 11239 11240 if (verificationParams != null) { 11241 if (verificationParams.getVerificationURI() != null) { 11242 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 11243 verificationParams.getVerificationURI()); 11244 } 11245 if (verificationParams.getOriginatingURI() != null) { 11246 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 11247 verificationParams.getOriginatingURI()); 11248 } 11249 if (verificationParams.getReferrer() != null) { 11250 verification.putExtra(Intent.EXTRA_REFERRER, 11251 verificationParams.getReferrer()); 11252 } 11253 if (verificationParams.getOriginatingUid() >= 0) { 11254 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 11255 verificationParams.getOriginatingUid()); 11256 } 11257 if (verificationParams.getInstallerUid() >= 0) { 11258 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 11259 verificationParams.getInstallerUid()); 11260 } 11261 } 11262 11263 final PackageVerificationState verificationState = new PackageVerificationState( 11264 requiredUid, args); 11265 11266 mPendingVerification.append(verificationId, verificationState); 11267 11268 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 11269 receivers, verificationState); 11270 11271 /* 11272 * If any sufficient verifiers were listed in the package 11273 * manifest, attempt to ask them. 11274 */ 11275 if (sufficientVerifiers != null) { 11276 final int N = sufficientVerifiers.size(); 11277 if (N == 0) { 11278 Slog.i(TAG, "Additional verifiers required, but none installed."); 11279 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 11280 } else { 11281 for (int i = 0; i < N; i++) { 11282 final ComponentName verifierComponent = sufficientVerifiers.get(i); 11283 11284 final Intent sufficientIntent = new Intent(verification); 11285 sufficientIntent.setComponent(verifierComponent); 11286 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 11287 } 11288 } 11289 } 11290 11291 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 11292 mRequiredVerifierPackage, receivers); 11293 if (ret == PackageManager.INSTALL_SUCCEEDED 11294 && mRequiredVerifierPackage != null) { 11295 Trace.asyncTraceBegin( 11296 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 11297 /* 11298 * Send the intent to the required verification agent, 11299 * but only start the verification timeout after the 11300 * target BroadcastReceivers have run. 11301 */ 11302 verification.setComponent(requiredVerifierComponent); 11303 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 11304 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11305 new BroadcastReceiver() { 11306 @Override 11307 public void onReceive(Context context, Intent intent) { 11308 final Message msg = mHandler 11309 .obtainMessage(CHECK_PENDING_VERIFICATION); 11310 msg.arg1 = verificationId; 11311 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 11312 } 11313 }, null, 0, null, null); 11314 11315 /* 11316 * We don't want the copy to proceed until verification 11317 * succeeds, so null out this field. 11318 */ 11319 mArgs = null; 11320 } 11321 } else { 11322 /* 11323 * No package verification is enabled, so immediately start 11324 * the remote call to initiate copy using temporary file. 11325 */ 11326 ret = args.copyApk(mContainerService, true); 11327 } 11328 } 11329 11330 mRet = ret; 11331 } 11332 11333 @Override 11334 void handleReturnCode() { 11335 // If mArgs is null, then MCS couldn't be reached. When it 11336 // reconnects, it will try again to install. At that point, this 11337 // will succeed. 11338 if (mArgs != null) { 11339 processPendingInstall(mArgs, mRet); 11340 } 11341 } 11342 11343 @Override 11344 void handleServiceError() { 11345 mArgs = createInstallArgs(this); 11346 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11347 } 11348 11349 public boolean isForwardLocked() { 11350 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11351 } 11352 } 11353 11354 /** 11355 * Used during creation of InstallArgs 11356 * 11357 * @param installFlags package installation flags 11358 * @return true if should be installed on external storage 11359 */ 11360 private static boolean installOnExternalAsec(int installFlags) { 11361 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 11362 return false; 11363 } 11364 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 11365 return true; 11366 } 11367 return false; 11368 } 11369 11370 /** 11371 * Used during creation of InstallArgs 11372 * 11373 * @param installFlags package installation flags 11374 * @return true if should be installed as forward locked 11375 */ 11376 private static boolean installForwardLocked(int installFlags) { 11377 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11378 } 11379 11380 private InstallArgs createInstallArgs(InstallParams params) { 11381 if (params.move != null) { 11382 return new MoveInstallArgs(params); 11383 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 11384 return new AsecInstallArgs(params); 11385 } else { 11386 return new FileInstallArgs(params); 11387 } 11388 } 11389 11390 /** 11391 * Create args that describe an existing installed package. Typically used 11392 * when cleaning up old installs, or used as a move source. 11393 */ 11394 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 11395 String resourcePath, String[] instructionSets) { 11396 final boolean isInAsec; 11397 if (installOnExternalAsec(installFlags)) { 11398 /* Apps on SD card are always in ASEC containers. */ 11399 isInAsec = true; 11400 } else if (installForwardLocked(installFlags) 11401 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 11402 /* 11403 * Forward-locked apps are only in ASEC containers if they're the 11404 * new style 11405 */ 11406 isInAsec = true; 11407 } else { 11408 isInAsec = false; 11409 } 11410 11411 if (isInAsec) { 11412 return new AsecInstallArgs(codePath, instructionSets, 11413 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 11414 } else { 11415 return new FileInstallArgs(codePath, resourcePath, instructionSets); 11416 } 11417 } 11418 11419 static abstract class InstallArgs { 11420 /** @see InstallParams#origin */ 11421 final OriginInfo origin; 11422 /** @see InstallParams#move */ 11423 final MoveInfo move; 11424 11425 final IPackageInstallObserver2 observer; 11426 // Always refers to PackageManager flags only 11427 final int installFlags; 11428 final String installerPackageName; 11429 final String volumeUuid; 11430 final UserHandle user; 11431 final String abiOverride; 11432 final String[] installGrantPermissions; 11433 /** If non-null, drop an async trace when the install completes */ 11434 final String traceMethod; 11435 final int traceCookie; 11436 11437 // The list of instruction sets supported by this app. This is currently 11438 // only used during the rmdex() phase to clean up resources. We can get rid of this 11439 // if we move dex files under the common app path. 11440 /* nullable */ String[] instructionSets; 11441 11442 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11443 int installFlags, String installerPackageName, String volumeUuid, 11444 UserHandle user, String[] instructionSets, 11445 String abiOverride, String[] installGrantPermissions, 11446 String traceMethod, int traceCookie) { 11447 this.origin = origin; 11448 this.move = move; 11449 this.installFlags = installFlags; 11450 this.observer = observer; 11451 this.installerPackageName = installerPackageName; 11452 this.volumeUuid = volumeUuid; 11453 this.user = user; 11454 this.instructionSets = instructionSets; 11455 this.abiOverride = abiOverride; 11456 this.installGrantPermissions = installGrantPermissions; 11457 this.traceMethod = traceMethod; 11458 this.traceCookie = traceCookie; 11459 } 11460 11461 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 11462 abstract int doPreInstall(int status); 11463 11464 /** 11465 * Rename package into final resting place. All paths on the given 11466 * scanned package should be updated to reflect the rename. 11467 */ 11468 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 11469 abstract int doPostInstall(int status, int uid); 11470 11471 /** @see PackageSettingBase#codePathString */ 11472 abstract String getCodePath(); 11473 /** @see PackageSettingBase#resourcePathString */ 11474 abstract String getResourcePath(); 11475 11476 // Need installer lock especially for dex file removal. 11477 abstract void cleanUpResourcesLI(); 11478 abstract boolean doPostDeleteLI(boolean delete); 11479 11480 /** 11481 * Called before the source arguments are copied. This is used mostly 11482 * for MoveParams when it needs to read the source file to put it in the 11483 * destination. 11484 */ 11485 int doPreCopy() { 11486 return PackageManager.INSTALL_SUCCEEDED; 11487 } 11488 11489 /** 11490 * Called after the source arguments are copied. This is used mostly for 11491 * MoveParams when it needs to read the source file to put it in the 11492 * destination. 11493 * 11494 * @return 11495 */ 11496 int doPostCopy(int uid) { 11497 return PackageManager.INSTALL_SUCCEEDED; 11498 } 11499 11500 protected boolean isFwdLocked() { 11501 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11502 } 11503 11504 protected boolean isExternalAsec() { 11505 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11506 } 11507 11508 protected boolean isEphemeral() { 11509 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11510 } 11511 11512 UserHandle getUser() { 11513 return user; 11514 } 11515 } 11516 11517 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 11518 if (!allCodePaths.isEmpty()) { 11519 if (instructionSets == null) { 11520 throw new IllegalStateException("instructionSet == null"); 11521 } 11522 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11523 for (String codePath : allCodePaths) { 11524 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11525 try { 11526 mInstaller.rmdex(codePath, dexCodeInstructionSet); 11527 } catch (InstallerException ignored) { 11528 } 11529 } 11530 } 11531 } 11532 } 11533 11534 /** 11535 * Logic to handle installation of non-ASEC applications, including copying 11536 * and renaming logic. 11537 */ 11538 class FileInstallArgs extends InstallArgs { 11539 private File codeFile; 11540 private File resourceFile; 11541 11542 // Example topology: 11543 // /data/app/com.example/base.apk 11544 // /data/app/com.example/split_foo.apk 11545 // /data/app/com.example/lib/arm/libfoo.so 11546 // /data/app/com.example/lib/arm64/libfoo.so 11547 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11548 11549 /** New install */ 11550 FileInstallArgs(InstallParams params) { 11551 super(params.origin, params.move, params.observer, params.installFlags, 11552 params.installerPackageName, params.volumeUuid, 11553 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11554 params.grantedRuntimePermissions, 11555 params.traceMethod, params.traceCookie); 11556 if (isFwdLocked()) { 11557 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11558 } 11559 } 11560 11561 /** Existing install */ 11562 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11563 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 11564 null, null, null, 0); 11565 this.codeFile = (codePath != null) ? new File(codePath) : null; 11566 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11567 } 11568 11569 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11570 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 11571 try { 11572 return doCopyApk(imcs, temp); 11573 } finally { 11574 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11575 } 11576 } 11577 11578 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11579 if (origin.staged) { 11580 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11581 codeFile = origin.file; 11582 resourceFile = origin.file; 11583 return PackageManager.INSTALL_SUCCEEDED; 11584 } 11585 11586 try { 11587 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11588 final File tempDir = 11589 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 11590 codeFile = tempDir; 11591 resourceFile = tempDir; 11592 } catch (IOException e) { 11593 Slog.w(TAG, "Failed to create copy file: " + e); 11594 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11595 } 11596 11597 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11598 @Override 11599 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11600 if (!FileUtils.isValidExtFilename(name)) { 11601 throw new IllegalArgumentException("Invalid filename: " + name); 11602 } 11603 try { 11604 final File file = new File(codeFile, name); 11605 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11606 O_RDWR | O_CREAT, 0644); 11607 Os.chmod(file.getAbsolutePath(), 0644); 11608 return new ParcelFileDescriptor(fd); 11609 } catch (ErrnoException e) { 11610 throw new RemoteException("Failed to open: " + e.getMessage()); 11611 } 11612 } 11613 }; 11614 11615 int ret = PackageManager.INSTALL_SUCCEEDED; 11616 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11617 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11618 Slog.e(TAG, "Failed to copy package"); 11619 return ret; 11620 } 11621 11622 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11623 NativeLibraryHelper.Handle handle = null; 11624 try { 11625 handle = NativeLibraryHelper.Handle.create(codeFile); 11626 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11627 abiOverride); 11628 } catch (IOException e) { 11629 Slog.e(TAG, "Copying native libraries failed", e); 11630 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11631 } finally { 11632 IoUtils.closeQuietly(handle); 11633 } 11634 11635 return ret; 11636 } 11637 11638 int doPreInstall(int status) { 11639 if (status != PackageManager.INSTALL_SUCCEEDED) { 11640 cleanUp(); 11641 } 11642 return status; 11643 } 11644 11645 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11646 if (status != PackageManager.INSTALL_SUCCEEDED) { 11647 cleanUp(); 11648 return false; 11649 } 11650 11651 final File targetDir = codeFile.getParentFile(); 11652 final File beforeCodeFile = codeFile; 11653 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11654 11655 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11656 try { 11657 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11658 } catch (ErrnoException e) { 11659 Slog.w(TAG, "Failed to rename", e); 11660 return false; 11661 } 11662 11663 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11664 Slog.w(TAG, "Failed to restorecon"); 11665 return false; 11666 } 11667 11668 // Reflect the rename internally 11669 codeFile = afterCodeFile; 11670 resourceFile = afterCodeFile; 11671 11672 // Reflect the rename in scanned details 11673 pkg.codePath = afterCodeFile.getAbsolutePath(); 11674 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11675 pkg.baseCodePath); 11676 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11677 pkg.splitCodePaths); 11678 11679 // Reflect the rename in app info 11680 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11681 pkg.applicationInfo.setCodePath(pkg.codePath); 11682 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11683 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11684 pkg.applicationInfo.setResourcePath(pkg.codePath); 11685 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11686 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11687 11688 return true; 11689 } 11690 11691 int doPostInstall(int status, int uid) { 11692 if (status != PackageManager.INSTALL_SUCCEEDED) { 11693 cleanUp(); 11694 } 11695 return status; 11696 } 11697 11698 @Override 11699 String getCodePath() { 11700 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11701 } 11702 11703 @Override 11704 String getResourcePath() { 11705 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11706 } 11707 11708 private boolean cleanUp() { 11709 if (codeFile == null || !codeFile.exists()) { 11710 return false; 11711 } 11712 11713 removeCodePathLI(codeFile); 11714 11715 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11716 resourceFile.delete(); 11717 } 11718 11719 return true; 11720 } 11721 11722 void cleanUpResourcesLI() { 11723 // Try enumerating all code paths before deleting 11724 List<String> allCodePaths = Collections.EMPTY_LIST; 11725 if (codeFile != null && codeFile.exists()) { 11726 try { 11727 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11728 allCodePaths = pkg.getAllCodePaths(); 11729 } catch (PackageParserException e) { 11730 // Ignored; we tried our best 11731 } 11732 } 11733 11734 cleanUp(); 11735 removeDexFiles(allCodePaths, instructionSets); 11736 } 11737 11738 boolean doPostDeleteLI(boolean delete) { 11739 // XXX err, shouldn't we respect the delete flag? 11740 cleanUpResourcesLI(); 11741 return true; 11742 } 11743 } 11744 11745 private boolean isAsecExternal(String cid) { 11746 final String asecPath = PackageHelper.getSdFilesystem(cid); 11747 return !asecPath.startsWith(mAsecInternalPath); 11748 } 11749 11750 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11751 PackageManagerException { 11752 if (copyRet < 0) { 11753 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11754 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11755 throw new PackageManagerException(copyRet, message); 11756 } 11757 } 11758 } 11759 11760 /** 11761 * Extract the MountService "container ID" from the full code path of an 11762 * .apk. 11763 */ 11764 static String cidFromCodePath(String fullCodePath) { 11765 int eidx = fullCodePath.lastIndexOf("/"); 11766 String subStr1 = fullCodePath.substring(0, eidx); 11767 int sidx = subStr1.lastIndexOf("/"); 11768 return subStr1.substring(sidx+1, eidx); 11769 } 11770 11771 /** 11772 * Logic to handle installation of ASEC applications, including copying and 11773 * renaming logic. 11774 */ 11775 class AsecInstallArgs extends InstallArgs { 11776 static final String RES_FILE_NAME = "pkg.apk"; 11777 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11778 11779 String cid; 11780 String packagePath; 11781 String resourcePath; 11782 11783 /** New install */ 11784 AsecInstallArgs(InstallParams params) { 11785 super(params.origin, params.move, params.observer, params.installFlags, 11786 params.installerPackageName, params.volumeUuid, 11787 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11788 params.grantedRuntimePermissions, 11789 params.traceMethod, params.traceCookie); 11790 } 11791 11792 /** Existing install */ 11793 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11794 boolean isExternal, boolean isForwardLocked) { 11795 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11796 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 11797 instructionSets, null, null, null, 0); 11798 // Hackily pretend we're still looking at a full code path 11799 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11800 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11801 } 11802 11803 // Extract cid from fullCodePath 11804 int eidx = fullCodePath.lastIndexOf("/"); 11805 String subStr1 = fullCodePath.substring(0, eidx); 11806 int sidx = subStr1.lastIndexOf("/"); 11807 cid = subStr1.substring(sidx+1, eidx); 11808 setMountPath(subStr1); 11809 } 11810 11811 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11812 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11813 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 11814 instructionSets, null, null, null, 0); 11815 this.cid = cid; 11816 setMountPath(PackageHelper.getSdDir(cid)); 11817 } 11818 11819 void createCopyFile() { 11820 cid = mInstallerService.allocateExternalStageCidLegacy(); 11821 } 11822 11823 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11824 if (origin.staged && origin.cid != null) { 11825 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11826 cid = origin.cid; 11827 setMountPath(PackageHelper.getSdDir(cid)); 11828 return PackageManager.INSTALL_SUCCEEDED; 11829 } 11830 11831 if (temp) { 11832 createCopyFile(); 11833 } else { 11834 /* 11835 * Pre-emptively destroy the container since it's destroyed if 11836 * copying fails due to it existing anyway. 11837 */ 11838 PackageHelper.destroySdDir(cid); 11839 } 11840 11841 final String newMountPath = imcs.copyPackageToContainer( 11842 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11843 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11844 11845 if (newMountPath != null) { 11846 setMountPath(newMountPath); 11847 return PackageManager.INSTALL_SUCCEEDED; 11848 } else { 11849 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11850 } 11851 } 11852 11853 @Override 11854 String getCodePath() { 11855 return packagePath; 11856 } 11857 11858 @Override 11859 String getResourcePath() { 11860 return resourcePath; 11861 } 11862 11863 int doPreInstall(int status) { 11864 if (status != PackageManager.INSTALL_SUCCEEDED) { 11865 // Destroy container 11866 PackageHelper.destroySdDir(cid); 11867 } else { 11868 boolean mounted = PackageHelper.isContainerMounted(cid); 11869 if (!mounted) { 11870 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11871 Process.SYSTEM_UID); 11872 if (newMountPath != null) { 11873 setMountPath(newMountPath); 11874 } else { 11875 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11876 } 11877 } 11878 } 11879 return status; 11880 } 11881 11882 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11883 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11884 String newMountPath = null; 11885 if (PackageHelper.isContainerMounted(cid)) { 11886 // Unmount the container 11887 if (!PackageHelper.unMountSdDir(cid)) { 11888 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11889 return false; 11890 } 11891 } 11892 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11893 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11894 " which might be stale. Will try to clean up."); 11895 // Clean up the stale container and proceed to recreate. 11896 if (!PackageHelper.destroySdDir(newCacheId)) { 11897 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11898 return false; 11899 } 11900 // Successfully cleaned up stale container. Try to rename again. 11901 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11902 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11903 + " inspite of cleaning it up."); 11904 return false; 11905 } 11906 } 11907 if (!PackageHelper.isContainerMounted(newCacheId)) { 11908 Slog.w(TAG, "Mounting container " + newCacheId); 11909 newMountPath = PackageHelper.mountSdDir(newCacheId, 11910 getEncryptKey(), Process.SYSTEM_UID); 11911 } else { 11912 newMountPath = PackageHelper.getSdDir(newCacheId); 11913 } 11914 if (newMountPath == null) { 11915 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11916 return false; 11917 } 11918 Log.i(TAG, "Succesfully renamed " + cid + 11919 " to " + newCacheId + 11920 " at new path: " + newMountPath); 11921 cid = newCacheId; 11922 11923 final File beforeCodeFile = new File(packagePath); 11924 setMountPath(newMountPath); 11925 final File afterCodeFile = new File(packagePath); 11926 11927 // Reflect the rename in scanned details 11928 pkg.codePath = afterCodeFile.getAbsolutePath(); 11929 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11930 pkg.baseCodePath); 11931 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11932 pkg.splitCodePaths); 11933 11934 // Reflect the rename in app info 11935 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11936 pkg.applicationInfo.setCodePath(pkg.codePath); 11937 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11938 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11939 pkg.applicationInfo.setResourcePath(pkg.codePath); 11940 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11941 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11942 11943 return true; 11944 } 11945 11946 private void setMountPath(String mountPath) { 11947 final File mountFile = new File(mountPath); 11948 11949 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11950 if (monolithicFile.exists()) { 11951 packagePath = monolithicFile.getAbsolutePath(); 11952 if (isFwdLocked()) { 11953 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11954 } else { 11955 resourcePath = packagePath; 11956 } 11957 } else { 11958 packagePath = mountFile.getAbsolutePath(); 11959 resourcePath = packagePath; 11960 } 11961 } 11962 11963 int doPostInstall(int status, int uid) { 11964 if (status != PackageManager.INSTALL_SUCCEEDED) { 11965 cleanUp(); 11966 } else { 11967 final int groupOwner; 11968 final String protectedFile; 11969 if (isFwdLocked()) { 11970 groupOwner = UserHandle.getSharedAppGid(uid); 11971 protectedFile = RES_FILE_NAME; 11972 } else { 11973 groupOwner = -1; 11974 protectedFile = null; 11975 } 11976 11977 if (uid < Process.FIRST_APPLICATION_UID 11978 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11979 Slog.e(TAG, "Failed to finalize " + cid); 11980 PackageHelper.destroySdDir(cid); 11981 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11982 } 11983 11984 boolean mounted = PackageHelper.isContainerMounted(cid); 11985 if (!mounted) { 11986 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11987 } 11988 } 11989 return status; 11990 } 11991 11992 private void cleanUp() { 11993 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11994 11995 // Destroy secure container 11996 PackageHelper.destroySdDir(cid); 11997 } 11998 11999 private List<String> getAllCodePaths() { 12000 final File codeFile = new File(getCodePath()); 12001 if (codeFile != null && codeFile.exists()) { 12002 try { 12003 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12004 return pkg.getAllCodePaths(); 12005 } catch (PackageParserException e) { 12006 // Ignored; we tried our best 12007 } 12008 } 12009 return Collections.EMPTY_LIST; 12010 } 12011 12012 void cleanUpResourcesLI() { 12013 // Enumerate all code paths before deleting 12014 cleanUpResourcesLI(getAllCodePaths()); 12015 } 12016 12017 private void cleanUpResourcesLI(List<String> allCodePaths) { 12018 cleanUp(); 12019 removeDexFiles(allCodePaths, instructionSets); 12020 } 12021 12022 String getPackageName() { 12023 return getAsecPackageName(cid); 12024 } 12025 12026 boolean doPostDeleteLI(boolean delete) { 12027 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 12028 final List<String> allCodePaths = getAllCodePaths(); 12029 boolean mounted = PackageHelper.isContainerMounted(cid); 12030 if (mounted) { 12031 // Unmount first 12032 if (PackageHelper.unMountSdDir(cid)) { 12033 mounted = false; 12034 } 12035 } 12036 if (!mounted && delete) { 12037 cleanUpResourcesLI(allCodePaths); 12038 } 12039 return !mounted; 12040 } 12041 12042 @Override 12043 int doPreCopy() { 12044 if (isFwdLocked()) { 12045 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 12046 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 12047 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12048 } 12049 } 12050 12051 return PackageManager.INSTALL_SUCCEEDED; 12052 } 12053 12054 @Override 12055 int doPostCopy(int uid) { 12056 if (isFwdLocked()) { 12057 if (uid < Process.FIRST_APPLICATION_UID 12058 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 12059 RES_FILE_NAME)) { 12060 Slog.e(TAG, "Failed to finalize " + cid); 12061 PackageHelper.destroySdDir(cid); 12062 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12063 } 12064 } 12065 12066 return PackageManager.INSTALL_SUCCEEDED; 12067 } 12068 } 12069 12070 /** 12071 * Logic to handle movement of existing installed applications. 12072 */ 12073 class MoveInstallArgs extends InstallArgs { 12074 private File codeFile; 12075 private File resourceFile; 12076 12077 /** New install */ 12078 MoveInstallArgs(InstallParams params) { 12079 super(params.origin, params.move, params.observer, params.installFlags, 12080 params.installerPackageName, params.volumeUuid, 12081 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12082 params.grantedRuntimePermissions, 12083 params.traceMethod, params.traceCookie); 12084 } 12085 12086 int copyApk(IMediaContainerService imcs, boolean temp) { 12087 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 12088 + move.fromUuid + " to " + move.toUuid); 12089 synchronized (mInstaller) { 12090 try { 12091 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 12092 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 12093 } catch (InstallerException e) { 12094 Slog.w(TAG, "Failed to move app", e); 12095 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12096 } 12097 } 12098 12099 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 12100 resourceFile = codeFile; 12101 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 12102 12103 return PackageManager.INSTALL_SUCCEEDED; 12104 } 12105 12106 int doPreInstall(int status) { 12107 if (status != PackageManager.INSTALL_SUCCEEDED) { 12108 cleanUp(move.toUuid); 12109 } 12110 return status; 12111 } 12112 12113 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12114 if (status != PackageManager.INSTALL_SUCCEEDED) { 12115 cleanUp(move.toUuid); 12116 return false; 12117 } 12118 12119 // Reflect the move in app info 12120 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 12121 pkg.applicationInfo.setCodePath(pkg.codePath); 12122 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 12123 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 12124 pkg.applicationInfo.setResourcePath(pkg.codePath); 12125 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 12126 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 12127 12128 return true; 12129 } 12130 12131 int doPostInstall(int status, int uid) { 12132 if (status == PackageManager.INSTALL_SUCCEEDED) { 12133 cleanUp(move.fromUuid); 12134 } else { 12135 cleanUp(move.toUuid); 12136 } 12137 return status; 12138 } 12139 12140 @Override 12141 String getCodePath() { 12142 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12143 } 12144 12145 @Override 12146 String getResourcePath() { 12147 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12148 } 12149 12150 private boolean cleanUp(String volumeUuid) { 12151 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 12152 move.dataAppName); 12153 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 12154 synchronized (mInstallLock) { 12155 // Clean up both app data and code 12156 removeDataDirsLI(volumeUuid, move.packageName); 12157 removeCodePathLI(codeFile); 12158 } 12159 return true; 12160 } 12161 12162 void cleanUpResourcesLI() { 12163 throw new UnsupportedOperationException(); 12164 } 12165 12166 boolean doPostDeleteLI(boolean delete) { 12167 throw new UnsupportedOperationException(); 12168 } 12169 } 12170 12171 static String getAsecPackageName(String packageCid) { 12172 int idx = packageCid.lastIndexOf("-"); 12173 if (idx == -1) { 12174 return packageCid; 12175 } 12176 return packageCid.substring(0, idx); 12177 } 12178 12179 // Utility method used to create code paths based on package name and available index. 12180 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 12181 String idxStr = ""; 12182 int idx = 1; 12183 // Fall back to default value of idx=1 if prefix is not 12184 // part of oldCodePath 12185 if (oldCodePath != null) { 12186 String subStr = oldCodePath; 12187 // Drop the suffix right away 12188 if (suffix != null && subStr.endsWith(suffix)) { 12189 subStr = subStr.substring(0, subStr.length() - suffix.length()); 12190 } 12191 // If oldCodePath already contains prefix find out the 12192 // ending index to either increment or decrement. 12193 int sidx = subStr.lastIndexOf(prefix); 12194 if (sidx != -1) { 12195 subStr = subStr.substring(sidx + prefix.length()); 12196 if (subStr != null) { 12197 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 12198 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 12199 } 12200 try { 12201 idx = Integer.parseInt(subStr); 12202 if (idx <= 1) { 12203 idx++; 12204 } else { 12205 idx--; 12206 } 12207 } catch(NumberFormatException e) { 12208 } 12209 } 12210 } 12211 } 12212 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 12213 return prefix + idxStr; 12214 } 12215 12216 private File getNextCodePath(File targetDir, String packageName) { 12217 int suffix = 1; 12218 File result; 12219 do { 12220 result = new File(targetDir, packageName + "-" + suffix); 12221 suffix++; 12222 } while (result.exists()); 12223 return result; 12224 } 12225 12226 // Utility method that returns the relative package path with respect 12227 // to the installation directory. Like say for /data/data/com.test-1.apk 12228 // string com.test-1 is returned. 12229 static String deriveCodePathName(String codePath) { 12230 if (codePath == null) { 12231 return null; 12232 } 12233 final File codeFile = new File(codePath); 12234 final String name = codeFile.getName(); 12235 if (codeFile.isDirectory()) { 12236 return name; 12237 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 12238 final int lastDot = name.lastIndexOf('.'); 12239 return name.substring(0, lastDot); 12240 } else { 12241 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 12242 return null; 12243 } 12244 } 12245 12246 static class PackageInstalledInfo { 12247 String name; 12248 int uid; 12249 // The set of users that originally had this package installed. 12250 int[] origUsers; 12251 // The set of users that now have this package installed. 12252 int[] newUsers; 12253 PackageParser.Package pkg; 12254 int returnCode; 12255 String returnMsg; 12256 PackageRemovedInfo removedInfo; 12257 12258 public void setError(int code, String msg) { 12259 returnCode = code; 12260 returnMsg = msg; 12261 Slog.w(TAG, msg); 12262 } 12263 12264 public void setError(String msg, PackageParserException e) { 12265 returnCode = e.error; 12266 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12267 Slog.w(TAG, msg, e); 12268 } 12269 12270 public void setError(String msg, PackageManagerException e) { 12271 returnCode = e.error; 12272 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12273 Slog.w(TAG, msg, e); 12274 } 12275 12276 // In some error cases we want to convey more info back to the observer 12277 String origPackage; 12278 String origPermission; 12279 } 12280 12281 /* 12282 * Install a non-existing package. 12283 */ 12284 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12285 UserHandle user, String installerPackageName, String volumeUuid, 12286 PackageInstalledInfo res) { 12287 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 12288 12289 // Remember this for later, in case we need to rollback this install 12290 String pkgName = pkg.packageName; 12291 12292 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 12293 // TODO: b/23350563 12294 final boolean dataDirExists = Environment 12295 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists(); 12296 12297 synchronized(mPackages) { 12298 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 12299 // A package with the same name is already installed, though 12300 // it has been renamed to an older name. The package we 12301 // are trying to install should be installed as an update to 12302 // the existing one, but that has not been requested, so bail. 12303 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12304 + " without first uninstalling package running as " 12305 + mSettings.mRenamedPackages.get(pkgName)); 12306 return; 12307 } 12308 if (mPackages.containsKey(pkgName)) { 12309 // Don't allow installation over an existing package with the same name. 12310 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12311 + " without first uninstalling."); 12312 return; 12313 } 12314 } 12315 12316 try { 12317 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 12318 System.currentTimeMillis(), user); 12319 12320 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 12321 prepareAppDataAfterInstall(newPackage); 12322 12323 // delete the partially installed application. the data directory will have to be 12324 // restored if it was already existing 12325 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12326 // remove package from internal structures. Note that we want deletePackageX to 12327 // delete the package data and cache directories that it created in 12328 // scanPackageLocked, unless those directories existed before we even tried to 12329 // install. 12330 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 12331 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 12332 res.removedInfo, true); 12333 } 12334 12335 } catch (PackageManagerException e) { 12336 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12337 } 12338 12339 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12340 } 12341 12342 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 12343 // Can't rotate keys during boot or if sharedUser. 12344 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 12345 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 12346 return false; 12347 } 12348 // app is using upgradeKeySets; make sure all are valid 12349 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12350 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 12351 for (int i = 0; i < upgradeKeySets.length; i++) { 12352 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 12353 Slog.wtf(TAG, "Package " 12354 + (oldPs.name != null ? oldPs.name : "<null>") 12355 + " contains upgrade-key-set reference to unknown key-set: " 12356 + upgradeKeySets[i] 12357 + " reverting to signatures check."); 12358 return false; 12359 } 12360 } 12361 return true; 12362 } 12363 12364 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 12365 // Upgrade keysets are being used. Determine if new package has a superset of the 12366 // required keys. 12367 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 12368 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12369 for (int i = 0; i < upgradeKeySets.length; i++) { 12370 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 12371 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 12372 return true; 12373 } 12374 } 12375 return false; 12376 } 12377 12378 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12379 UserHandle user, String installerPackageName, String volumeUuid, 12380 PackageInstalledInfo res) { 12381 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 12382 12383 final PackageParser.Package oldPackage; 12384 final String pkgName = pkg.packageName; 12385 final int[] allUsers; 12386 final boolean[] perUserInstalled; 12387 12388 // First find the old package info and check signatures 12389 synchronized(mPackages) { 12390 oldPackage = mPackages.get(pkgName); 12391 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 12392 if (isEphemeral && !oldIsEphemeral) { 12393 // can't downgrade from full to ephemeral 12394 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 12395 res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 12396 return; 12397 } 12398 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 12399 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12400 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12401 if(!checkUpgradeKeySetLP(ps, pkg)) { 12402 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12403 "New package not signed by keys specified by upgrade-keysets: " 12404 + pkgName); 12405 return; 12406 } 12407 } else { 12408 // default to original signature matching 12409 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 12410 != PackageManager.SIGNATURE_MATCH) { 12411 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12412 "New package has a different signature: " + pkgName); 12413 return; 12414 } 12415 } 12416 12417 // In case of rollback, remember per-user/profile install state 12418 allUsers = sUserManager.getUserIds(); 12419 perUserInstalled = new boolean[allUsers.length]; 12420 for (int i = 0; i < allUsers.length; i++) { 12421 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12422 } 12423 } 12424 12425 boolean sysPkg = (isSystemApp(oldPackage)); 12426 if (sysPkg) { 12427 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12428 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12429 } else { 12430 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12431 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12432 } 12433 } 12434 12435 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 12436 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12437 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12438 String volumeUuid, PackageInstalledInfo res) { 12439 String pkgName = deletedPackage.packageName; 12440 boolean deletedPkg = true; 12441 boolean updatedSettings = false; 12442 12443 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 12444 + deletedPackage); 12445 long origUpdateTime; 12446 if (pkg.mExtras != null) { 12447 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 12448 } else { 12449 origUpdateTime = 0; 12450 } 12451 12452 // First delete the existing package while retaining the data directory 12453 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 12454 res.removedInfo, true)) { 12455 // If the existing package wasn't successfully deleted 12456 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 12457 deletedPkg = false; 12458 } else { 12459 // Successfully deleted the old package; proceed with replace. 12460 12461 // If deleted package lived in a container, give users a chance to 12462 // relinquish resources before killing. 12463 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 12464 if (DEBUG_INSTALL) { 12465 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 12466 } 12467 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 12468 final ArrayList<String> pkgList = new ArrayList<String>(1); 12469 pkgList.add(deletedPackage.applicationInfo.packageName); 12470 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 12471 } 12472 12473 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 12474 try { 12475 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 12476 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 12477 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12478 perUserInstalled, res, user); 12479 prepareAppDataAfterInstall(newPackage); 12480 updatedSettings = true; 12481 } catch (PackageManagerException e) { 12482 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12483 } 12484 } 12485 12486 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12487 // remove package from internal structures. Note that we want deletePackageX to 12488 // delete the package data and cache directories that it created in 12489 // scanPackageLocked, unless those directories existed before we even tried to 12490 // install. 12491 if(updatedSettings) { 12492 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 12493 deletePackageLI( 12494 pkgName, null, true, allUsers, perUserInstalled, 12495 PackageManager.DELETE_KEEP_DATA, 12496 res.removedInfo, true); 12497 } 12498 // Since we failed to install the new package we need to restore the old 12499 // package that we deleted. 12500 if (deletedPkg) { 12501 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 12502 File restoreFile = new File(deletedPackage.codePath); 12503 // Parse old package 12504 boolean oldExternal = isExternal(deletedPackage); 12505 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 12506 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 12507 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12508 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 12509 try { 12510 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 12511 null); 12512 } catch (PackageManagerException e) { 12513 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 12514 + e.getMessage()); 12515 return; 12516 } 12517 // Restore of old package succeeded. Update permissions. 12518 // writer 12519 synchronized (mPackages) { 12520 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 12521 UPDATE_PERMISSIONS_ALL); 12522 // can downgrade to reader 12523 mSettings.writeLPr(); 12524 } 12525 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 12526 } 12527 } 12528 } 12529 12530 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 12531 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12532 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12533 String volumeUuid, PackageInstalledInfo res) { 12534 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 12535 + ", old=" + deletedPackage); 12536 boolean disabledSystem = false; 12537 boolean updatedSettings = false; 12538 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 12539 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 12540 != 0) { 12541 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12542 } 12543 String packageName = deletedPackage.packageName; 12544 if (packageName == null) { 12545 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12546 "Attempt to delete null packageName."); 12547 return; 12548 } 12549 PackageParser.Package oldPkg; 12550 PackageSetting oldPkgSetting; 12551 // reader 12552 synchronized (mPackages) { 12553 oldPkg = mPackages.get(packageName); 12554 oldPkgSetting = mSettings.mPackages.get(packageName); 12555 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 12556 (oldPkgSetting == null)) { 12557 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12558 "Couldn't find package " + packageName + " information"); 12559 return; 12560 } 12561 } 12562 12563 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12564 12565 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12566 res.removedInfo.removedPackage = packageName; 12567 // Remove existing system package 12568 removePackageLI(oldPkgSetting, true); 12569 // writer 12570 synchronized (mPackages) { 12571 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12572 if (!disabledSystem && deletedPackage != null) { 12573 // We didn't need to disable the .apk as a current system package, 12574 // which means we are replacing another update that is already 12575 // installed. We need to make sure to delete the older one's .apk. 12576 res.removedInfo.args = createInstallArgsForExisting(0, 12577 deletedPackage.applicationInfo.getCodePath(), 12578 deletedPackage.applicationInfo.getResourcePath(), 12579 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12580 } else { 12581 res.removedInfo.args = null; 12582 } 12583 } 12584 12585 // Successfully disabled the old package. Now proceed with re-installation 12586 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12587 12588 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12589 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12590 12591 PackageParser.Package newPackage = null; 12592 try { 12593 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 12594 if (newPackage.mExtras != null) { 12595 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12596 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12597 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12598 12599 // is the update attempting to change shared user? that isn't going to work... 12600 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12601 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12602 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12603 + " to " + newPkgSetting.sharedUser); 12604 updatedSettings = true; 12605 } 12606 } 12607 12608 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12609 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12610 perUserInstalled, res, user); 12611 prepareAppDataAfterInstall(newPackage); 12612 updatedSettings = true; 12613 } 12614 12615 } catch (PackageManagerException e) { 12616 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12617 } 12618 12619 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12620 // Re installation failed. Restore old information 12621 // Remove new pkg information 12622 if (newPackage != null) { 12623 removeInstalledPackageLI(newPackage, true); 12624 } 12625 // Add back the old system package 12626 try { 12627 scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12628 } catch (PackageManagerException e) { 12629 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12630 } 12631 // Restore the old system information in Settings 12632 synchronized (mPackages) { 12633 if (disabledSystem) { 12634 mSettings.enableSystemPackageLPw(packageName); 12635 } 12636 if (updatedSettings) { 12637 mSettings.setInstallerPackageName(packageName, 12638 oldPkgSetting.installerPackageName); 12639 } 12640 mSettings.writeLPr(); 12641 } 12642 } 12643 } 12644 12645 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 12646 // Collect all used permissions in the UID 12647 ArraySet<String> usedPermissions = new ArraySet<>(); 12648 final int packageCount = su.packages.size(); 12649 for (int i = 0; i < packageCount; i++) { 12650 PackageSetting ps = su.packages.valueAt(i); 12651 if (ps.pkg == null) { 12652 continue; 12653 } 12654 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 12655 for (int j = 0; j < requestedPermCount; j++) { 12656 String permission = ps.pkg.requestedPermissions.get(j); 12657 BasePermission bp = mSettings.mPermissions.get(permission); 12658 if (bp != null) { 12659 usedPermissions.add(permission); 12660 } 12661 } 12662 } 12663 12664 PermissionsState permissionsState = su.getPermissionsState(); 12665 // Prune install permissions 12666 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 12667 final int installPermCount = installPermStates.size(); 12668 for (int i = installPermCount - 1; i >= 0; i--) { 12669 PermissionState permissionState = installPermStates.get(i); 12670 if (!usedPermissions.contains(permissionState.getName())) { 12671 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12672 if (bp != null) { 12673 permissionsState.revokeInstallPermission(bp); 12674 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 12675 PackageManager.MASK_PERMISSION_FLAGS, 0); 12676 } 12677 } 12678 } 12679 12680 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 12681 12682 // Prune runtime permissions 12683 for (int userId : allUserIds) { 12684 List<PermissionState> runtimePermStates = permissionsState 12685 .getRuntimePermissionStates(userId); 12686 final int runtimePermCount = runtimePermStates.size(); 12687 for (int i = runtimePermCount - 1; i >= 0; i--) { 12688 PermissionState permissionState = runtimePermStates.get(i); 12689 if (!usedPermissions.contains(permissionState.getName())) { 12690 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12691 if (bp != null) { 12692 permissionsState.revokeRuntimePermission(bp, userId); 12693 permissionsState.updatePermissionFlags(bp, userId, 12694 PackageManager.MASK_PERMISSION_FLAGS, 0); 12695 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 12696 runtimePermissionChangedUserIds, userId); 12697 } 12698 } 12699 } 12700 } 12701 12702 return runtimePermissionChangedUserIds; 12703 } 12704 12705 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12706 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12707 UserHandle user) { 12708 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 12709 12710 String pkgName = newPackage.packageName; 12711 synchronized (mPackages) { 12712 //write settings. the installStatus will be incomplete at this stage. 12713 //note that the new package setting would have already been 12714 //added to mPackages. It hasn't been persisted yet. 12715 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12716 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12717 mSettings.writeLPr(); 12718 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12719 } 12720 12721 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12722 synchronized (mPackages) { 12723 updatePermissionsLPw(newPackage.packageName, newPackage, 12724 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12725 ? UPDATE_PERMISSIONS_ALL : 0)); 12726 // For system-bundled packages, we assume that installing an upgraded version 12727 // of the package implies that the user actually wants to run that new code, 12728 // so we enable the package. 12729 PackageSetting ps = mSettings.mPackages.get(pkgName); 12730 if (ps != null) { 12731 if (isSystemApp(newPackage)) { 12732 // NB: implicit assumption that system package upgrades apply to all users 12733 if (DEBUG_INSTALL) { 12734 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12735 } 12736 if (res.origUsers != null) { 12737 for (int userHandle : res.origUsers) { 12738 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12739 userHandle, installerPackageName); 12740 } 12741 } 12742 // Also convey the prior install/uninstall state 12743 if (allUsers != null && perUserInstalled != null) { 12744 for (int i = 0; i < allUsers.length; i++) { 12745 if (DEBUG_INSTALL) { 12746 Slog.d(TAG, " user " + allUsers[i] 12747 + " => " + perUserInstalled[i]); 12748 } 12749 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12750 } 12751 // these install state changes will be persisted in the 12752 // upcoming call to mSettings.writeLPr(). 12753 } 12754 } 12755 // It's implied that when a user requests installation, they want the app to be 12756 // installed and enabled. 12757 int userId = user.getIdentifier(); 12758 if (userId != UserHandle.USER_ALL) { 12759 ps.setInstalled(true, userId); 12760 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12761 } 12762 } 12763 res.name = pkgName; 12764 res.uid = newPackage.applicationInfo.uid; 12765 res.pkg = newPackage; 12766 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12767 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12768 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12769 //to update install status 12770 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12771 mSettings.writeLPr(); 12772 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12773 } 12774 12775 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12776 } 12777 12778 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 12779 try { 12780 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 12781 installPackageLI(args, res); 12782 } finally { 12783 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12784 } 12785 } 12786 12787 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12788 final int installFlags = args.installFlags; 12789 final String installerPackageName = args.installerPackageName; 12790 final String volumeUuid = args.volumeUuid; 12791 final File tmpPackageFile = new File(args.getCodePath()); 12792 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12793 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12794 || (args.volumeUuid != null)); 12795 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 12796 boolean replace = false; 12797 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12798 if (args.move != null) { 12799 // moving a complete application; perfom an initial scan on the new install location 12800 scanFlags |= SCAN_INITIAL; 12801 } 12802 // Result object to be returned 12803 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12804 12805 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12806 12807 // Sanity check 12808 if (ephemeral && (forwardLocked || onExternal)) { 12809 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 12810 + " external=" + onExternal); 12811 res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 12812 return; 12813 } 12814 12815 // Retrieve PackageSettings and parse package 12816 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12817 | PackageParser.PARSE_ENFORCE_CODE 12818 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12819 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 12820 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 12821 PackageParser pp = new PackageParser(); 12822 pp.setSeparateProcesses(mSeparateProcesses); 12823 pp.setDisplayMetrics(mMetrics); 12824 12825 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 12826 final PackageParser.Package pkg; 12827 try { 12828 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12829 } catch (PackageParserException e) { 12830 res.setError("Failed parse during installPackageLI", e); 12831 return; 12832 } finally { 12833 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12834 } 12835 12836 // If package doesn't declare API override, mark that we have an install 12837 // time CPU ABI override. 12838 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 12839 pkg.cpuAbiOverride = args.abiOverride; 12840 } 12841 12842 String pkgName = res.name = pkg.packageName; 12843 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12844 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12845 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12846 return; 12847 } 12848 } 12849 12850 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 12851 try { 12852 pp.collectCertificates(pkg, parseFlags); 12853 } catch (PackageParserException e) { 12854 res.setError("Failed collect during installPackageLI", e); 12855 return; 12856 } finally { 12857 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12858 } 12859 12860 // Get rid of all references to package scan path via parser. 12861 pp = null; 12862 String oldCodePath = null; 12863 boolean systemApp = false; 12864 synchronized (mPackages) { 12865 // Check if installing already existing package 12866 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12867 String oldName = mSettings.mRenamedPackages.get(pkgName); 12868 if (pkg.mOriginalPackages != null 12869 && pkg.mOriginalPackages.contains(oldName) 12870 && mPackages.containsKey(oldName)) { 12871 // This package is derived from an original package, 12872 // and this device has been updating from that original 12873 // name. We must continue using the original name, so 12874 // rename the new package here. 12875 pkg.setPackageName(oldName); 12876 pkgName = pkg.packageName; 12877 replace = true; 12878 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12879 + oldName + " pkgName=" + pkgName); 12880 } else if (mPackages.containsKey(pkgName)) { 12881 // This package, under its official name, already exists 12882 // on the device; we should replace it. 12883 replace = true; 12884 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12885 } 12886 12887 // Prevent apps opting out from runtime permissions 12888 if (replace) { 12889 PackageParser.Package oldPackage = mPackages.get(pkgName); 12890 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12891 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12892 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12893 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12894 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12895 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12896 + " doesn't support runtime permissions but the old" 12897 + " target SDK " + oldTargetSdk + " does."); 12898 return; 12899 } 12900 } 12901 } 12902 12903 PackageSetting ps = mSettings.mPackages.get(pkgName); 12904 if (ps != null) { 12905 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12906 12907 // Quick sanity check that we're signed correctly if updating; 12908 // we'll check this again later when scanning, but we want to 12909 // bail early here before tripping over redefined permissions. 12910 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12911 if (!checkUpgradeKeySetLP(ps, pkg)) { 12912 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12913 + pkg.packageName + " upgrade keys do not match the " 12914 + "previously installed version"); 12915 return; 12916 } 12917 } else { 12918 try { 12919 verifySignaturesLP(ps, pkg); 12920 } catch (PackageManagerException e) { 12921 res.setError(e.error, e.getMessage()); 12922 return; 12923 } 12924 } 12925 12926 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12927 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12928 systemApp = (ps.pkg.applicationInfo.flags & 12929 ApplicationInfo.FLAG_SYSTEM) != 0; 12930 } 12931 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12932 } 12933 12934 // Check whether the newly-scanned package wants to define an already-defined perm 12935 int N = pkg.permissions.size(); 12936 for (int i = N-1; i >= 0; i--) { 12937 PackageParser.Permission perm = pkg.permissions.get(i); 12938 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12939 if (bp != null) { 12940 // If the defining package is signed with our cert, it's okay. This 12941 // also includes the "updating the same package" case, of course. 12942 // "updating same package" could also involve key-rotation. 12943 final boolean sigsOk; 12944 if (bp.sourcePackage.equals(pkg.packageName) 12945 && (bp.packageSetting instanceof PackageSetting) 12946 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12947 scanFlags))) { 12948 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12949 } else { 12950 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12951 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12952 } 12953 if (!sigsOk) { 12954 // If the owning package is the system itself, we log but allow 12955 // install to proceed; we fail the install on all other permission 12956 // redefinitions. 12957 if (!bp.sourcePackage.equals("android")) { 12958 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12959 + pkg.packageName + " attempting to redeclare permission " 12960 + perm.info.name + " already owned by " + bp.sourcePackage); 12961 res.origPermission = perm.info.name; 12962 res.origPackage = bp.sourcePackage; 12963 return; 12964 } else { 12965 Slog.w(TAG, "Package " + pkg.packageName 12966 + " attempting to redeclare system permission " 12967 + perm.info.name + "; ignoring new declaration"); 12968 pkg.permissions.remove(i); 12969 } 12970 } 12971 } 12972 } 12973 12974 } 12975 12976 if (systemApp) { 12977 if (onExternal) { 12978 // Abort update; system app can't be replaced with app on sdcard 12979 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12980 "Cannot install updates to system apps on sdcard"); 12981 return; 12982 } else if (ephemeral) { 12983 // Abort update; system app can't be replaced with an ephemeral app 12984 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 12985 "Cannot update a system app with an ephemeral app"); 12986 return; 12987 } 12988 } 12989 12990 if (args.move != null) { 12991 // We did an in-place move, so dex is ready to roll 12992 scanFlags |= SCAN_NO_DEX; 12993 scanFlags |= SCAN_MOVE; 12994 12995 synchronized (mPackages) { 12996 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12997 if (ps == null) { 12998 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12999 "Missing settings for moved package " + pkgName); 13000 } 13001 13002 // We moved the entire application as-is, so bring over the 13003 // previously derived ABI information. 13004 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 13005 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 13006 } 13007 13008 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 13009 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 13010 scanFlags |= SCAN_NO_DEX; 13011 13012 try { 13013 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 13014 args.abiOverride : pkg.cpuAbiOverride); 13015 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 13016 true /* extract libs */); 13017 } catch (PackageManagerException pme) { 13018 Slog.e(TAG, "Error deriving application ABI", pme); 13019 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 13020 return; 13021 } 13022 13023 // Extract package to save the VM unzipping the APK in memory during 13024 // launch. Only do this if profile-guided compilation is enabled because 13025 // otherwise BackgroundDexOptService will not dexopt the package later. 13026 if (mUseJitProfiles) { 13027 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 13028 // Do not run PackageDexOptimizer through the local performDexOpt 13029 // method because `pkg` is not in `mPackages` yet. 13030 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 13031 false /* inclDependencies */, false /* useProfiles */, 13032 true /* extractOnly */); 13033 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13034 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 13035 String msg = "Extracking package failed for " + pkgName; 13036 res.setError(INSTALL_FAILED_DEXOPT, msg); 13037 return; 13038 } 13039 } 13040 } 13041 13042 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 13043 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 13044 return; 13045 } 13046 13047 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 13048 13049 if (replace) { 13050 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 13051 installerPackageName, volumeUuid, res); 13052 } else { 13053 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 13054 args.user, installerPackageName, volumeUuid, res); 13055 } 13056 synchronized (mPackages) { 13057 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13058 if (ps != null) { 13059 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13060 } 13061 } 13062 } 13063 13064 private void startIntentFilterVerifications(int userId, boolean replacing, 13065 PackageParser.Package pkg) { 13066 if (mIntentFilterVerifierComponent == null) { 13067 Slog.w(TAG, "No IntentFilter verification will not be done as " 13068 + "there is no IntentFilterVerifier available!"); 13069 return; 13070 } 13071 13072 final int verifierUid = getPackageUid( 13073 mIntentFilterVerifierComponent.getPackageName(), 13074 MATCH_DEBUG_TRIAGED_MISSING, 13075 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 13076 13077 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 13078 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 13079 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 13080 mHandler.sendMessage(msg); 13081 } 13082 13083 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 13084 PackageParser.Package pkg) { 13085 int size = pkg.activities.size(); 13086 if (size == 0) { 13087 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13088 "No activity, so no need to verify any IntentFilter!"); 13089 return; 13090 } 13091 13092 final boolean hasDomainURLs = hasDomainURLs(pkg); 13093 if (!hasDomainURLs) { 13094 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13095 "No domain URLs, so no need to verify any IntentFilter!"); 13096 return; 13097 } 13098 13099 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 13100 + " if any IntentFilter from the " + size 13101 + " Activities needs verification ..."); 13102 13103 int count = 0; 13104 final String packageName = pkg.packageName; 13105 13106 synchronized (mPackages) { 13107 // If this is a new install and we see that we've already run verification for this 13108 // package, we have nothing to do: it means the state was restored from backup. 13109 if (!replacing) { 13110 IntentFilterVerificationInfo ivi = 13111 mSettings.getIntentFilterVerificationLPr(packageName); 13112 if (ivi != null) { 13113 if (DEBUG_DOMAIN_VERIFICATION) { 13114 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 13115 + ivi.getStatusString()); 13116 } 13117 return; 13118 } 13119 } 13120 13121 // If any filters need to be verified, then all need to be. 13122 boolean needToVerify = false; 13123 for (PackageParser.Activity a : pkg.activities) { 13124 for (ActivityIntentInfo filter : a.intents) { 13125 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 13126 if (DEBUG_DOMAIN_VERIFICATION) { 13127 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 13128 } 13129 needToVerify = true; 13130 break; 13131 } 13132 } 13133 } 13134 13135 if (needToVerify) { 13136 final int verificationId = mIntentFilterVerificationToken++; 13137 for (PackageParser.Activity a : pkg.activities) { 13138 for (ActivityIntentInfo filter : a.intents) { 13139 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 13140 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13141 "Verification needed for IntentFilter:" + filter.toString()); 13142 mIntentFilterVerifier.addOneIntentFilterVerification( 13143 verifierUid, userId, verificationId, filter, packageName); 13144 count++; 13145 } 13146 } 13147 } 13148 } 13149 } 13150 13151 if (count > 0) { 13152 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 13153 + " IntentFilter verification" + (count > 1 ? "s" : "") 13154 + " for userId:" + userId); 13155 mIntentFilterVerifier.startVerifications(userId); 13156 } else { 13157 if (DEBUG_DOMAIN_VERIFICATION) { 13158 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 13159 } 13160 } 13161 } 13162 13163 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 13164 final ComponentName cn = filter.activity.getComponentName(); 13165 final String packageName = cn.getPackageName(); 13166 13167 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 13168 packageName); 13169 if (ivi == null) { 13170 return true; 13171 } 13172 int status = ivi.getStatus(); 13173 switch (status) { 13174 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 13175 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 13176 return true; 13177 13178 default: 13179 // Nothing to do 13180 return false; 13181 } 13182 } 13183 13184 private static boolean isMultiArch(ApplicationInfo info) { 13185 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 13186 } 13187 13188 private static boolean isExternal(PackageParser.Package pkg) { 13189 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13190 } 13191 13192 private static boolean isExternal(PackageSetting ps) { 13193 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13194 } 13195 13196 private static boolean isEphemeral(PackageParser.Package pkg) { 13197 return pkg.applicationInfo.isEphemeralApp(); 13198 } 13199 13200 private static boolean isEphemeral(PackageSetting ps) { 13201 return ps.pkg != null && isEphemeral(ps.pkg); 13202 } 13203 13204 private static boolean isSystemApp(PackageParser.Package pkg) { 13205 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 13206 } 13207 13208 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 13209 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 13210 } 13211 13212 private static boolean hasDomainURLs(PackageParser.Package pkg) { 13213 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 13214 } 13215 13216 private static boolean isSystemApp(PackageSetting ps) { 13217 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 13218 } 13219 13220 private static boolean isUpdatedSystemApp(PackageSetting ps) { 13221 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 13222 } 13223 13224 private int packageFlagsToInstallFlags(PackageSetting ps) { 13225 int installFlags = 0; 13226 if (isEphemeral(ps)) { 13227 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13228 } 13229 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 13230 // This existing package was an external ASEC install when we have 13231 // the external flag without a UUID 13232 installFlags |= PackageManager.INSTALL_EXTERNAL; 13233 } 13234 if (ps.isForwardLocked()) { 13235 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13236 } 13237 return installFlags; 13238 } 13239 13240 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 13241 if (isExternal(pkg)) { 13242 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13243 return StorageManager.UUID_PRIMARY_PHYSICAL; 13244 } else { 13245 return pkg.volumeUuid; 13246 } 13247 } else { 13248 return StorageManager.UUID_PRIVATE_INTERNAL; 13249 } 13250 } 13251 13252 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 13253 if (isExternal(pkg)) { 13254 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13255 return mSettings.getExternalVersion(); 13256 } else { 13257 return mSettings.findOrCreateVersion(pkg.volumeUuid); 13258 } 13259 } else { 13260 return mSettings.getInternalVersion(); 13261 } 13262 } 13263 13264 private void deleteTempPackageFiles() { 13265 final FilenameFilter filter = new FilenameFilter() { 13266 public boolean accept(File dir, String name) { 13267 return name.startsWith("vmdl") && name.endsWith(".tmp"); 13268 } 13269 }; 13270 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 13271 file.delete(); 13272 } 13273 } 13274 13275 @Override 13276 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 13277 int flags) { 13278 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 13279 flags); 13280 } 13281 13282 @Override 13283 public void deletePackage(final String packageName, 13284 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 13285 mContext.enforceCallingOrSelfPermission( 13286 android.Manifest.permission.DELETE_PACKAGES, null); 13287 Preconditions.checkNotNull(packageName); 13288 Preconditions.checkNotNull(observer); 13289 final int uid = Binder.getCallingUid(); 13290 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 13291 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 13292 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 13293 mContext.enforceCallingOrSelfPermission( 13294 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 13295 "deletePackage for user " + userId); 13296 } 13297 13298 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 13299 try { 13300 observer.onPackageDeleted(packageName, 13301 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 13302 } catch (RemoteException re) { 13303 } 13304 return; 13305 } 13306 13307 for (int currentUserId : users) { 13308 if (getBlockUninstallForUser(packageName, currentUserId)) { 13309 try { 13310 observer.onPackageDeleted(packageName, 13311 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 13312 } catch (RemoteException re) { 13313 } 13314 return; 13315 } 13316 } 13317 13318 if (DEBUG_REMOVE) { 13319 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 13320 } 13321 // Queue up an async operation since the package deletion may take a little while. 13322 mHandler.post(new Runnable() { 13323 public void run() { 13324 mHandler.removeCallbacks(this); 13325 final int returnCode = deletePackageX(packageName, userId, flags); 13326 try { 13327 observer.onPackageDeleted(packageName, returnCode, null); 13328 } catch (RemoteException e) { 13329 Log.i(TAG, "Observer no longer exists."); 13330 } //end catch 13331 } //end run 13332 }); 13333 } 13334 13335 private boolean isPackageDeviceAdmin(String packageName, int userId) { 13336 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13337 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13338 try { 13339 if (dpm != null) { 13340 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 13341 /* callingUserOnly =*/ false); 13342 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 13343 : deviceOwnerComponentName.getPackageName(); 13344 // Does the package contains the device owner? 13345 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 13346 // this check is probably not needed, since DO should be registered as a device 13347 // admin on some user too. (Original bug for this: b/17657954) 13348 if (packageName.equals(deviceOwnerPackageName)) { 13349 return true; 13350 } 13351 // Does it contain a device admin for any user? 13352 int[] users; 13353 if (userId == UserHandle.USER_ALL) { 13354 users = sUserManager.getUserIds(); 13355 } else { 13356 users = new int[]{userId}; 13357 } 13358 for (int i = 0; i < users.length; ++i) { 13359 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 13360 return true; 13361 } 13362 } 13363 } 13364 } catch (RemoteException e) { 13365 } 13366 return false; 13367 } 13368 13369 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 13370 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 13371 } 13372 13373 /** 13374 * This method is an internal method that could be get invoked either 13375 * to delete an installed package or to clean up a failed installation. 13376 * After deleting an installed package, a broadcast is sent to notify any 13377 * listeners that the package has been installed. For cleaning up a failed 13378 * installation, the broadcast is not necessary since the package's 13379 * installation wouldn't have sent the initial broadcast either 13380 * The key steps in deleting a package are 13381 * deleting the package information in internal structures like mPackages, 13382 * deleting the packages base directories through installd 13383 * updating mSettings to reflect current status 13384 * persisting settings for later use 13385 * sending a broadcast if necessary 13386 */ 13387 private int deletePackageX(String packageName, int userId, int flags) { 13388 final PackageRemovedInfo info = new PackageRemovedInfo(); 13389 final boolean res; 13390 13391 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 13392 ? UserHandle.ALL : new UserHandle(userId); 13393 13394 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 13395 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 13396 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 13397 } 13398 13399 boolean removedForAllUsers = false; 13400 boolean systemUpdate = false; 13401 13402 PackageParser.Package uninstalledPkg; 13403 13404 // for the uninstall-updates case and restricted profiles, remember the per- 13405 // userhandle installed state 13406 int[] allUsers; 13407 boolean[] perUserInstalled; 13408 synchronized (mPackages) { 13409 uninstalledPkg = mPackages.get(packageName); 13410 PackageSetting ps = mSettings.mPackages.get(packageName); 13411 allUsers = sUserManager.getUserIds(); 13412 perUserInstalled = new boolean[allUsers.length]; 13413 for (int i = 0; i < allUsers.length; i++) { 13414 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 13415 } 13416 } 13417 13418 synchronized (mInstallLock) { 13419 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 13420 res = deletePackageLI(packageName, removeForUser, 13421 true, allUsers, perUserInstalled, 13422 flags | REMOVE_CHATTY, info, true); 13423 systemUpdate = info.isRemovedPackageSystemUpdate; 13424 synchronized (mPackages) { 13425 if (res) { 13426 if (!systemUpdate && mPackages.get(packageName) == null) { 13427 removedForAllUsers = true; 13428 } 13429 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg); 13430 } 13431 } 13432 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 13433 + " removedForAllUsers=" + removedForAllUsers); 13434 } 13435 13436 if (res) { 13437 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 13438 13439 // If the removed package was a system update, the old system package 13440 // was re-enabled; we need to broadcast this information 13441 if (systemUpdate) { 13442 Bundle extras = new Bundle(1); 13443 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 13444 ? info.removedAppId : info.uid); 13445 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13446 13447 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 13448 extras, 0, null, null, null); 13449 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 13450 extras, 0, null, null, null); 13451 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 13452 null, 0, packageName, null, null); 13453 } 13454 } 13455 // Force a gc here. 13456 Runtime.getRuntime().gc(); 13457 // Delete the resources here after sending the broadcast to let 13458 // other processes clean up before deleting resources. 13459 if (info.args != null) { 13460 synchronized (mInstallLock) { 13461 info.args.doPostDeleteLI(true); 13462 } 13463 } 13464 13465 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 13466 } 13467 13468 class PackageRemovedInfo { 13469 String removedPackage; 13470 int uid = -1; 13471 int removedAppId = -1; 13472 int[] removedUsers = null; 13473 boolean isRemovedPackageSystemUpdate = false; 13474 // Clean up resources deleted packages. 13475 InstallArgs args = null; 13476 13477 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 13478 Bundle extras = new Bundle(1); 13479 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 13480 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 13481 if (replacing) { 13482 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13483 } 13484 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 13485 if (removedPackage != null) { 13486 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 13487 extras, 0, null, null, removedUsers); 13488 if (fullRemove && !replacing) { 13489 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 13490 extras, 0, null, null, removedUsers); 13491 } 13492 } 13493 if (removedAppId >= 0) { 13494 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 13495 removedUsers); 13496 } 13497 } 13498 } 13499 13500 /* 13501 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 13502 * flag is not set, the data directory is removed as well. 13503 * make sure this flag is set for partially installed apps. If not its meaningless to 13504 * delete a partially installed application. 13505 */ 13506 private void removePackageDataLI(PackageSetting ps, 13507 int[] allUserHandles, boolean[] perUserInstalled, 13508 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 13509 String packageName = ps.name; 13510 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 13511 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 13512 // Retrieve object to delete permissions for shared user later on 13513 final PackageSetting deletedPs; 13514 // reader 13515 synchronized (mPackages) { 13516 deletedPs = mSettings.mPackages.get(packageName); 13517 if (outInfo != null) { 13518 outInfo.removedPackage = packageName; 13519 outInfo.removedUsers = deletedPs != null 13520 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 13521 : null; 13522 } 13523 } 13524 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13525 removeDataDirsLI(ps.volumeUuid, packageName); 13526 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 13527 } 13528 // writer 13529 synchronized (mPackages) { 13530 if (deletedPs != null) { 13531 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13532 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 13533 clearDefaultBrowserIfNeeded(packageName); 13534 if (outInfo != null) { 13535 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 13536 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 13537 } 13538 updatePermissionsLPw(deletedPs.name, null, 0); 13539 if (deletedPs.sharedUser != null) { 13540 // Remove permissions associated with package. Since runtime 13541 // permissions are per user we have to kill the removed package 13542 // or packages running under the shared user of the removed 13543 // package if revoking the permissions requested only by the removed 13544 // package is successful and this causes a change in gids. 13545 for (int userId : UserManagerService.getInstance().getUserIds()) { 13546 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 13547 userId); 13548 if (userIdToKill == UserHandle.USER_ALL 13549 || userIdToKill >= UserHandle.USER_SYSTEM) { 13550 // If gids changed for this user, kill all affected packages. 13551 mHandler.post(new Runnable() { 13552 @Override 13553 public void run() { 13554 // This has to happen with no lock held. 13555 killApplication(deletedPs.name, deletedPs.appId, 13556 KILL_APP_REASON_GIDS_CHANGED); 13557 } 13558 }); 13559 break; 13560 } 13561 } 13562 } 13563 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 13564 } 13565 // make sure to preserve per-user disabled state if this removal was just 13566 // a downgrade of a system app to the factory package 13567 if (allUserHandles != null && perUserInstalled != null) { 13568 if (DEBUG_REMOVE) { 13569 Slog.d(TAG, "Propagating install state across downgrade"); 13570 } 13571 for (int i = 0; i < allUserHandles.length; i++) { 13572 if (DEBUG_REMOVE) { 13573 Slog.d(TAG, " user " + allUserHandles[i] 13574 + " => " + perUserInstalled[i]); 13575 } 13576 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13577 } 13578 } 13579 } 13580 // can downgrade to reader 13581 if (writeSettings) { 13582 // Save settings now 13583 mSettings.writeLPr(); 13584 } 13585 } 13586 if (outInfo != null) { 13587 // A user ID was deleted here. Go through all users and remove it 13588 // from KeyStore. 13589 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 13590 } 13591 } 13592 13593 static boolean locationIsPrivileged(File path) { 13594 try { 13595 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 13596 .getCanonicalPath(); 13597 return path.getCanonicalPath().startsWith(privilegedAppDir); 13598 } catch (IOException e) { 13599 Slog.e(TAG, "Unable to access code path " + path); 13600 } 13601 return false; 13602 } 13603 13604 /* 13605 * Tries to delete system package. 13606 */ 13607 private boolean deleteSystemPackageLI(PackageSetting newPs, 13608 int[] allUserHandles, boolean[] perUserInstalled, 13609 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 13610 final boolean applyUserRestrictions 13611 = (allUserHandles != null) && (perUserInstalled != null); 13612 PackageSetting disabledPs = null; 13613 // Confirm if the system package has been updated 13614 // An updated system app can be deleted. This will also have to restore 13615 // the system pkg from system partition 13616 // reader 13617 synchronized (mPackages) { 13618 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13619 } 13620 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13621 + " disabledPs=" + disabledPs); 13622 if (disabledPs == null) { 13623 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13624 return false; 13625 } else if (DEBUG_REMOVE) { 13626 Slog.d(TAG, "Deleting system pkg from data partition"); 13627 } 13628 if (DEBUG_REMOVE) { 13629 if (applyUserRestrictions) { 13630 Slog.d(TAG, "Remembering install states:"); 13631 for (int i = 0; i < allUserHandles.length; i++) { 13632 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13633 } 13634 } 13635 } 13636 // Delete the updated package 13637 outInfo.isRemovedPackageSystemUpdate = true; 13638 if (disabledPs.versionCode < newPs.versionCode) { 13639 // Delete data for downgrades 13640 flags &= ~PackageManager.DELETE_KEEP_DATA; 13641 } else { 13642 // Preserve data by setting flag 13643 flags |= PackageManager.DELETE_KEEP_DATA; 13644 } 13645 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13646 allUserHandles, perUserInstalled, outInfo, writeSettings); 13647 if (!ret) { 13648 return false; 13649 } 13650 // writer 13651 synchronized (mPackages) { 13652 // Reinstate the old system package 13653 mSettings.enableSystemPackageLPw(newPs.name); 13654 // Remove any native libraries from the upgraded package. 13655 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13656 } 13657 // Install the system package 13658 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13659 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13660 if (locationIsPrivileged(disabledPs.codePath)) { 13661 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13662 } 13663 13664 final PackageParser.Package newPkg; 13665 try { 13666 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 13667 } catch (PackageManagerException e) { 13668 Slog.w(TAG, "Failed to restore system package " + newPs.name + ": " + e.getMessage()); 13669 return false; 13670 } 13671 13672 prepareAppDataAfterInstall(newPkg); 13673 13674 // writer 13675 synchronized (mPackages) { 13676 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13677 13678 // Propagate the permissions state as we do not want to drop on the floor 13679 // runtime permissions. The update permissions method below will take 13680 // care of removing obsolete permissions and grant install permissions. 13681 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13682 updatePermissionsLPw(newPkg.packageName, newPkg, 13683 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13684 13685 if (applyUserRestrictions) { 13686 if (DEBUG_REMOVE) { 13687 Slog.d(TAG, "Propagating install state across reinstall"); 13688 } 13689 for (int i = 0; i < allUserHandles.length; i++) { 13690 if (DEBUG_REMOVE) { 13691 Slog.d(TAG, " user " + allUserHandles[i] 13692 + " => " + perUserInstalled[i]); 13693 } 13694 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13695 13696 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13697 } 13698 // Regardless of writeSettings we need to ensure that this restriction 13699 // state propagation is persisted 13700 mSettings.writeAllUsersPackageRestrictionsLPr(); 13701 } 13702 // can downgrade to reader here 13703 if (writeSettings) { 13704 mSettings.writeLPr(); 13705 } 13706 } 13707 return true; 13708 } 13709 13710 private boolean deleteInstalledPackageLI(PackageSetting ps, 13711 boolean deleteCodeAndResources, int flags, 13712 int[] allUserHandles, boolean[] perUserInstalled, 13713 PackageRemovedInfo outInfo, boolean writeSettings) { 13714 if (outInfo != null) { 13715 outInfo.uid = ps.appId; 13716 } 13717 13718 // Delete package data from internal structures and also remove data if flag is set 13719 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13720 13721 // Delete application code and resources 13722 if (deleteCodeAndResources && (outInfo != null)) { 13723 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13724 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13725 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13726 } 13727 return true; 13728 } 13729 13730 @Override 13731 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13732 int userId) { 13733 mContext.enforceCallingOrSelfPermission( 13734 android.Manifest.permission.DELETE_PACKAGES, null); 13735 synchronized (mPackages) { 13736 PackageSetting ps = mSettings.mPackages.get(packageName); 13737 if (ps == null) { 13738 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13739 return false; 13740 } 13741 if (!ps.getInstalled(userId)) { 13742 // Can't block uninstall for an app that is not installed or enabled. 13743 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13744 return false; 13745 } 13746 ps.setBlockUninstall(blockUninstall, userId); 13747 mSettings.writePackageRestrictionsLPr(userId); 13748 } 13749 return true; 13750 } 13751 13752 @Override 13753 public boolean getBlockUninstallForUser(String packageName, int userId) { 13754 synchronized (mPackages) { 13755 PackageSetting ps = mSettings.mPackages.get(packageName); 13756 if (ps == null) { 13757 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13758 return false; 13759 } 13760 return ps.getBlockUninstall(userId); 13761 } 13762 } 13763 13764 @Override 13765 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 13766 int callingUid = Binder.getCallingUid(); 13767 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 13768 throw new SecurityException( 13769 "setRequiredForSystemUser can only be run by the system or root"); 13770 } 13771 synchronized (mPackages) { 13772 PackageSetting ps = mSettings.mPackages.get(packageName); 13773 if (ps == null) { 13774 Log.w(TAG, "Package doesn't exist: " + packageName); 13775 return false; 13776 } 13777 if (systemUserApp) { 13778 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 13779 } else { 13780 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 13781 } 13782 mSettings.writeLPr(); 13783 } 13784 return true; 13785 } 13786 13787 /* 13788 * This method handles package deletion in general 13789 */ 13790 private boolean deletePackageLI(String packageName, UserHandle user, 13791 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13792 int flags, PackageRemovedInfo outInfo, 13793 boolean writeSettings) { 13794 if (packageName == null) { 13795 Slog.w(TAG, "Attempt to delete null packageName."); 13796 return false; 13797 } 13798 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13799 PackageSetting ps; 13800 boolean dataOnly = false; 13801 int removeUser = -1; 13802 int appId = -1; 13803 synchronized (mPackages) { 13804 ps = mSettings.mPackages.get(packageName); 13805 if (ps == null) { 13806 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13807 return false; 13808 } 13809 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13810 && user.getIdentifier() != UserHandle.USER_ALL) { 13811 // The caller is asking that the package only be deleted for a single 13812 // user. To do this, we just mark its uninstalled state and delete 13813 // its data. If this is a system app, we only allow this to happen if 13814 // they have set the special DELETE_SYSTEM_APP which requests different 13815 // semantics than normal for uninstalling system apps. 13816 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13817 final int userId = user.getIdentifier(); 13818 ps.setUserState(userId, 13819 COMPONENT_ENABLED_STATE_DEFAULT, 13820 false, //installed 13821 true, //stopped 13822 true, //notLaunched 13823 false, //hidden 13824 false, //suspended 13825 null, null, null, 13826 false, // blockUninstall 13827 ps.readUserState(userId).domainVerificationStatus, 0); 13828 if (!isSystemApp(ps)) { 13829 // Do not uninstall the APK if an app should be cached 13830 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 13831 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 13832 // Other user still have this package installed, so all 13833 // we need to do is clear this user's data and save that 13834 // it is uninstalled. 13835 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13836 removeUser = user.getIdentifier(); 13837 appId = ps.appId; 13838 scheduleWritePackageRestrictionsLocked(removeUser); 13839 } else { 13840 // We need to set it back to 'installed' so the uninstall 13841 // broadcasts will be sent correctly. 13842 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13843 ps.setInstalled(true, user.getIdentifier()); 13844 } 13845 } else { 13846 // This is a system app, so we assume that the 13847 // other users still have this package installed, so all 13848 // we need to do is clear this user's data and save that 13849 // it is uninstalled. 13850 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13851 removeUser = user.getIdentifier(); 13852 appId = ps.appId; 13853 scheduleWritePackageRestrictionsLocked(removeUser); 13854 } 13855 } 13856 } 13857 13858 if (removeUser >= 0) { 13859 // From above, we determined that we are deleting this only 13860 // for a single user. Continue the work here. 13861 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13862 if (outInfo != null) { 13863 outInfo.removedPackage = packageName; 13864 outInfo.removedAppId = appId; 13865 outInfo.removedUsers = new int[] {removeUser}; 13866 } 13867 // TODO: triage flags as part of 26466827 13868 final int installerFlags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 13869 try { 13870 mInstaller.destroyAppData(ps.volumeUuid, packageName, removeUser, installerFlags); 13871 } catch (InstallerException e) { 13872 Slog.w(TAG, "Failed to delete app data", e); 13873 } 13874 removeKeystoreDataIfNeeded(removeUser, appId); 13875 schedulePackageCleaning(packageName, removeUser, false); 13876 synchronized (mPackages) { 13877 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13878 scheduleWritePackageRestrictionsLocked(removeUser); 13879 } 13880 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13881 } 13882 return true; 13883 } 13884 13885 if (dataOnly) { 13886 // Delete application data first 13887 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13888 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13889 return true; 13890 } 13891 13892 boolean ret = false; 13893 if (isSystemApp(ps)) { 13894 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 13895 // When an updated system application is deleted we delete the existing resources as well and 13896 // fall back to existing code in system partition 13897 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13898 flags, outInfo, writeSettings); 13899 } else { 13900 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 13901 // Kill application pre-emptively especially for apps on sd. 13902 killApplication(packageName, ps.appId, "uninstall pkg"); 13903 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13904 allUserHandles, perUserInstalled, 13905 outInfo, writeSettings); 13906 } 13907 13908 return ret; 13909 } 13910 13911 private final static class ClearStorageConnection implements ServiceConnection { 13912 IMediaContainerService mContainerService; 13913 13914 @Override 13915 public void onServiceConnected(ComponentName name, IBinder service) { 13916 synchronized (this) { 13917 mContainerService = IMediaContainerService.Stub.asInterface(service); 13918 notifyAll(); 13919 } 13920 } 13921 13922 @Override 13923 public void onServiceDisconnected(ComponentName name) { 13924 } 13925 } 13926 13927 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13928 final boolean mounted; 13929 if (Environment.isExternalStorageEmulated()) { 13930 mounted = true; 13931 } else { 13932 final String status = Environment.getExternalStorageState(); 13933 13934 mounted = status.equals(Environment.MEDIA_MOUNTED) 13935 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13936 } 13937 13938 if (!mounted) { 13939 return; 13940 } 13941 13942 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13943 int[] users; 13944 if (userId == UserHandle.USER_ALL) { 13945 users = sUserManager.getUserIds(); 13946 } else { 13947 users = new int[] { userId }; 13948 } 13949 final ClearStorageConnection conn = new ClearStorageConnection(); 13950 if (mContext.bindServiceAsUser( 13951 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 13952 try { 13953 for (int curUser : users) { 13954 long timeout = SystemClock.uptimeMillis() + 5000; 13955 synchronized (conn) { 13956 long now = SystemClock.uptimeMillis(); 13957 while (conn.mContainerService == null && now < timeout) { 13958 try { 13959 conn.wait(timeout - now); 13960 } catch (InterruptedException e) { 13961 } 13962 } 13963 } 13964 if (conn.mContainerService == null) { 13965 return; 13966 } 13967 13968 final UserEnvironment userEnv = new UserEnvironment(curUser); 13969 clearDirectory(conn.mContainerService, 13970 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13971 if (allData) { 13972 clearDirectory(conn.mContainerService, 13973 userEnv.buildExternalStorageAppDataDirs(packageName)); 13974 clearDirectory(conn.mContainerService, 13975 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13976 } 13977 } 13978 } finally { 13979 mContext.unbindService(conn); 13980 } 13981 } 13982 } 13983 13984 @Override 13985 public void clearApplicationUserData(final String packageName, 13986 final IPackageDataObserver observer, final int userId) { 13987 mContext.enforceCallingOrSelfPermission( 13988 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13989 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13990 // Queue up an async operation since the package deletion may take a little while. 13991 mHandler.post(new Runnable() { 13992 public void run() { 13993 mHandler.removeCallbacks(this); 13994 final boolean succeeded; 13995 synchronized (mInstallLock) { 13996 succeeded = clearApplicationUserDataLI(packageName, userId); 13997 } 13998 clearExternalStorageDataSync(packageName, userId, true); 13999 if (succeeded) { 14000 // invoke DeviceStorageMonitor's update method to clear any notifications 14001 DeviceStorageMonitorInternal 14002 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 14003 if (dsm != null) { 14004 dsm.checkMemory(); 14005 } 14006 } 14007 if(observer != null) { 14008 try { 14009 observer.onRemoveCompleted(packageName, succeeded); 14010 } catch (RemoteException e) { 14011 Log.i(TAG, "Observer no longer exists."); 14012 } 14013 } //end if observer 14014 } //end run 14015 }); 14016 } 14017 14018 private boolean clearApplicationUserDataLI(String packageName, int userId) { 14019 if (packageName == null) { 14020 Slog.w(TAG, "Attempt to delete null packageName."); 14021 return false; 14022 } 14023 14024 // Try finding details about the requested package 14025 PackageParser.Package pkg; 14026 synchronized (mPackages) { 14027 pkg = mPackages.get(packageName); 14028 if (pkg == null) { 14029 final PackageSetting ps = mSettings.mPackages.get(packageName); 14030 if (ps != null) { 14031 pkg = ps.pkg; 14032 } 14033 } 14034 14035 if (pkg == null) { 14036 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 14037 return false; 14038 } 14039 14040 PackageSetting ps = (PackageSetting) pkg.mExtras; 14041 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 14042 } 14043 14044 // Always delete data directories for package, even if we found no other 14045 // record of app. This helps users recover from UID mismatches without 14046 // resorting to a full data wipe. 14047 // TODO: triage flags as part of 26466827 14048 final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 14049 try { 14050 mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags); 14051 } catch (InstallerException e) { 14052 Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e); 14053 return false; 14054 } 14055 14056 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 14057 removeKeystoreDataIfNeeded(userId, appId); 14058 14059 // Create a native library symlink only if we have native libraries 14060 // and if the native libraries are 32 bit libraries. We do not provide 14061 // this symlink for 64 bit libraries. 14062 if (pkg.applicationInfo.primaryCpuAbi != null && 14063 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 14064 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 14065 try { 14066 mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 14067 nativeLibPath, userId); 14068 } catch (InstallerException e) { 14069 Slog.w(TAG, "Failed linking native library dir", e); 14070 return false; 14071 } 14072 } 14073 14074 return true; 14075 } 14076 14077 /** 14078 * Reverts user permission state changes (permissions and flags) in 14079 * all packages for a given user. 14080 * 14081 * @param userId The device user for which to do a reset. 14082 */ 14083 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 14084 final int packageCount = mPackages.size(); 14085 for (int i = 0; i < packageCount; i++) { 14086 PackageParser.Package pkg = mPackages.valueAt(i); 14087 PackageSetting ps = (PackageSetting) pkg.mExtras; 14088 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 14089 } 14090 } 14091 14092 /** 14093 * Reverts user permission state changes (permissions and flags). 14094 * 14095 * @param ps The package for which to reset. 14096 * @param userId The device user for which to do a reset. 14097 */ 14098 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 14099 final PackageSetting ps, final int userId) { 14100 if (ps.pkg == null) { 14101 return; 14102 } 14103 14104 // These are flags that can change base on user actions. 14105 final int userSettableMask = FLAG_PERMISSION_USER_SET 14106 | FLAG_PERMISSION_USER_FIXED 14107 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 14108 | FLAG_PERMISSION_REVIEW_REQUIRED; 14109 14110 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 14111 | FLAG_PERMISSION_POLICY_FIXED; 14112 14113 boolean writeInstallPermissions = false; 14114 boolean writeRuntimePermissions = false; 14115 14116 final int permissionCount = ps.pkg.requestedPermissions.size(); 14117 for (int i = 0; i < permissionCount; i++) { 14118 String permission = ps.pkg.requestedPermissions.get(i); 14119 14120 BasePermission bp = mSettings.mPermissions.get(permission); 14121 if (bp == null) { 14122 continue; 14123 } 14124 14125 // If shared user we just reset the state to which only this app contributed. 14126 if (ps.sharedUser != null) { 14127 boolean used = false; 14128 final int packageCount = ps.sharedUser.packages.size(); 14129 for (int j = 0; j < packageCount; j++) { 14130 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 14131 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 14132 && pkg.pkg.requestedPermissions.contains(permission)) { 14133 used = true; 14134 break; 14135 } 14136 } 14137 if (used) { 14138 continue; 14139 } 14140 } 14141 14142 PermissionsState permissionsState = ps.getPermissionsState(); 14143 14144 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 14145 14146 // Always clear the user settable flags. 14147 final boolean hasInstallState = permissionsState.getInstallPermissionState( 14148 bp.name) != null; 14149 // If permission review is enabled and this is a legacy app, mark the 14150 // permission as requiring a review as this is the initial state. 14151 int flags = 0; 14152 if (Build.PERMISSIONS_REVIEW_REQUIRED 14153 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 14154 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 14155 } 14156 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 14157 if (hasInstallState) { 14158 writeInstallPermissions = true; 14159 } else { 14160 writeRuntimePermissions = true; 14161 } 14162 } 14163 14164 // Below is only runtime permission handling. 14165 if (!bp.isRuntime()) { 14166 continue; 14167 } 14168 14169 // Never clobber system or policy. 14170 if ((oldFlags & policyOrSystemFlags) != 0) { 14171 continue; 14172 } 14173 14174 // If this permission was granted by default, make sure it is. 14175 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 14176 if (permissionsState.grantRuntimePermission(bp, userId) 14177 != PERMISSION_OPERATION_FAILURE) { 14178 writeRuntimePermissions = true; 14179 } 14180 // If permission review is enabled the permissions for a legacy apps 14181 // are represented as constantly granted runtime ones, so don't revoke. 14182 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 14183 // Otherwise, reset the permission. 14184 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 14185 switch (revokeResult) { 14186 case PERMISSION_OPERATION_SUCCESS: { 14187 writeRuntimePermissions = true; 14188 } break; 14189 14190 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 14191 writeRuntimePermissions = true; 14192 final int appId = ps.appId; 14193 mHandler.post(new Runnable() { 14194 @Override 14195 public void run() { 14196 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 14197 } 14198 }); 14199 } break; 14200 } 14201 } 14202 } 14203 14204 // Synchronously write as we are taking permissions away. 14205 if (writeRuntimePermissions) { 14206 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 14207 } 14208 14209 // Synchronously write as we are taking permissions away. 14210 if (writeInstallPermissions) { 14211 mSettings.writeLPr(); 14212 } 14213 } 14214 14215 /** 14216 * Remove entries from the keystore daemon. Will only remove it if the 14217 * {@code appId} is valid. 14218 */ 14219 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 14220 if (appId < 0) { 14221 return; 14222 } 14223 14224 final KeyStore keyStore = KeyStore.getInstance(); 14225 if (keyStore != null) { 14226 if (userId == UserHandle.USER_ALL) { 14227 for (final int individual : sUserManager.getUserIds()) { 14228 keyStore.clearUid(UserHandle.getUid(individual, appId)); 14229 } 14230 } else { 14231 keyStore.clearUid(UserHandle.getUid(userId, appId)); 14232 } 14233 } else { 14234 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 14235 } 14236 } 14237 14238 @Override 14239 public void deleteApplicationCacheFiles(final String packageName, 14240 final IPackageDataObserver observer) { 14241 mContext.enforceCallingOrSelfPermission( 14242 android.Manifest.permission.DELETE_CACHE_FILES, null); 14243 // Queue up an async operation since the package deletion may take a little while. 14244 final int userId = UserHandle.getCallingUserId(); 14245 mHandler.post(new Runnable() { 14246 public void run() { 14247 mHandler.removeCallbacks(this); 14248 final boolean succeded; 14249 synchronized (mInstallLock) { 14250 succeded = deleteApplicationCacheFilesLI(packageName, userId); 14251 } 14252 clearExternalStorageDataSync(packageName, userId, false); 14253 if (observer != null) { 14254 try { 14255 observer.onRemoveCompleted(packageName, succeded); 14256 } catch (RemoteException e) { 14257 Log.i(TAG, "Observer no longer exists."); 14258 } 14259 } //end if observer 14260 } //end run 14261 }); 14262 } 14263 14264 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 14265 if (packageName == null) { 14266 Slog.w(TAG, "Attempt to delete null packageName."); 14267 return false; 14268 } 14269 PackageParser.Package p; 14270 synchronized (mPackages) { 14271 p = mPackages.get(packageName); 14272 } 14273 if (p == null) { 14274 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14275 return false; 14276 } 14277 final ApplicationInfo applicationInfo = p.applicationInfo; 14278 if (applicationInfo == null) { 14279 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14280 return false; 14281 } 14282 // TODO: triage flags as part of 26466827 14283 final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 14284 try { 14285 mInstaller.clearAppData(p.volumeUuid, packageName, userId, 14286 flags | Installer.FLAG_CLEAR_CACHE_ONLY); 14287 } catch (InstallerException e) { 14288 Slog.w(TAG, "Couldn't remove cache files for package " 14289 + packageName + " u" + userId, e); 14290 return false; 14291 } 14292 return true; 14293 } 14294 14295 @Override 14296 public void getPackageSizeInfo(final String packageName, int userHandle, 14297 final IPackageStatsObserver observer) { 14298 mContext.enforceCallingOrSelfPermission( 14299 android.Manifest.permission.GET_PACKAGE_SIZE, null); 14300 if (packageName == null) { 14301 throw new IllegalArgumentException("Attempt to get size of null packageName"); 14302 } 14303 14304 PackageStats stats = new PackageStats(packageName, userHandle); 14305 14306 /* 14307 * Queue up an async operation since the package measurement may take a 14308 * little while. 14309 */ 14310 Message msg = mHandler.obtainMessage(INIT_COPY); 14311 msg.obj = new MeasureParams(stats, observer); 14312 mHandler.sendMessage(msg); 14313 } 14314 14315 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 14316 PackageStats pStats) { 14317 if (packageName == null) { 14318 Slog.w(TAG, "Attempt to get size of null packageName."); 14319 return false; 14320 } 14321 PackageParser.Package p; 14322 boolean dataOnly = false; 14323 String libDirRoot = null; 14324 String asecPath = null; 14325 PackageSetting ps = null; 14326 synchronized (mPackages) { 14327 p = mPackages.get(packageName); 14328 ps = mSettings.mPackages.get(packageName); 14329 if(p == null) { 14330 dataOnly = true; 14331 if((ps == null) || (ps.pkg == null)) { 14332 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14333 return false; 14334 } 14335 p = ps.pkg; 14336 } 14337 if (ps != null) { 14338 libDirRoot = ps.legacyNativeLibraryPathString; 14339 } 14340 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 14341 final long token = Binder.clearCallingIdentity(); 14342 try { 14343 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 14344 if (secureContainerId != null) { 14345 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 14346 } 14347 } finally { 14348 Binder.restoreCallingIdentity(token); 14349 } 14350 } 14351 } 14352 String publicSrcDir = null; 14353 if(!dataOnly) { 14354 final ApplicationInfo applicationInfo = p.applicationInfo; 14355 if (applicationInfo == null) { 14356 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14357 return false; 14358 } 14359 if (p.isForwardLocked()) { 14360 publicSrcDir = applicationInfo.getBaseResourcePath(); 14361 } 14362 } 14363 // TODO: extend to measure size of split APKs 14364 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 14365 // not just the first level. 14366 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 14367 // just the primary. 14368 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 14369 14370 String apkPath; 14371 File packageDir = new File(p.codePath); 14372 14373 if (packageDir.isDirectory() && p.canHaveOatDir()) { 14374 apkPath = packageDir.getAbsolutePath(); 14375 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 14376 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 14377 libDirRoot = null; 14378 } 14379 } else { 14380 apkPath = p.baseCodePath; 14381 } 14382 14383 // TODO: triage flags as part of 26466827 14384 final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 14385 try { 14386 mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath, 14387 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 14388 } catch (InstallerException e) { 14389 return false; 14390 } 14391 14392 // Fix-up for forward-locked applications in ASEC containers. 14393 if (!isExternal(p)) { 14394 pStats.codeSize += pStats.externalCodeSize; 14395 pStats.externalCodeSize = 0L; 14396 } 14397 14398 return true; 14399 } 14400 14401 14402 @Override 14403 public void addPackageToPreferred(String packageName) { 14404 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 14405 } 14406 14407 @Override 14408 public void removePackageFromPreferred(String packageName) { 14409 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 14410 } 14411 14412 @Override 14413 public List<PackageInfo> getPreferredPackages(int flags) { 14414 return new ArrayList<PackageInfo>(); 14415 } 14416 14417 private int getUidTargetSdkVersionLockedLPr(int uid) { 14418 Object obj = mSettings.getUserIdLPr(uid); 14419 if (obj instanceof SharedUserSetting) { 14420 final SharedUserSetting sus = (SharedUserSetting) obj; 14421 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 14422 final Iterator<PackageSetting> it = sus.packages.iterator(); 14423 while (it.hasNext()) { 14424 final PackageSetting ps = it.next(); 14425 if (ps.pkg != null) { 14426 int v = ps.pkg.applicationInfo.targetSdkVersion; 14427 if (v < vers) vers = v; 14428 } 14429 } 14430 return vers; 14431 } else if (obj instanceof PackageSetting) { 14432 final PackageSetting ps = (PackageSetting) obj; 14433 if (ps.pkg != null) { 14434 return ps.pkg.applicationInfo.targetSdkVersion; 14435 } 14436 } 14437 return Build.VERSION_CODES.CUR_DEVELOPMENT; 14438 } 14439 14440 @Override 14441 public void addPreferredActivity(IntentFilter filter, int match, 14442 ComponentName[] set, ComponentName activity, int userId) { 14443 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14444 "Adding preferred"); 14445 } 14446 14447 private void addPreferredActivityInternal(IntentFilter filter, int match, 14448 ComponentName[] set, ComponentName activity, boolean always, int userId, 14449 String opname) { 14450 // writer 14451 int callingUid = Binder.getCallingUid(); 14452 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 14453 if (filter.countActions() == 0) { 14454 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14455 return; 14456 } 14457 synchronized (mPackages) { 14458 if (mContext.checkCallingOrSelfPermission( 14459 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14460 != PackageManager.PERMISSION_GRANTED) { 14461 if (getUidTargetSdkVersionLockedLPr(callingUid) 14462 < Build.VERSION_CODES.FROYO) { 14463 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 14464 + callingUid); 14465 return; 14466 } 14467 mContext.enforceCallingOrSelfPermission( 14468 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14469 } 14470 14471 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 14472 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 14473 + userId + ":"); 14474 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14475 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 14476 scheduleWritePackageRestrictionsLocked(userId); 14477 } 14478 } 14479 14480 @Override 14481 public void replacePreferredActivity(IntentFilter filter, int match, 14482 ComponentName[] set, ComponentName activity, int userId) { 14483 if (filter.countActions() != 1) { 14484 throw new IllegalArgumentException( 14485 "replacePreferredActivity expects filter to have only 1 action."); 14486 } 14487 if (filter.countDataAuthorities() != 0 14488 || filter.countDataPaths() != 0 14489 || filter.countDataSchemes() > 1 14490 || filter.countDataTypes() != 0) { 14491 throw new IllegalArgumentException( 14492 "replacePreferredActivity expects filter to have no data authorities, " + 14493 "paths, or types; and at most one scheme."); 14494 } 14495 14496 final int callingUid = Binder.getCallingUid(); 14497 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 14498 synchronized (mPackages) { 14499 if (mContext.checkCallingOrSelfPermission( 14500 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14501 != PackageManager.PERMISSION_GRANTED) { 14502 if (getUidTargetSdkVersionLockedLPr(callingUid) 14503 < Build.VERSION_CODES.FROYO) { 14504 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 14505 + Binder.getCallingUid()); 14506 return; 14507 } 14508 mContext.enforceCallingOrSelfPermission( 14509 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14510 } 14511 14512 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14513 if (pir != null) { 14514 // Get all of the existing entries that exactly match this filter. 14515 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 14516 if (existing != null && existing.size() == 1) { 14517 PreferredActivity cur = existing.get(0); 14518 if (DEBUG_PREFERRED) { 14519 Slog.i(TAG, "Checking replace of preferred:"); 14520 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14521 if (!cur.mPref.mAlways) { 14522 Slog.i(TAG, " -- CUR; not mAlways!"); 14523 } else { 14524 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 14525 Slog.i(TAG, " -- CUR: mSet=" 14526 + Arrays.toString(cur.mPref.mSetComponents)); 14527 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 14528 Slog.i(TAG, " -- NEW: mMatch=" 14529 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 14530 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 14531 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 14532 } 14533 } 14534 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 14535 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 14536 && cur.mPref.sameSet(set)) { 14537 // Setting the preferred activity to what it happens to be already 14538 if (DEBUG_PREFERRED) { 14539 Slog.i(TAG, "Replacing with same preferred activity " 14540 + cur.mPref.mShortComponent + " for user " 14541 + userId + ":"); 14542 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14543 } 14544 return; 14545 } 14546 } 14547 14548 if (existing != null) { 14549 if (DEBUG_PREFERRED) { 14550 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 14551 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14552 } 14553 for (int i = 0; i < existing.size(); i++) { 14554 PreferredActivity pa = existing.get(i); 14555 if (DEBUG_PREFERRED) { 14556 Slog.i(TAG, "Removing existing preferred activity " 14557 + pa.mPref.mComponent + ":"); 14558 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 14559 } 14560 pir.removeFilter(pa); 14561 } 14562 } 14563 } 14564 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14565 "Replacing preferred"); 14566 } 14567 } 14568 14569 @Override 14570 public void clearPackagePreferredActivities(String packageName) { 14571 final int uid = Binder.getCallingUid(); 14572 // writer 14573 synchronized (mPackages) { 14574 PackageParser.Package pkg = mPackages.get(packageName); 14575 if (pkg == null || pkg.applicationInfo.uid != uid) { 14576 if (mContext.checkCallingOrSelfPermission( 14577 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14578 != PackageManager.PERMISSION_GRANTED) { 14579 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 14580 < Build.VERSION_CODES.FROYO) { 14581 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 14582 + Binder.getCallingUid()); 14583 return; 14584 } 14585 mContext.enforceCallingOrSelfPermission( 14586 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14587 } 14588 } 14589 14590 int user = UserHandle.getCallingUserId(); 14591 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 14592 scheduleWritePackageRestrictionsLocked(user); 14593 } 14594 } 14595 } 14596 14597 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14598 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 14599 ArrayList<PreferredActivity> removed = null; 14600 boolean changed = false; 14601 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14602 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 14603 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14604 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 14605 continue; 14606 } 14607 Iterator<PreferredActivity> it = pir.filterIterator(); 14608 while (it.hasNext()) { 14609 PreferredActivity pa = it.next(); 14610 // Mark entry for removal only if it matches the package name 14611 // and the entry is of type "always". 14612 if (packageName == null || 14613 (pa.mPref.mComponent.getPackageName().equals(packageName) 14614 && pa.mPref.mAlways)) { 14615 if (removed == null) { 14616 removed = new ArrayList<PreferredActivity>(); 14617 } 14618 removed.add(pa); 14619 } 14620 } 14621 if (removed != null) { 14622 for (int j=0; j<removed.size(); j++) { 14623 PreferredActivity pa = removed.get(j); 14624 pir.removeFilter(pa); 14625 } 14626 changed = true; 14627 } 14628 } 14629 return changed; 14630 } 14631 14632 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14633 private void clearIntentFilterVerificationsLPw(int userId) { 14634 final int packageCount = mPackages.size(); 14635 for (int i = 0; i < packageCount; i++) { 14636 PackageParser.Package pkg = mPackages.valueAt(i); 14637 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 14638 } 14639 } 14640 14641 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14642 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 14643 if (userId == UserHandle.USER_ALL) { 14644 if (mSettings.removeIntentFilterVerificationLPw(packageName, 14645 sUserManager.getUserIds())) { 14646 for (int oneUserId : sUserManager.getUserIds()) { 14647 scheduleWritePackageRestrictionsLocked(oneUserId); 14648 } 14649 } 14650 } else { 14651 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 14652 scheduleWritePackageRestrictionsLocked(userId); 14653 } 14654 } 14655 } 14656 14657 void clearDefaultBrowserIfNeeded(String packageName) { 14658 for (int oneUserId : sUserManager.getUserIds()) { 14659 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 14660 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 14661 if (packageName.equals(defaultBrowserPackageName)) { 14662 setDefaultBrowserPackageName(null, oneUserId); 14663 } 14664 } 14665 } 14666 14667 @Override 14668 public void resetApplicationPreferences(int userId) { 14669 mContext.enforceCallingOrSelfPermission( 14670 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14671 // writer 14672 synchronized (mPackages) { 14673 final long identity = Binder.clearCallingIdentity(); 14674 try { 14675 clearPackagePreferredActivitiesLPw(null, userId); 14676 mSettings.applyDefaultPreferredAppsLPw(this, userId); 14677 // TODO: We have to reset the default SMS and Phone. This requires 14678 // significant refactoring to keep all default apps in the package 14679 // manager (cleaner but more work) or have the services provide 14680 // callbacks to the package manager to request a default app reset. 14681 applyFactoryDefaultBrowserLPw(userId); 14682 clearIntentFilterVerificationsLPw(userId); 14683 primeDomainVerificationsLPw(userId); 14684 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 14685 scheduleWritePackageRestrictionsLocked(userId); 14686 } finally { 14687 Binder.restoreCallingIdentity(identity); 14688 } 14689 } 14690 } 14691 14692 @Override 14693 public int getPreferredActivities(List<IntentFilter> outFilters, 14694 List<ComponentName> outActivities, String packageName) { 14695 14696 int num = 0; 14697 final int userId = UserHandle.getCallingUserId(); 14698 // reader 14699 synchronized (mPackages) { 14700 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14701 if (pir != null) { 14702 final Iterator<PreferredActivity> it = pir.filterIterator(); 14703 while (it.hasNext()) { 14704 final PreferredActivity pa = it.next(); 14705 if (packageName == null 14706 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14707 && pa.mPref.mAlways)) { 14708 if (outFilters != null) { 14709 outFilters.add(new IntentFilter(pa)); 14710 } 14711 if (outActivities != null) { 14712 outActivities.add(pa.mPref.mComponent); 14713 } 14714 } 14715 } 14716 } 14717 } 14718 14719 return num; 14720 } 14721 14722 @Override 14723 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14724 int userId) { 14725 int callingUid = Binder.getCallingUid(); 14726 if (callingUid != Process.SYSTEM_UID) { 14727 throw new SecurityException( 14728 "addPersistentPreferredActivity can only be run by the system"); 14729 } 14730 if (filter.countActions() == 0) { 14731 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14732 return; 14733 } 14734 synchronized (mPackages) { 14735 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14736 ":"); 14737 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14738 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14739 new PersistentPreferredActivity(filter, activity)); 14740 scheduleWritePackageRestrictionsLocked(userId); 14741 } 14742 } 14743 14744 @Override 14745 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14746 int callingUid = Binder.getCallingUid(); 14747 if (callingUid != Process.SYSTEM_UID) { 14748 throw new SecurityException( 14749 "clearPackagePersistentPreferredActivities can only be run by the system"); 14750 } 14751 ArrayList<PersistentPreferredActivity> removed = null; 14752 boolean changed = false; 14753 synchronized (mPackages) { 14754 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14755 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14756 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14757 .valueAt(i); 14758 if (userId != thisUserId) { 14759 continue; 14760 } 14761 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14762 while (it.hasNext()) { 14763 PersistentPreferredActivity ppa = it.next(); 14764 // Mark entry for removal only if it matches the package name. 14765 if (ppa.mComponent.getPackageName().equals(packageName)) { 14766 if (removed == null) { 14767 removed = new ArrayList<PersistentPreferredActivity>(); 14768 } 14769 removed.add(ppa); 14770 } 14771 } 14772 if (removed != null) { 14773 for (int j=0; j<removed.size(); j++) { 14774 PersistentPreferredActivity ppa = removed.get(j); 14775 ppir.removeFilter(ppa); 14776 } 14777 changed = true; 14778 } 14779 } 14780 14781 if (changed) { 14782 scheduleWritePackageRestrictionsLocked(userId); 14783 } 14784 } 14785 } 14786 14787 /** 14788 * Common machinery for picking apart a restored XML blob and passing 14789 * it to a caller-supplied functor to be applied to the running system. 14790 */ 14791 private void restoreFromXml(XmlPullParser parser, int userId, 14792 String expectedStartTag, BlobXmlRestorer functor) 14793 throws IOException, XmlPullParserException { 14794 int type; 14795 while ((type = parser.next()) != XmlPullParser.START_TAG 14796 && type != XmlPullParser.END_DOCUMENT) { 14797 } 14798 if (type != XmlPullParser.START_TAG) { 14799 // oops didn't find a start tag?! 14800 if (DEBUG_BACKUP) { 14801 Slog.e(TAG, "Didn't find start tag during restore"); 14802 } 14803 return; 14804 } 14805Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 14806 // this is supposed to be TAG_PREFERRED_BACKUP 14807 if (!expectedStartTag.equals(parser.getName())) { 14808 if (DEBUG_BACKUP) { 14809 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14810 } 14811 return; 14812 } 14813 14814 // skip interfering stuff, then we're aligned with the backing implementation 14815 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14816Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 14817 functor.apply(parser, userId); 14818 } 14819 14820 private interface BlobXmlRestorer { 14821 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14822 } 14823 14824 /** 14825 * Non-Binder method, support for the backup/restore mechanism: write the 14826 * full set of preferred activities in its canonical XML format. Returns the 14827 * XML output as a byte array, or null if there is none. 14828 */ 14829 @Override 14830 public byte[] getPreferredActivityBackup(int userId) { 14831 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14832 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14833 } 14834 14835 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14836 try { 14837 final XmlSerializer serializer = new FastXmlSerializer(); 14838 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14839 serializer.startDocument(null, true); 14840 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14841 14842 synchronized (mPackages) { 14843 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14844 } 14845 14846 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14847 serializer.endDocument(); 14848 serializer.flush(); 14849 } catch (Exception e) { 14850 if (DEBUG_BACKUP) { 14851 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14852 } 14853 return null; 14854 } 14855 14856 return dataStream.toByteArray(); 14857 } 14858 14859 @Override 14860 public void restorePreferredActivities(byte[] backup, int userId) { 14861 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14862 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14863 } 14864 14865 try { 14866 final XmlPullParser parser = Xml.newPullParser(); 14867 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14868 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14869 new BlobXmlRestorer() { 14870 @Override 14871 public void apply(XmlPullParser parser, int userId) 14872 throws XmlPullParserException, IOException { 14873 synchronized (mPackages) { 14874 mSettings.readPreferredActivitiesLPw(parser, userId); 14875 } 14876 } 14877 } ); 14878 } catch (Exception e) { 14879 if (DEBUG_BACKUP) { 14880 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14881 } 14882 } 14883 } 14884 14885 /** 14886 * Non-Binder method, support for the backup/restore mechanism: write the 14887 * default browser (etc) settings in its canonical XML format. Returns the default 14888 * browser XML representation as a byte array, or null if there is none. 14889 */ 14890 @Override 14891 public byte[] getDefaultAppsBackup(int userId) { 14892 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14893 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14894 } 14895 14896 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14897 try { 14898 final XmlSerializer serializer = new FastXmlSerializer(); 14899 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14900 serializer.startDocument(null, true); 14901 serializer.startTag(null, TAG_DEFAULT_APPS); 14902 14903 synchronized (mPackages) { 14904 mSettings.writeDefaultAppsLPr(serializer, userId); 14905 } 14906 14907 serializer.endTag(null, TAG_DEFAULT_APPS); 14908 serializer.endDocument(); 14909 serializer.flush(); 14910 } catch (Exception e) { 14911 if (DEBUG_BACKUP) { 14912 Slog.e(TAG, "Unable to write default apps for backup", e); 14913 } 14914 return null; 14915 } 14916 14917 return dataStream.toByteArray(); 14918 } 14919 14920 @Override 14921 public void restoreDefaultApps(byte[] backup, int userId) { 14922 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14923 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14924 } 14925 14926 try { 14927 final XmlPullParser parser = Xml.newPullParser(); 14928 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14929 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14930 new BlobXmlRestorer() { 14931 @Override 14932 public void apply(XmlPullParser parser, int userId) 14933 throws XmlPullParserException, IOException { 14934 synchronized (mPackages) { 14935 mSettings.readDefaultAppsLPw(parser, userId); 14936 } 14937 } 14938 } ); 14939 } catch (Exception e) { 14940 if (DEBUG_BACKUP) { 14941 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14942 } 14943 } 14944 } 14945 14946 @Override 14947 public byte[] getIntentFilterVerificationBackup(int userId) { 14948 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14949 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14950 } 14951 14952 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14953 try { 14954 final XmlSerializer serializer = new FastXmlSerializer(); 14955 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14956 serializer.startDocument(null, true); 14957 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14958 14959 synchronized (mPackages) { 14960 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14961 } 14962 14963 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14964 serializer.endDocument(); 14965 serializer.flush(); 14966 } catch (Exception e) { 14967 if (DEBUG_BACKUP) { 14968 Slog.e(TAG, "Unable to write default apps for backup", e); 14969 } 14970 return null; 14971 } 14972 14973 return dataStream.toByteArray(); 14974 } 14975 14976 @Override 14977 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14978 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14979 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14980 } 14981 14982 try { 14983 final XmlPullParser parser = Xml.newPullParser(); 14984 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14985 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14986 new BlobXmlRestorer() { 14987 @Override 14988 public void apply(XmlPullParser parser, int userId) 14989 throws XmlPullParserException, IOException { 14990 synchronized (mPackages) { 14991 mSettings.readAllDomainVerificationsLPr(parser, userId); 14992 mSettings.writeLPr(); 14993 } 14994 } 14995 } ); 14996 } catch (Exception e) { 14997 if (DEBUG_BACKUP) { 14998 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14999 } 15000 } 15001 } 15002 15003 @Override 15004 public byte[] getPermissionGrantBackup(int userId) { 15005 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15006 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 15007 } 15008 15009 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 15010 try { 15011 final XmlSerializer serializer = new FastXmlSerializer(); 15012 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 15013 serializer.startDocument(null, true); 15014 serializer.startTag(null, TAG_PERMISSION_BACKUP); 15015 15016 synchronized (mPackages) { 15017 serializeRuntimePermissionGrantsLPr(serializer, userId); 15018 } 15019 15020 serializer.endTag(null, TAG_PERMISSION_BACKUP); 15021 serializer.endDocument(); 15022 serializer.flush(); 15023 } catch (Exception e) { 15024 if (DEBUG_BACKUP) { 15025 Slog.e(TAG, "Unable to write default apps for backup", e); 15026 } 15027 return null; 15028 } 15029 15030 return dataStream.toByteArray(); 15031 } 15032 15033 @Override 15034 public void restorePermissionGrants(byte[] backup, int userId) { 15035 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15036 throw new SecurityException("Only the system may call restorePermissionGrants()"); 15037 } 15038 15039 try { 15040 final XmlPullParser parser = Xml.newPullParser(); 15041 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 15042 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 15043 new BlobXmlRestorer() { 15044 @Override 15045 public void apply(XmlPullParser parser, int userId) 15046 throws XmlPullParserException, IOException { 15047 synchronized (mPackages) { 15048 processRestoredPermissionGrantsLPr(parser, userId); 15049 } 15050 } 15051 } ); 15052 } catch (Exception e) { 15053 if (DEBUG_BACKUP) { 15054 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 15055 } 15056 } 15057 } 15058 15059 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 15060 throws IOException { 15061 serializer.startTag(null, TAG_ALL_GRANTS); 15062 15063 final int N = mSettings.mPackages.size(); 15064 for (int i = 0; i < N; i++) { 15065 final PackageSetting ps = mSettings.mPackages.valueAt(i); 15066 boolean pkgGrantsKnown = false; 15067 15068 PermissionsState packagePerms = ps.getPermissionsState(); 15069 15070 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 15071 final int grantFlags = state.getFlags(); 15072 // only look at grants that are not system/policy fixed 15073 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 15074 final boolean isGranted = state.isGranted(); 15075 // And only back up the user-twiddled state bits 15076 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 15077 final String packageName = mSettings.mPackages.keyAt(i); 15078 if (!pkgGrantsKnown) { 15079 serializer.startTag(null, TAG_GRANT); 15080 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 15081 pkgGrantsKnown = true; 15082 } 15083 15084 final boolean userSet = 15085 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 15086 final boolean userFixed = 15087 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 15088 final boolean revoke = 15089 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 15090 15091 serializer.startTag(null, TAG_PERMISSION); 15092 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 15093 if (isGranted) { 15094 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 15095 } 15096 if (userSet) { 15097 serializer.attribute(null, ATTR_USER_SET, "true"); 15098 } 15099 if (userFixed) { 15100 serializer.attribute(null, ATTR_USER_FIXED, "true"); 15101 } 15102 if (revoke) { 15103 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 15104 } 15105 serializer.endTag(null, TAG_PERMISSION); 15106 } 15107 } 15108 } 15109 15110 if (pkgGrantsKnown) { 15111 serializer.endTag(null, TAG_GRANT); 15112 } 15113 } 15114 15115 serializer.endTag(null, TAG_ALL_GRANTS); 15116 } 15117 15118 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 15119 throws XmlPullParserException, IOException { 15120 String pkgName = null; 15121 int outerDepth = parser.getDepth(); 15122 int type; 15123 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 15124 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 15125 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 15126 continue; 15127 } 15128 15129 final String tagName = parser.getName(); 15130 if (tagName.equals(TAG_GRANT)) { 15131 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 15132 if (DEBUG_BACKUP) { 15133 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 15134 } 15135 } else if (tagName.equals(TAG_PERMISSION)) { 15136 15137 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 15138 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 15139 15140 int newFlagSet = 0; 15141 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 15142 newFlagSet |= FLAG_PERMISSION_USER_SET; 15143 } 15144 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 15145 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 15146 } 15147 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 15148 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 15149 } 15150 if (DEBUG_BACKUP) { 15151 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 15152 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 15153 } 15154 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15155 if (ps != null) { 15156 // Already installed so we apply the grant immediately 15157 if (DEBUG_BACKUP) { 15158 Slog.v(TAG, " + already installed; applying"); 15159 } 15160 PermissionsState perms = ps.getPermissionsState(); 15161 BasePermission bp = mSettings.mPermissions.get(permName); 15162 if (bp != null) { 15163 if (isGranted) { 15164 perms.grantRuntimePermission(bp, userId); 15165 } 15166 if (newFlagSet != 0) { 15167 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 15168 } 15169 } 15170 } else { 15171 // Need to wait for post-restore install to apply the grant 15172 if (DEBUG_BACKUP) { 15173 Slog.v(TAG, " - not yet installed; saving for later"); 15174 } 15175 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 15176 isGranted, newFlagSet, userId); 15177 } 15178 } else { 15179 PackageManagerService.reportSettingsProblem(Log.WARN, 15180 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 15181 XmlUtils.skipCurrentTag(parser); 15182 } 15183 } 15184 15185 scheduleWriteSettingsLocked(); 15186 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15187 } 15188 15189 @Override 15190 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 15191 int sourceUserId, int targetUserId, int flags) { 15192 mContext.enforceCallingOrSelfPermission( 15193 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 15194 int callingUid = Binder.getCallingUid(); 15195 enforceOwnerRights(ownerPackage, callingUid); 15196 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 15197 if (intentFilter.countActions() == 0) { 15198 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 15199 return; 15200 } 15201 synchronized (mPackages) { 15202 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 15203 ownerPackage, targetUserId, flags); 15204 CrossProfileIntentResolver resolver = 15205 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 15206 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 15207 // We have all those whose filter is equal. Now checking if the rest is equal as well. 15208 if (existing != null) { 15209 int size = existing.size(); 15210 for (int i = 0; i < size; i++) { 15211 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 15212 return; 15213 } 15214 } 15215 } 15216 resolver.addFilter(newFilter); 15217 scheduleWritePackageRestrictionsLocked(sourceUserId); 15218 } 15219 } 15220 15221 @Override 15222 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 15223 mContext.enforceCallingOrSelfPermission( 15224 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 15225 int callingUid = Binder.getCallingUid(); 15226 enforceOwnerRights(ownerPackage, callingUid); 15227 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 15228 synchronized (mPackages) { 15229 CrossProfileIntentResolver resolver = 15230 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 15231 ArraySet<CrossProfileIntentFilter> set = 15232 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 15233 for (CrossProfileIntentFilter filter : set) { 15234 if (filter.getOwnerPackage().equals(ownerPackage)) { 15235 resolver.removeFilter(filter); 15236 } 15237 } 15238 scheduleWritePackageRestrictionsLocked(sourceUserId); 15239 } 15240 } 15241 15242 // Enforcing that callingUid is owning pkg on userId 15243 private void enforceOwnerRights(String pkg, int callingUid) { 15244 // The system owns everything. 15245 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 15246 return; 15247 } 15248 int callingUserId = UserHandle.getUserId(callingUid); 15249 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 15250 if (pi == null) { 15251 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 15252 + callingUserId); 15253 } 15254 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 15255 throw new SecurityException("Calling uid " + callingUid 15256 + " does not own package " + pkg); 15257 } 15258 } 15259 15260 @Override 15261 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 15262 Intent intent = new Intent(Intent.ACTION_MAIN); 15263 intent.addCategory(Intent.CATEGORY_HOME); 15264 15265 final int callingUserId = UserHandle.getCallingUserId(); 15266 List<ResolveInfo> list = queryIntentActivities(intent, null, 15267 PackageManager.GET_META_DATA, callingUserId); 15268 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 15269 true, false, false, callingUserId); 15270 15271 allHomeCandidates.clear(); 15272 if (list != null) { 15273 for (ResolveInfo ri : list) { 15274 allHomeCandidates.add(ri); 15275 } 15276 } 15277 return (preferred == null || preferred.activityInfo == null) 15278 ? null 15279 : new ComponentName(preferred.activityInfo.packageName, 15280 preferred.activityInfo.name); 15281 } 15282 15283 @Override 15284 public void setApplicationEnabledSetting(String appPackageName, 15285 int newState, int flags, int userId, String callingPackage) { 15286 if (!sUserManager.exists(userId)) return; 15287 if (callingPackage == null) { 15288 callingPackage = Integer.toString(Binder.getCallingUid()); 15289 } 15290 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 15291 } 15292 15293 @Override 15294 public void setComponentEnabledSetting(ComponentName componentName, 15295 int newState, int flags, int userId) { 15296 if (!sUserManager.exists(userId)) return; 15297 setEnabledSetting(componentName.getPackageName(), 15298 componentName.getClassName(), newState, flags, userId, null); 15299 } 15300 15301 private void setEnabledSetting(final String packageName, String className, int newState, 15302 final int flags, int userId, String callingPackage) { 15303 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 15304 || newState == COMPONENT_ENABLED_STATE_ENABLED 15305 || newState == COMPONENT_ENABLED_STATE_DISABLED 15306 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 15307 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 15308 throw new IllegalArgumentException("Invalid new component state: " 15309 + newState); 15310 } 15311 PackageSetting pkgSetting; 15312 final int uid = Binder.getCallingUid(); 15313 final int permission = mContext.checkCallingOrSelfPermission( 15314 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 15315 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 15316 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 15317 boolean sendNow = false; 15318 boolean isApp = (className == null); 15319 String componentName = isApp ? packageName : className; 15320 int packageUid = -1; 15321 ArrayList<String> components; 15322 15323 // writer 15324 synchronized (mPackages) { 15325 pkgSetting = mSettings.mPackages.get(packageName); 15326 if (pkgSetting == null) { 15327 if (className == null) { 15328 throw new IllegalArgumentException("Unknown package: " + packageName); 15329 } 15330 throw new IllegalArgumentException( 15331 "Unknown component: " + packageName + "/" + className); 15332 } 15333 // Allow root and verify that userId is not being specified by a different user 15334 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 15335 throw new SecurityException( 15336 "Permission Denial: attempt to change component state from pid=" 15337 + Binder.getCallingPid() 15338 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 15339 } 15340 if (className == null) { 15341 // We're dealing with an application/package level state change 15342 if (pkgSetting.getEnabled(userId) == newState) { 15343 // Nothing to do 15344 return; 15345 } 15346 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 15347 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 15348 // Don't care about who enables an app. 15349 callingPackage = null; 15350 } 15351 pkgSetting.setEnabled(newState, userId, callingPackage); 15352 // pkgSetting.pkg.mSetEnabled = newState; 15353 } else { 15354 // We're dealing with a component level state change 15355 // First, verify that this is a valid class name. 15356 PackageParser.Package pkg = pkgSetting.pkg; 15357 if (pkg == null || !pkg.hasComponentClassName(className)) { 15358 if (pkg != null && 15359 pkg.applicationInfo.targetSdkVersion >= 15360 Build.VERSION_CODES.JELLY_BEAN) { 15361 throw new IllegalArgumentException("Component class " + className 15362 + " does not exist in " + packageName); 15363 } else { 15364 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 15365 + className + " does not exist in " + packageName); 15366 } 15367 } 15368 switch (newState) { 15369 case COMPONENT_ENABLED_STATE_ENABLED: 15370 if (!pkgSetting.enableComponentLPw(className, userId)) { 15371 return; 15372 } 15373 break; 15374 case COMPONENT_ENABLED_STATE_DISABLED: 15375 if (!pkgSetting.disableComponentLPw(className, userId)) { 15376 return; 15377 } 15378 break; 15379 case COMPONENT_ENABLED_STATE_DEFAULT: 15380 if (!pkgSetting.restoreComponentLPw(className, userId)) { 15381 return; 15382 } 15383 break; 15384 default: 15385 Slog.e(TAG, "Invalid new component state: " + newState); 15386 return; 15387 } 15388 } 15389 scheduleWritePackageRestrictionsLocked(userId); 15390 components = mPendingBroadcasts.get(userId, packageName); 15391 final boolean newPackage = components == null; 15392 if (newPackage) { 15393 components = new ArrayList<String>(); 15394 } 15395 if (!components.contains(componentName)) { 15396 components.add(componentName); 15397 } 15398 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 15399 sendNow = true; 15400 // Purge entry from pending broadcast list if another one exists already 15401 // since we are sending one right away. 15402 mPendingBroadcasts.remove(userId, packageName); 15403 } else { 15404 if (newPackage) { 15405 mPendingBroadcasts.put(userId, packageName, components); 15406 } 15407 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 15408 // Schedule a message 15409 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 15410 } 15411 } 15412 } 15413 15414 long callingId = Binder.clearCallingIdentity(); 15415 try { 15416 if (sendNow) { 15417 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 15418 sendPackageChangedBroadcast(packageName, 15419 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 15420 } 15421 } finally { 15422 Binder.restoreCallingIdentity(callingId); 15423 } 15424 } 15425 15426 private void sendPackageChangedBroadcast(String packageName, 15427 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 15428 if (DEBUG_INSTALL) 15429 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 15430 + componentNames); 15431 Bundle extras = new Bundle(4); 15432 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 15433 String nameList[] = new String[componentNames.size()]; 15434 componentNames.toArray(nameList); 15435 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 15436 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 15437 extras.putInt(Intent.EXTRA_UID, packageUid); 15438 // If this is not reporting a change of the overall package, then only send it 15439 // to registered receivers. We don't want to launch a swath of apps for every 15440 // little component state change. 15441 final int flags = !componentNames.contains(packageName) 15442 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 15443 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 15444 new int[] {UserHandle.getUserId(packageUid)}); 15445 } 15446 15447 @Override 15448 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 15449 if (!sUserManager.exists(userId)) return; 15450 final int uid = Binder.getCallingUid(); 15451 final int permission = mContext.checkCallingOrSelfPermission( 15452 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 15453 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 15454 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 15455 // writer 15456 synchronized (mPackages) { 15457 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 15458 allowedByPermission, uid, userId)) { 15459 scheduleWritePackageRestrictionsLocked(userId); 15460 } 15461 } 15462 } 15463 15464 @Override 15465 public String getInstallerPackageName(String packageName) { 15466 // reader 15467 synchronized (mPackages) { 15468 return mSettings.getInstallerPackageNameLPr(packageName); 15469 } 15470 } 15471 15472 @Override 15473 public int getApplicationEnabledSetting(String packageName, int userId) { 15474 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 15475 int uid = Binder.getCallingUid(); 15476 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 15477 // reader 15478 synchronized (mPackages) { 15479 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 15480 } 15481 } 15482 15483 @Override 15484 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 15485 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 15486 int uid = Binder.getCallingUid(); 15487 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 15488 // reader 15489 synchronized (mPackages) { 15490 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 15491 } 15492 } 15493 15494 @Override 15495 public void enterSafeMode() { 15496 enforceSystemOrRoot("Only the system can request entering safe mode"); 15497 15498 if (!mSystemReady) { 15499 mSafeMode = true; 15500 } 15501 } 15502 15503 @Override 15504 public void systemReady() { 15505 mSystemReady = true; 15506 15507 // Read the compatibilty setting when the system is ready. 15508 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 15509 mContext.getContentResolver(), 15510 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 15511 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 15512 if (DEBUG_SETTINGS) { 15513 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 15514 } 15515 15516 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 15517 15518 synchronized (mPackages) { 15519 // Verify that all of the preferred activity components actually 15520 // exist. It is possible for applications to be updated and at 15521 // that point remove a previously declared activity component that 15522 // had been set as a preferred activity. We try to clean this up 15523 // the next time we encounter that preferred activity, but it is 15524 // possible for the user flow to never be able to return to that 15525 // situation so here we do a sanity check to make sure we haven't 15526 // left any junk around. 15527 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 15528 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15529 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15530 removed.clear(); 15531 for (PreferredActivity pa : pir.filterSet()) { 15532 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 15533 removed.add(pa); 15534 } 15535 } 15536 if (removed.size() > 0) { 15537 for (int r=0; r<removed.size(); r++) { 15538 PreferredActivity pa = removed.get(r); 15539 Slog.w(TAG, "Removing dangling preferred activity: " 15540 + pa.mPref.mComponent); 15541 pir.removeFilter(pa); 15542 } 15543 mSettings.writePackageRestrictionsLPr( 15544 mSettings.mPreferredActivities.keyAt(i)); 15545 } 15546 } 15547 15548 for (int userId : UserManagerService.getInstance().getUserIds()) { 15549 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 15550 grantPermissionsUserIds = ArrayUtils.appendInt( 15551 grantPermissionsUserIds, userId); 15552 } 15553 } 15554 } 15555 sUserManager.systemReady(); 15556 15557 // If we upgraded grant all default permissions before kicking off. 15558 for (int userId : grantPermissionsUserIds) { 15559 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 15560 } 15561 15562 // Kick off any messages waiting for system ready 15563 if (mPostSystemReadyMessages != null) { 15564 for (Message msg : mPostSystemReadyMessages) { 15565 msg.sendToTarget(); 15566 } 15567 mPostSystemReadyMessages = null; 15568 } 15569 15570 // Watch for external volumes that come and go over time 15571 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15572 storage.registerListener(mStorageListener); 15573 15574 mInstallerService.systemReady(); 15575 mPackageDexOptimizer.systemReady(); 15576 15577 MountServiceInternal mountServiceInternal = LocalServices.getService( 15578 MountServiceInternal.class); 15579 mountServiceInternal.addExternalStoragePolicy( 15580 new MountServiceInternal.ExternalStorageMountPolicy() { 15581 @Override 15582 public int getMountMode(int uid, String packageName) { 15583 if (Process.isIsolated(uid)) { 15584 return Zygote.MOUNT_EXTERNAL_NONE; 15585 } 15586 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 15587 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15588 } 15589 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15590 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15591 } 15592 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15593 return Zygote.MOUNT_EXTERNAL_READ; 15594 } 15595 return Zygote.MOUNT_EXTERNAL_WRITE; 15596 } 15597 15598 @Override 15599 public boolean hasExternalStorage(int uid, String packageName) { 15600 return true; 15601 } 15602 }); 15603 } 15604 15605 @Override 15606 public boolean isSafeMode() { 15607 return mSafeMode; 15608 } 15609 15610 @Override 15611 public boolean hasSystemUidErrors() { 15612 return mHasSystemUidErrors; 15613 } 15614 15615 static String arrayToString(int[] array) { 15616 StringBuffer buf = new StringBuffer(128); 15617 buf.append('['); 15618 if (array != null) { 15619 for (int i=0; i<array.length; i++) { 15620 if (i > 0) buf.append(", "); 15621 buf.append(array[i]); 15622 } 15623 } 15624 buf.append(']'); 15625 return buf.toString(); 15626 } 15627 15628 static class DumpState { 15629 public static final int DUMP_LIBS = 1 << 0; 15630 public static final int DUMP_FEATURES = 1 << 1; 15631 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 15632 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 15633 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 15634 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 15635 public static final int DUMP_PERMISSIONS = 1 << 6; 15636 public static final int DUMP_PACKAGES = 1 << 7; 15637 public static final int DUMP_SHARED_USERS = 1 << 8; 15638 public static final int DUMP_MESSAGES = 1 << 9; 15639 public static final int DUMP_PROVIDERS = 1 << 10; 15640 public static final int DUMP_VERIFIERS = 1 << 11; 15641 public static final int DUMP_PREFERRED = 1 << 12; 15642 public static final int DUMP_PREFERRED_XML = 1 << 13; 15643 public static final int DUMP_KEYSETS = 1 << 14; 15644 public static final int DUMP_VERSION = 1 << 15; 15645 public static final int DUMP_INSTALLS = 1 << 16; 15646 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 15647 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 15648 15649 public static final int OPTION_SHOW_FILTERS = 1 << 0; 15650 15651 private int mTypes; 15652 15653 private int mOptions; 15654 15655 private boolean mTitlePrinted; 15656 15657 private SharedUserSetting mSharedUser; 15658 15659 public boolean isDumping(int type) { 15660 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 15661 return true; 15662 } 15663 15664 return (mTypes & type) != 0; 15665 } 15666 15667 public void setDump(int type) { 15668 mTypes |= type; 15669 } 15670 15671 public boolean isOptionEnabled(int option) { 15672 return (mOptions & option) != 0; 15673 } 15674 15675 public void setOptionEnabled(int option) { 15676 mOptions |= option; 15677 } 15678 15679 public boolean onTitlePrinted() { 15680 final boolean printed = mTitlePrinted; 15681 mTitlePrinted = true; 15682 return printed; 15683 } 15684 15685 public boolean getTitlePrinted() { 15686 return mTitlePrinted; 15687 } 15688 15689 public void setTitlePrinted(boolean enabled) { 15690 mTitlePrinted = enabled; 15691 } 15692 15693 public SharedUserSetting getSharedUser() { 15694 return mSharedUser; 15695 } 15696 15697 public void setSharedUser(SharedUserSetting user) { 15698 mSharedUser = user; 15699 } 15700 } 15701 15702 @Override 15703 public void onShellCommand(FileDescriptor in, FileDescriptor out, 15704 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 15705 (new PackageManagerShellCommand(this)).exec( 15706 this, in, out, err, args, resultReceiver); 15707 } 15708 15709 @Override 15710 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 15711 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 15712 != PackageManager.PERMISSION_GRANTED) { 15713 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 15714 + Binder.getCallingPid() 15715 + ", uid=" + Binder.getCallingUid() 15716 + " without permission " 15717 + android.Manifest.permission.DUMP); 15718 return; 15719 } 15720 15721 DumpState dumpState = new DumpState(); 15722 boolean fullPreferred = false; 15723 boolean checkin = false; 15724 15725 String packageName = null; 15726 ArraySet<String> permissionNames = null; 15727 15728 int opti = 0; 15729 while (opti < args.length) { 15730 String opt = args[opti]; 15731 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 15732 break; 15733 } 15734 opti++; 15735 15736 if ("-a".equals(opt)) { 15737 // Right now we only know how to print all. 15738 } else if ("-h".equals(opt)) { 15739 pw.println("Package manager dump options:"); 15740 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 15741 pw.println(" --checkin: dump for a checkin"); 15742 pw.println(" -f: print details of intent filters"); 15743 pw.println(" -h: print this help"); 15744 pw.println(" cmd may be one of:"); 15745 pw.println(" l[ibraries]: list known shared libraries"); 15746 pw.println(" f[eatures]: list device features"); 15747 pw.println(" k[eysets]: print known keysets"); 15748 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 15749 pw.println(" perm[issions]: dump permissions"); 15750 pw.println(" permission [name ...]: dump declaration and use of given permission"); 15751 pw.println(" pref[erred]: print preferred package settings"); 15752 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 15753 pw.println(" prov[iders]: dump content providers"); 15754 pw.println(" p[ackages]: dump installed packages"); 15755 pw.println(" s[hared-users]: dump shared user IDs"); 15756 pw.println(" m[essages]: print collected runtime messages"); 15757 pw.println(" v[erifiers]: print package verifier info"); 15758 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 15759 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 15760 pw.println(" version: print database version info"); 15761 pw.println(" write: write current settings now"); 15762 pw.println(" installs: details about install sessions"); 15763 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 15764 pw.println(" <package.name>: info about given package"); 15765 return; 15766 } else if ("--checkin".equals(opt)) { 15767 checkin = true; 15768 } else if ("-f".equals(opt)) { 15769 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15770 } else { 15771 pw.println("Unknown argument: " + opt + "; use -h for help"); 15772 } 15773 } 15774 15775 // Is the caller requesting to dump a particular piece of data? 15776 if (opti < args.length) { 15777 String cmd = args[opti]; 15778 opti++; 15779 // Is this a package name? 15780 if ("android".equals(cmd) || cmd.contains(".")) { 15781 packageName = cmd; 15782 // When dumping a single package, we always dump all of its 15783 // filter information since the amount of data will be reasonable. 15784 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15785 } else if ("check-permission".equals(cmd)) { 15786 if (opti >= args.length) { 15787 pw.println("Error: check-permission missing permission argument"); 15788 return; 15789 } 15790 String perm = args[opti]; 15791 opti++; 15792 if (opti >= args.length) { 15793 pw.println("Error: check-permission missing package argument"); 15794 return; 15795 } 15796 String pkg = args[opti]; 15797 opti++; 15798 int user = UserHandle.getUserId(Binder.getCallingUid()); 15799 if (opti < args.length) { 15800 try { 15801 user = Integer.parseInt(args[opti]); 15802 } catch (NumberFormatException e) { 15803 pw.println("Error: check-permission user argument is not a number: " 15804 + args[opti]); 15805 return; 15806 } 15807 } 15808 pw.println(checkPermission(perm, pkg, user)); 15809 return; 15810 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 15811 dumpState.setDump(DumpState.DUMP_LIBS); 15812 } else if ("f".equals(cmd) || "features".equals(cmd)) { 15813 dumpState.setDump(DumpState.DUMP_FEATURES); 15814 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 15815 if (opti >= args.length) { 15816 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 15817 | DumpState.DUMP_SERVICE_RESOLVERS 15818 | DumpState.DUMP_RECEIVER_RESOLVERS 15819 | DumpState.DUMP_CONTENT_RESOLVERS); 15820 } else { 15821 while (opti < args.length) { 15822 String name = args[opti]; 15823 if ("a".equals(name) || "activity".equals(name)) { 15824 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 15825 } else if ("s".equals(name) || "service".equals(name)) { 15826 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 15827 } else if ("r".equals(name) || "receiver".equals(name)) { 15828 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 15829 } else if ("c".equals(name) || "content".equals(name)) { 15830 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 15831 } else { 15832 pw.println("Error: unknown resolver table type: " + name); 15833 return; 15834 } 15835 opti++; 15836 } 15837 } 15838 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 15839 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 15840 } else if ("permission".equals(cmd)) { 15841 if (opti >= args.length) { 15842 pw.println("Error: permission requires permission name"); 15843 return; 15844 } 15845 permissionNames = new ArraySet<>(); 15846 while (opti < args.length) { 15847 permissionNames.add(args[opti]); 15848 opti++; 15849 } 15850 dumpState.setDump(DumpState.DUMP_PERMISSIONS 15851 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 15852 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 15853 dumpState.setDump(DumpState.DUMP_PREFERRED); 15854 } else if ("preferred-xml".equals(cmd)) { 15855 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 15856 if (opti < args.length && "--full".equals(args[opti])) { 15857 fullPreferred = true; 15858 opti++; 15859 } 15860 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 15861 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 15862 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 15863 dumpState.setDump(DumpState.DUMP_PACKAGES); 15864 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 15865 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 15866 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 15867 dumpState.setDump(DumpState.DUMP_PROVIDERS); 15868 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 15869 dumpState.setDump(DumpState.DUMP_MESSAGES); 15870 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 15871 dumpState.setDump(DumpState.DUMP_VERIFIERS); 15872 } else if ("i".equals(cmd) || "ifv".equals(cmd) 15873 || "intent-filter-verifiers".equals(cmd)) { 15874 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 15875 } else if ("version".equals(cmd)) { 15876 dumpState.setDump(DumpState.DUMP_VERSION); 15877 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 15878 dumpState.setDump(DumpState.DUMP_KEYSETS); 15879 } else if ("installs".equals(cmd)) { 15880 dumpState.setDump(DumpState.DUMP_INSTALLS); 15881 } else if ("write".equals(cmd)) { 15882 synchronized (mPackages) { 15883 mSettings.writeLPr(); 15884 pw.println("Settings written."); 15885 return; 15886 } 15887 } 15888 } 15889 15890 if (checkin) { 15891 pw.println("vers,1"); 15892 } 15893 15894 // reader 15895 synchronized (mPackages) { 15896 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 15897 if (!checkin) { 15898 if (dumpState.onTitlePrinted()) 15899 pw.println(); 15900 pw.println("Database versions:"); 15901 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 15902 } 15903 } 15904 15905 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 15906 if (!checkin) { 15907 if (dumpState.onTitlePrinted()) 15908 pw.println(); 15909 pw.println("Verifiers:"); 15910 pw.print(" Required: "); 15911 pw.print(mRequiredVerifierPackage); 15912 pw.print(" (uid="); 15913 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 15914 UserHandle.USER_SYSTEM)); 15915 pw.println(")"); 15916 } else if (mRequiredVerifierPackage != null) { 15917 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 15918 pw.print(","); 15919 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 15920 UserHandle.USER_SYSTEM)); 15921 } 15922 } 15923 15924 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 15925 packageName == null) { 15926 if (mIntentFilterVerifierComponent != null) { 15927 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 15928 if (!checkin) { 15929 if (dumpState.onTitlePrinted()) 15930 pw.println(); 15931 pw.println("Intent Filter Verifier:"); 15932 pw.print(" Using: "); 15933 pw.print(verifierPackageName); 15934 pw.print(" (uid="); 15935 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 15936 UserHandle.USER_SYSTEM)); 15937 pw.println(")"); 15938 } else if (verifierPackageName != null) { 15939 pw.print("ifv,"); pw.print(verifierPackageName); 15940 pw.print(","); 15941 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 15942 UserHandle.USER_SYSTEM)); 15943 } 15944 } else { 15945 pw.println(); 15946 pw.println("No Intent Filter Verifier available!"); 15947 } 15948 } 15949 15950 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 15951 boolean printedHeader = false; 15952 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 15953 while (it.hasNext()) { 15954 String name = it.next(); 15955 SharedLibraryEntry ent = mSharedLibraries.get(name); 15956 if (!checkin) { 15957 if (!printedHeader) { 15958 if (dumpState.onTitlePrinted()) 15959 pw.println(); 15960 pw.println("Libraries:"); 15961 printedHeader = true; 15962 } 15963 pw.print(" "); 15964 } else { 15965 pw.print("lib,"); 15966 } 15967 pw.print(name); 15968 if (!checkin) { 15969 pw.print(" -> "); 15970 } 15971 if (ent.path != null) { 15972 if (!checkin) { 15973 pw.print("(jar) "); 15974 pw.print(ent.path); 15975 } else { 15976 pw.print(",jar,"); 15977 pw.print(ent.path); 15978 } 15979 } else { 15980 if (!checkin) { 15981 pw.print("(apk) "); 15982 pw.print(ent.apk); 15983 } else { 15984 pw.print(",apk,"); 15985 pw.print(ent.apk); 15986 } 15987 } 15988 pw.println(); 15989 } 15990 } 15991 15992 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 15993 if (dumpState.onTitlePrinted()) 15994 pw.println(); 15995 if (!checkin) { 15996 pw.println("Features:"); 15997 } 15998 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 15999 while (it.hasNext()) { 16000 String name = it.next(); 16001 if (!checkin) { 16002 pw.print(" "); 16003 } else { 16004 pw.print("feat,"); 16005 } 16006 pw.println(name); 16007 } 16008 } 16009 16010 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 16011 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 16012 : "Activity Resolver Table:", " ", packageName, 16013 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16014 dumpState.setTitlePrinted(true); 16015 } 16016 } 16017 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 16018 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 16019 : "Receiver Resolver Table:", " ", packageName, 16020 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16021 dumpState.setTitlePrinted(true); 16022 } 16023 } 16024 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 16025 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 16026 : "Service Resolver Table:", " ", packageName, 16027 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16028 dumpState.setTitlePrinted(true); 16029 } 16030 } 16031 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 16032 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 16033 : "Provider Resolver Table:", " ", packageName, 16034 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16035 dumpState.setTitlePrinted(true); 16036 } 16037 } 16038 16039 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 16040 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16041 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16042 int user = mSettings.mPreferredActivities.keyAt(i); 16043 if (pir.dump(pw, 16044 dumpState.getTitlePrinted() 16045 ? "\nPreferred Activities User " + user + ":" 16046 : "Preferred Activities User " + user + ":", " ", 16047 packageName, true, false)) { 16048 dumpState.setTitlePrinted(true); 16049 } 16050 } 16051 } 16052 16053 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 16054 pw.flush(); 16055 FileOutputStream fout = new FileOutputStream(fd); 16056 BufferedOutputStream str = new BufferedOutputStream(fout); 16057 XmlSerializer serializer = new FastXmlSerializer(); 16058 try { 16059 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 16060 serializer.startDocument(null, true); 16061 serializer.setFeature( 16062 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 16063 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 16064 serializer.endDocument(); 16065 serializer.flush(); 16066 } catch (IllegalArgumentException e) { 16067 pw.println("Failed writing: " + e); 16068 } catch (IllegalStateException e) { 16069 pw.println("Failed writing: " + e); 16070 } catch (IOException e) { 16071 pw.println("Failed writing: " + e); 16072 } 16073 } 16074 16075 if (!checkin 16076 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 16077 && packageName == null) { 16078 pw.println(); 16079 int count = mSettings.mPackages.size(); 16080 if (count == 0) { 16081 pw.println("No applications!"); 16082 pw.println(); 16083 } else { 16084 final String prefix = " "; 16085 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 16086 if (allPackageSettings.size() == 0) { 16087 pw.println("No domain preferred apps!"); 16088 pw.println(); 16089 } else { 16090 pw.println("App verification status:"); 16091 pw.println(); 16092 count = 0; 16093 for (PackageSetting ps : allPackageSettings) { 16094 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 16095 if (ivi == null || ivi.getPackageName() == null) continue; 16096 pw.println(prefix + "Package: " + ivi.getPackageName()); 16097 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 16098 pw.println(prefix + "Status: " + ivi.getStatusString()); 16099 pw.println(); 16100 count++; 16101 } 16102 if (count == 0) { 16103 pw.println(prefix + "No app verification established."); 16104 pw.println(); 16105 } 16106 for (int userId : sUserManager.getUserIds()) { 16107 pw.println("App linkages for user " + userId + ":"); 16108 pw.println(); 16109 count = 0; 16110 for (PackageSetting ps : allPackageSettings) { 16111 final long status = ps.getDomainVerificationStatusForUser(userId); 16112 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 16113 continue; 16114 } 16115 pw.println(prefix + "Package: " + ps.name); 16116 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 16117 String statusStr = IntentFilterVerificationInfo. 16118 getStatusStringFromValue(status); 16119 pw.println(prefix + "Status: " + statusStr); 16120 pw.println(); 16121 count++; 16122 } 16123 if (count == 0) { 16124 pw.println(prefix + "No configured app linkages."); 16125 pw.println(); 16126 } 16127 } 16128 } 16129 } 16130 } 16131 16132 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 16133 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 16134 if (packageName == null && permissionNames == null) { 16135 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 16136 if (iperm == 0) { 16137 if (dumpState.onTitlePrinted()) 16138 pw.println(); 16139 pw.println("AppOp Permissions:"); 16140 } 16141 pw.print(" AppOp Permission "); 16142 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 16143 pw.println(":"); 16144 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 16145 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 16146 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 16147 } 16148 } 16149 } 16150 } 16151 16152 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 16153 boolean printedSomething = false; 16154 for (PackageParser.Provider p : mProviders.mProviders.values()) { 16155 if (packageName != null && !packageName.equals(p.info.packageName)) { 16156 continue; 16157 } 16158 if (!printedSomething) { 16159 if (dumpState.onTitlePrinted()) 16160 pw.println(); 16161 pw.println("Registered ContentProviders:"); 16162 printedSomething = true; 16163 } 16164 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 16165 pw.print(" "); pw.println(p.toString()); 16166 } 16167 printedSomething = false; 16168 for (Map.Entry<String, PackageParser.Provider> entry : 16169 mProvidersByAuthority.entrySet()) { 16170 PackageParser.Provider p = entry.getValue(); 16171 if (packageName != null && !packageName.equals(p.info.packageName)) { 16172 continue; 16173 } 16174 if (!printedSomething) { 16175 if (dumpState.onTitlePrinted()) 16176 pw.println(); 16177 pw.println("ContentProvider Authorities:"); 16178 printedSomething = true; 16179 } 16180 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 16181 pw.print(" "); pw.println(p.toString()); 16182 if (p.info != null && p.info.applicationInfo != null) { 16183 final String appInfo = p.info.applicationInfo.toString(); 16184 pw.print(" applicationInfo="); pw.println(appInfo); 16185 } 16186 } 16187 } 16188 16189 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 16190 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 16191 } 16192 16193 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 16194 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 16195 } 16196 16197 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 16198 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 16199 } 16200 16201 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 16202 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 16203 } 16204 16205 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 16206 // XXX should handle packageName != null by dumping only install data that 16207 // the given package is involved with. 16208 if (dumpState.onTitlePrinted()) pw.println(); 16209 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 16210 } 16211 16212 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 16213 if (dumpState.onTitlePrinted()) pw.println(); 16214 mSettings.dumpReadMessagesLPr(pw, dumpState); 16215 16216 pw.println(); 16217 pw.println("Package warning messages:"); 16218 BufferedReader in = null; 16219 String line = null; 16220 try { 16221 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 16222 while ((line = in.readLine()) != null) { 16223 if (line.contains("ignored: updated version")) continue; 16224 pw.println(line); 16225 } 16226 } catch (IOException ignored) { 16227 } finally { 16228 IoUtils.closeQuietly(in); 16229 } 16230 } 16231 16232 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 16233 BufferedReader in = null; 16234 String line = null; 16235 try { 16236 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 16237 while ((line = in.readLine()) != null) { 16238 if (line.contains("ignored: updated version")) continue; 16239 pw.print("msg,"); 16240 pw.println(line); 16241 } 16242 } catch (IOException ignored) { 16243 } finally { 16244 IoUtils.closeQuietly(in); 16245 } 16246 } 16247 } 16248 } 16249 16250 private String dumpDomainString(String packageName) { 16251 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 16252 List<IntentFilter> filters = getAllIntentFilters(packageName); 16253 16254 ArraySet<String> result = new ArraySet<>(); 16255 if (iviList.size() > 0) { 16256 for (IntentFilterVerificationInfo ivi : iviList) { 16257 for (String host : ivi.getDomains()) { 16258 result.add(host); 16259 } 16260 } 16261 } 16262 if (filters != null && filters.size() > 0) { 16263 for (IntentFilter filter : filters) { 16264 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 16265 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 16266 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 16267 result.addAll(filter.getHostsList()); 16268 } 16269 } 16270 } 16271 16272 StringBuilder sb = new StringBuilder(result.size() * 16); 16273 for (String domain : result) { 16274 if (sb.length() > 0) sb.append(" "); 16275 sb.append(domain); 16276 } 16277 return sb.toString(); 16278 } 16279 16280 // ------- apps on sdcard specific code ------- 16281 static final boolean DEBUG_SD_INSTALL = false; 16282 16283 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 16284 16285 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 16286 16287 private boolean mMediaMounted = false; 16288 16289 static String getEncryptKey() { 16290 try { 16291 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 16292 SD_ENCRYPTION_KEYSTORE_NAME); 16293 if (sdEncKey == null) { 16294 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 16295 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 16296 if (sdEncKey == null) { 16297 Slog.e(TAG, "Failed to create encryption keys"); 16298 return null; 16299 } 16300 } 16301 return sdEncKey; 16302 } catch (NoSuchAlgorithmException nsae) { 16303 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 16304 return null; 16305 } catch (IOException ioe) { 16306 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 16307 return null; 16308 } 16309 } 16310 16311 /* 16312 * Update media status on PackageManager. 16313 */ 16314 @Override 16315 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 16316 int callingUid = Binder.getCallingUid(); 16317 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 16318 throw new SecurityException("Media status can only be updated by the system"); 16319 } 16320 // reader; this apparently protects mMediaMounted, but should probably 16321 // be a different lock in that case. 16322 synchronized (mPackages) { 16323 Log.i(TAG, "Updating external media status from " 16324 + (mMediaMounted ? "mounted" : "unmounted") + " to " 16325 + (mediaStatus ? "mounted" : "unmounted")); 16326 if (DEBUG_SD_INSTALL) 16327 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 16328 + ", mMediaMounted=" + mMediaMounted); 16329 if (mediaStatus == mMediaMounted) { 16330 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 16331 : 0, -1); 16332 mHandler.sendMessage(msg); 16333 return; 16334 } 16335 mMediaMounted = mediaStatus; 16336 } 16337 // Queue up an async operation since the package installation may take a 16338 // little while. 16339 mHandler.post(new Runnable() { 16340 public void run() { 16341 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 16342 } 16343 }); 16344 } 16345 16346 /** 16347 * Called by MountService when the initial ASECs to scan are available. 16348 * Should block until all the ASEC containers are finished being scanned. 16349 */ 16350 public void scanAvailableAsecs() { 16351 updateExternalMediaStatusInner(true, false, false); 16352 } 16353 16354 /* 16355 * Collect information of applications on external media, map them against 16356 * existing containers and update information based on current mount status. 16357 * Please note that we always have to report status if reportStatus has been 16358 * set to true especially when unloading packages. 16359 */ 16360 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 16361 boolean externalStorage) { 16362 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 16363 int[] uidArr = EmptyArray.INT; 16364 16365 final String[] list = PackageHelper.getSecureContainerList(); 16366 if (ArrayUtils.isEmpty(list)) { 16367 Log.i(TAG, "No secure containers found"); 16368 } else { 16369 // Process list of secure containers and categorize them 16370 // as active or stale based on their package internal state. 16371 16372 // reader 16373 synchronized (mPackages) { 16374 for (String cid : list) { 16375 // Leave stages untouched for now; installer service owns them 16376 if (PackageInstallerService.isStageName(cid)) continue; 16377 16378 if (DEBUG_SD_INSTALL) 16379 Log.i(TAG, "Processing container " + cid); 16380 String pkgName = getAsecPackageName(cid); 16381 if (pkgName == null) { 16382 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 16383 continue; 16384 } 16385 if (DEBUG_SD_INSTALL) 16386 Log.i(TAG, "Looking for pkg : " + pkgName); 16387 16388 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16389 if (ps == null) { 16390 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 16391 continue; 16392 } 16393 16394 /* 16395 * Skip packages that are not external if we're unmounting 16396 * external storage. 16397 */ 16398 if (externalStorage && !isMounted && !isExternal(ps)) { 16399 continue; 16400 } 16401 16402 final AsecInstallArgs args = new AsecInstallArgs(cid, 16403 getAppDexInstructionSets(ps), ps.isForwardLocked()); 16404 // The package status is changed only if the code path 16405 // matches between settings and the container id. 16406 if (ps.codePathString != null 16407 && ps.codePathString.startsWith(args.getCodePath())) { 16408 if (DEBUG_SD_INSTALL) { 16409 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 16410 + " at code path: " + ps.codePathString); 16411 } 16412 16413 // We do have a valid package installed on sdcard 16414 processCids.put(args, ps.codePathString); 16415 final int uid = ps.appId; 16416 if (uid != -1) { 16417 uidArr = ArrayUtils.appendInt(uidArr, uid); 16418 } 16419 } else { 16420 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 16421 + ps.codePathString); 16422 } 16423 } 16424 } 16425 16426 Arrays.sort(uidArr); 16427 } 16428 16429 // Process packages with valid entries. 16430 if (isMounted) { 16431 if (DEBUG_SD_INSTALL) 16432 Log.i(TAG, "Loading packages"); 16433 loadMediaPackages(processCids, uidArr, externalStorage); 16434 startCleaningPackages(); 16435 mInstallerService.onSecureContainersAvailable(); 16436 } else { 16437 if (DEBUG_SD_INSTALL) 16438 Log.i(TAG, "Unloading packages"); 16439 unloadMediaPackages(processCids, uidArr, reportStatus); 16440 } 16441 } 16442 16443 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16444 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 16445 final int size = infos.size(); 16446 final String[] packageNames = new String[size]; 16447 final int[] packageUids = new int[size]; 16448 for (int i = 0; i < size; i++) { 16449 final ApplicationInfo info = infos.get(i); 16450 packageNames[i] = info.packageName; 16451 packageUids[i] = info.uid; 16452 } 16453 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 16454 finishedReceiver); 16455 } 16456 16457 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16458 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 16459 sendResourcesChangedBroadcast(mediaStatus, replacing, 16460 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 16461 } 16462 16463 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16464 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 16465 int size = pkgList.length; 16466 if (size > 0) { 16467 // Send broadcasts here 16468 Bundle extras = new Bundle(); 16469 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 16470 if (uidArr != null) { 16471 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 16472 } 16473 if (replacing) { 16474 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 16475 } 16476 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 16477 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 16478 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 16479 } 16480 } 16481 16482 /* 16483 * Look at potentially valid container ids from processCids If package 16484 * information doesn't match the one on record or package scanning fails, 16485 * the cid is added to list of removeCids. We currently don't delete stale 16486 * containers. 16487 */ 16488 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 16489 boolean externalStorage) { 16490 ArrayList<String> pkgList = new ArrayList<String>(); 16491 Set<AsecInstallArgs> keys = processCids.keySet(); 16492 16493 for (AsecInstallArgs args : keys) { 16494 String codePath = processCids.get(args); 16495 if (DEBUG_SD_INSTALL) 16496 Log.i(TAG, "Loading container : " + args.cid); 16497 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 16498 try { 16499 // Make sure there are no container errors first. 16500 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 16501 Slog.e(TAG, "Failed to mount cid : " + args.cid 16502 + " when installing from sdcard"); 16503 continue; 16504 } 16505 // Check code path here. 16506 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 16507 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 16508 + " does not match one in settings " + codePath); 16509 continue; 16510 } 16511 // Parse package 16512 int parseFlags = mDefParseFlags; 16513 if (args.isExternalAsec()) { 16514 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 16515 } 16516 if (args.isFwdLocked()) { 16517 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 16518 } 16519 16520 synchronized (mInstallLock) { 16521 PackageParser.Package pkg = null; 16522 try { 16523 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 16524 } catch (PackageManagerException e) { 16525 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 16526 } 16527 // Scan the package 16528 if (pkg != null) { 16529 /* 16530 * TODO why is the lock being held? doPostInstall is 16531 * called in other places without the lock. This needs 16532 * to be straightened out. 16533 */ 16534 // writer 16535 synchronized (mPackages) { 16536 retCode = PackageManager.INSTALL_SUCCEEDED; 16537 pkgList.add(pkg.packageName); 16538 // Post process args 16539 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 16540 pkg.applicationInfo.uid); 16541 } 16542 } else { 16543 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 16544 } 16545 } 16546 16547 } finally { 16548 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 16549 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 16550 } 16551 } 16552 } 16553 // writer 16554 synchronized (mPackages) { 16555 // If the platform SDK has changed since the last time we booted, 16556 // we need to re-grant app permission to catch any new ones that 16557 // appear. This is really a hack, and means that apps can in some 16558 // cases get permissions that the user didn't initially explicitly 16559 // allow... it would be nice to have some better way to handle 16560 // this situation. 16561 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 16562 : mSettings.getInternalVersion(); 16563 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 16564 : StorageManager.UUID_PRIVATE_INTERNAL; 16565 16566 int updateFlags = UPDATE_PERMISSIONS_ALL; 16567 if (ver.sdkVersion != mSdkVersion) { 16568 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16569 + mSdkVersion + "; regranting permissions for external"); 16570 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16571 } 16572 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 16573 16574 // Yay, everything is now upgraded 16575 ver.forceCurrent(); 16576 16577 // can downgrade to reader 16578 // Persist settings 16579 mSettings.writeLPr(); 16580 } 16581 // Send a broadcast to let everyone know we are done processing 16582 if (pkgList.size() > 0) { 16583 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 16584 } 16585 } 16586 16587 /* 16588 * Utility method to unload a list of specified containers 16589 */ 16590 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 16591 // Just unmount all valid containers. 16592 for (AsecInstallArgs arg : cidArgs) { 16593 synchronized (mInstallLock) { 16594 arg.doPostDeleteLI(false); 16595 } 16596 } 16597 } 16598 16599 /* 16600 * Unload packages mounted on external media. This involves deleting package 16601 * data from internal structures, sending broadcasts about diabled packages, 16602 * gc'ing to free up references, unmounting all secure containers 16603 * corresponding to packages on external media, and posting a 16604 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 16605 * that we always have to post this message if status has been requested no 16606 * matter what. 16607 */ 16608 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 16609 final boolean reportStatus) { 16610 if (DEBUG_SD_INSTALL) 16611 Log.i(TAG, "unloading media packages"); 16612 ArrayList<String> pkgList = new ArrayList<String>(); 16613 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 16614 final Set<AsecInstallArgs> keys = processCids.keySet(); 16615 for (AsecInstallArgs args : keys) { 16616 String pkgName = args.getPackageName(); 16617 if (DEBUG_SD_INSTALL) 16618 Log.i(TAG, "Trying to unload pkg : " + pkgName); 16619 // Delete package internally 16620 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16621 synchronized (mInstallLock) { 16622 boolean res = deletePackageLI(pkgName, null, false, null, null, 16623 PackageManager.DELETE_KEEP_DATA, outInfo, false); 16624 if (res) { 16625 pkgList.add(pkgName); 16626 } else { 16627 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 16628 failedList.add(args); 16629 } 16630 } 16631 } 16632 16633 // reader 16634 synchronized (mPackages) { 16635 // We didn't update the settings after removing each package; 16636 // write them now for all packages. 16637 mSettings.writeLPr(); 16638 } 16639 16640 // We have to absolutely send UPDATED_MEDIA_STATUS only 16641 // after confirming that all the receivers processed the ordered 16642 // broadcast when packages get disabled, force a gc to clean things up. 16643 // and unload all the containers. 16644 if (pkgList.size() > 0) { 16645 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 16646 new IIntentReceiver.Stub() { 16647 public void performReceive(Intent intent, int resultCode, String data, 16648 Bundle extras, boolean ordered, boolean sticky, 16649 int sendingUser) throws RemoteException { 16650 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 16651 reportStatus ? 1 : 0, 1, keys); 16652 mHandler.sendMessage(msg); 16653 } 16654 }); 16655 } else { 16656 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 16657 keys); 16658 mHandler.sendMessage(msg); 16659 } 16660 } 16661 16662 private void loadPrivatePackages(final VolumeInfo vol) { 16663 mHandler.post(new Runnable() { 16664 @Override 16665 public void run() { 16666 loadPrivatePackagesInner(vol); 16667 } 16668 }); 16669 } 16670 16671 private void loadPrivatePackagesInner(VolumeInfo vol) { 16672 final String volumeUuid = vol.fsUuid; 16673 if (TextUtils.isEmpty(volumeUuid)) { 16674 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 16675 return; 16676 } 16677 16678 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 16679 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 16680 16681 final VersionInfo ver; 16682 final List<PackageSetting> packages; 16683 synchronized (mPackages) { 16684 ver = mSettings.findOrCreateVersion(volumeUuid); 16685 packages = mSettings.getVolumePackagesLPr(volumeUuid); 16686 } 16687 16688 // TODO: introduce a new concept similar to "frozen" to prevent these 16689 // apps from being launched until after data has been fully reconciled 16690 for (PackageSetting ps : packages) { 16691 synchronized (mInstallLock) { 16692 final PackageParser.Package pkg; 16693 try { 16694 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 16695 loaded.add(pkg.applicationInfo); 16696 16697 } catch (PackageManagerException e) { 16698 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 16699 } 16700 16701 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 16702 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 16703 } 16704 } 16705 } 16706 16707 // Reconcile app data for all started/unlocked users 16708 final UserManager um = mContext.getSystemService(UserManager.class); 16709 for (UserInfo user : um.getUsers()) { 16710 if (um.isUserUnlocked(user.id)) { 16711 reconcileAppsData(volumeUuid, user.id, 16712 Installer.FLAG_DE_STORAGE | Installer.FLAG_CE_STORAGE); 16713 } else if (um.isUserRunning(user.id)) { 16714 reconcileAppsData(volumeUuid, user.id, Installer.FLAG_DE_STORAGE); 16715 } else { 16716 continue; 16717 } 16718 } 16719 16720 synchronized (mPackages) { 16721 int updateFlags = UPDATE_PERMISSIONS_ALL; 16722 if (ver.sdkVersion != mSdkVersion) { 16723 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16724 + mSdkVersion + "; regranting permissions for " + volumeUuid); 16725 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16726 } 16727 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 16728 16729 // Yay, everything is now upgraded 16730 ver.forceCurrent(); 16731 16732 mSettings.writeLPr(); 16733 } 16734 16735 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 16736 sendResourcesChangedBroadcast(true, false, loaded, null); 16737 } 16738 16739 private void unloadPrivatePackages(final VolumeInfo vol) { 16740 mHandler.post(new Runnable() { 16741 @Override 16742 public void run() { 16743 unloadPrivatePackagesInner(vol); 16744 } 16745 }); 16746 } 16747 16748 private void unloadPrivatePackagesInner(VolumeInfo vol) { 16749 final String volumeUuid = vol.fsUuid; 16750 if (TextUtils.isEmpty(volumeUuid)) { 16751 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 16752 return; 16753 } 16754 16755 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 16756 synchronized (mInstallLock) { 16757 synchronized (mPackages) { 16758 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 16759 for (PackageSetting ps : packages) { 16760 if (ps.pkg == null) continue; 16761 16762 final ApplicationInfo info = ps.pkg.applicationInfo; 16763 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16764 if (deletePackageLI(ps.name, null, false, null, null, 16765 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 16766 unloaded.add(info); 16767 } else { 16768 Slog.w(TAG, "Failed to unload " + ps.codePath); 16769 } 16770 } 16771 16772 mSettings.writeLPr(); 16773 } 16774 } 16775 16776 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 16777 sendResourcesChangedBroadcast(false, false, unloaded, null); 16778 } 16779 16780 /** 16781 * Examine all users present on given mounted volume, and destroy data 16782 * belonging to users that are no longer valid, or whose user ID has been 16783 * recycled. 16784 */ 16785 private void reconcileUsers(String volumeUuid) { 16786 final File[] files = FileUtils 16787 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 16788 for (File file : files) { 16789 if (!file.isDirectory()) continue; 16790 16791 final int userId; 16792 final UserInfo info; 16793 try { 16794 userId = Integer.parseInt(file.getName()); 16795 info = sUserManager.getUserInfo(userId); 16796 } catch (NumberFormatException e) { 16797 Slog.w(TAG, "Invalid user directory " + file); 16798 continue; 16799 } 16800 16801 boolean destroyUser = false; 16802 if (info == null) { 16803 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16804 + " because no matching user was found"); 16805 destroyUser = true; 16806 } else { 16807 try { 16808 UserManagerService.enforceSerialNumber(file, info.serialNumber); 16809 } catch (IOException e) { 16810 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16811 + " because we failed to enforce serial number: " + e); 16812 destroyUser = true; 16813 } 16814 } 16815 16816 if (destroyUser) { 16817 synchronized (mInstallLock) { 16818 try { 16819 mInstaller.removeUserDataDirs(volumeUuid, userId); 16820 } catch (InstallerException e) { 16821 Slog.w(TAG, "Failed to clean up user dirs", e); 16822 } 16823 } 16824 } 16825 } 16826 16827 final StorageManager sm = mContext.getSystemService(StorageManager.class); 16828 final UserManager um = mContext.getSystemService(UserManager.class); 16829 for (UserInfo user : um.getUsers()) { 16830 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 16831 if (userDir.exists()) continue; 16832 16833 try { 16834 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, user.isEphemeral()); 16835 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 16836 } catch (IOException e) { 16837 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 16838 } 16839 } 16840 } 16841 16842 private void assertPackageKnown(String volumeUuid, String packageName) 16843 throws PackageManagerException { 16844 synchronized (mPackages) { 16845 final PackageSetting ps = mSettings.mPackages.get(packageName); 16846 if (ps == null) { 16847 throw new PackageManagerException("Package " + packageName + " is unknown"); 16848 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 16849 throw new PackageManagerException( 16850 "Package " + packageName + " found on unknown volume " + volumeUuid 16851 + "; expected volume " + ps.volumeUuid); 16852 } 16853 } 16854 } 16855 16856 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 16857 throws PackageManagerException { 16858 synchronized (mPackages) { 16859 final PackageSetting ps = mSettings.mPackages.get(packageName); 16860 if (ps == null) { 16861 throw new PackageManagerException("Package " + packageName + " is unknown"); 16862 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 16863 throw new PackageManagerException( 16864 "Package " + packageName + " found on unknown volume " + volumeUuid 16865 + "; expected volume " + ps.volumeUuid); 16866 } else if (!ps.getInstalled(userId)) { 16867 throw new PackageManagerException( 16868 "Package " + packageName + " not installed for user " + userId); 16869 } 16870 } 16871 } 16872 16873 /** 16874 * Examine all apps present on given mounted volume, and destroy apps that 16875 * aren't expected, either due to uninstallation or reinstallation on 16876 * another volume. 16877 */ 16878 private void reconcileApps(String volumeUuid) { 16879 final File[] files = FileUtils 16880 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 16881 for (File file : files) { 16882 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 16883 && !PackageInstallerService.isStageName(file.getName()); 16884 if (!isPackage) { 16885 // Ignore entries which are not packages 16886 continue; 16887 } 16888 16889 try { 16890 final PackageLite pkg = PackageParser.parsePackageLite(file, 16891 PackageParser.PARSE_MUST_BE_APK); 16892 assertPackageKnown(volumeUuid, pkg.packageName); 16893 16894 } catch (PackageParserException | PackageManagerException e) { 16895 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 16896 synchronized (mInstallLock) { 16897 removeCodePathLI(file); 16898 } 16899 } 16900 } 16901 } 16902 16903 /** 16904 * Reconcile all app data for the given user. 16905 * <p> 16906 * Verifies that directories exist and that ownership and labeling is 16907 * correct for all installed apps on all mounted volumes. 16908 */ 16909 void reconcileAppsData(int userId, @StorageFlags int flags) { 16910 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16911 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16912 final String volumeUuid = vol.getFsUuid(); 16913 reconcileAppsData(volumeUuid, userId, flags); 16914 } 16915 } 16916 16917 /** 16918 * Reconcile all app data on given mounted volume. 16919 * <p> 16920 * Destroys app data that isn't expected, either due to uninstallation or 16921 * reinstallation on another volume. 16922 * <p> 16923 * Verifies that directories exist and that ownership and labeling is 16924 * correct for all installed apps. 16925 */ 16926 private void reconcileAppsData(String volumeUuid, int userId, @StorageFlags int flags) { 16927 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 16928 + Integer.toHexString(flags)); 16929 16930 final File ceDir = Environment.getDataUserCredentialEncryptedDirectory(volumeUuid, userId); 16931 final File deDir = Environment.getDataUserDeviceEncryptedDirectory(volumeUuid, userId); 16932 16933 boolean restoreconNeeded = false; 16934 16935 // First look for stale data that doesn't belong, and check if things 16936 // have changed since we did our last restorecon 16937 if ((flags & Installer.FLAG_CE_STORAGE) != 0) { 16938 if (!isUserKeyUnlocked(userId)) { 16939 throw new RuntimeException( 16940 "Yikes, someone asked us to reconcile CE storage while " + userId 16941 + " was still locked; this would have caused massive data loss!"); 16942 } 16943 16944 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 16945 16946 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 16947 for (File file : files) { 16948 final String packageName = file.getName(); 16949 try { 16950 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 16951 } catch (PackageManagerException e) { 16952 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 16953 synchronized (mInstallLock) { 16954 destroyAppDataLI(volumeUuid, packageName, userId, 16955 Installer.FLAG_CE_STORAGE); 16956 } 16957 } 16958 } 16959 } 16960 if ((flags & Installer.FLAG_DE_STORAGE) != 0) { 16961 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 16962 16963 final File[] files = FileUtils.listFilesOrEmpty(deDir); 16964 for (File file : files) { 16965 final String packageName = file.getName(); 16966 try { 16967 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 16968 } catch (PackageManagerException e) { 16969 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 16970 synchronized (mInstallLock) { 16971 destroyAppDataLI(volumeUuid, packageName, userId, 16972 Installer.FLAG_DE_STORAGE); 16973 } 16974 } 16975 } 16976 } 16977 16978 // Ensure that data directories are ready to roll for all packages 16979 // installed for this volume and user 16980 final List<PackageSetting> packages; 16981 synchronized (mPackages) { 16982 packages = mSettings.getVolumePackagesLPr(volumeUuid); 16983 } 16984 int preparedCount = 0; 16985 for (PackageSetting ps : packages) { 16986 final String packageName = ps.name; 16987 if (ps.pkg == null) { 16988 Slog.w(TAG, "Odd, missing scanned package " + packageName); 16989 // TODO: might be due to legacy ASEC apps; we should circle back 16990 // and reconcile again once they're scanned 16991 continue; 16992 } 16993 16994 if (ps.getInstalled(userId)) { 16995 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 16996 preparedCount++; 16997 } 16998 } 16999 17000 if (restoreconNeeded) { 17001 if ((flags & Installer.FLAG_CE_STORAGE) != 0) { 17002 SELinuxMMAC.setRestoreconDone(ceDir); 17003 } 17004 if ((flags & Installer.FLAG_DE_STORAGE) != 0) { 17005 SELinuxMMAC.setRestoreconDone(deDir); 17006 } 17007 } 17008 17009 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 17010 + " packages; restoreconNeeded was " + restoreconNeeded); 17011 } 17012 17013 /** 17014 * Prepare app data for the given app just after it was installed or 17015 * upgraded. This method carefully only touches users that it's installed 17016 * for, and it forces a restorecon to handle any seinfo changes. 17017 * <p> 17018 * Verifies that directories exist and that ownership and labeling is 17019 * correct for all installed apps. If there is an ownership mismatch, it 17020 * will try recovering system apps by wiping data; third-party app data is 17021 * left intact. 17022 */ 17023 private void prepareAppDataAfterInstall(PackageParser.Package pkg) { 17024 final PackageSetting ps; 17025 synchronized (mPackages) { 17026 ps = mSettings.mPackages.get(pkg.packageName); 17027 } 17028 17029 final UserManager um = mContext.getSystemService(UserManager.class); 17030 for (UserInfo user : um.getUsers()) { 17031 final int flags; 17032 if (um.isUserUnlocked(user.id)) { 17033 flags = Installer.FLAG_DE_STORAGE | Installer.FLAG_CE_STORAGE; 17034 } else if (um.isUserRunning(user.id)) { 17035 flags = Installer.FLAG_DE_STORAGE; 17036 } else { 17037 continue; 17038 } 17039 17040 if (ps.getInstalled(user.id)) { 17041 // Whenever an app changes, force a restorecon of its data 17042 // TODO: when user data is locked, mark that we're still dirty 17043 prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true); 17044 } 17045 } 17046 } 17047 17048 /** 17049 * Prepare app data for the given app. 17050 * <p> 17051 * Verifies that directories exist and that ownership and labeling is 17052 * correct for all installed apps. If there is an ownership mismatch, this 17053 * will try recovering system apps by wiping data; third-party app data is 17054 * left intact. 17055 */ 17056 private void prepareAppData(String volumeUuid, int userId, @StorageFlags int flags, 17057 PackageParser.Package pkg, boolean restoreconNeeded) { 17058 if (DEBUG_APP_DATA) { 17059 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 17060 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 17061 } 17062 17063 final String packageName = pkg.packageName; 17064 final ApplicationInfo app = pkg.applicationInfo; 17065 final int appId = UserHandle.getAppId(app.uid); 17066 17067 Preconditions.checkNotNull(app.seinfo); 17068 17069 synchronized (mInstallLock) { 17070 try { 17071 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 17072 appId, app.seinfo, app.targetSdkVersion); 17073 } catch (InstallerException e) { 17074 if (app.isSystemApp()) { 17075 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 17076 + ", but trying to recover: " + e); 17077 destroyAppDataLI(volumeUuid, packageName, userId, flags); 17078 try { 17079 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 17080 appId, app.seinfo, app.targetSdkVersion); 17081 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 17082 } catch (InstallerException e2) { 17083 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 17084 } 17085 } else { 17086 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 17087 } 17088 } 17089 17090 if (restoreconNeeded) { 17091 restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo); 17092 } 17093 17094 if ((flags & Installer.FLAG_CE_STORAGE) != 0) { 17095 // Create a native library symlink only if we have native libraries 17096 // and if the native libraries are 32 bit libraries. We do not provide 17097 // this symlink for 64 bit libraries. 17098 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 17099 final String nativeLibPath = app.nativeLibraryDir; 17100 try { 17101 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 17102 nativeLibPath, userId); 17103 } catch (InstallerException e) { 17104 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 17105 } 17106 } 17107 } 17108 } 17109 } 17110 17111 private void unfreezePackage(String packageName) { 17112 synchronized (mPackages) { 17113 final PackageSetting ps = mSettings.mPackages.get(packageName); 17114 if (ps != null) { 17115 ps.frozen = false; 17116 } 17117 } 17118 } 17119 17120 @Override 17121 public int movePackage(final String packageName, final String volumeUuid) { 17122 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 17123 17124 final int moveId = mNextMoveId.getAndIncrement(); 17125 mHandler.post(new Runnable() { 17126 @Override 17127 public void run() { 17128 try { 17129 movePackageInternal(packageName, volumeUuid, moveId); 17130 } catch (PackageManagerException e) { 17131 Slog.w(TAG, "Failed to move " + packageName, e); 17132 mMoveCallbacks.notifyStatusChanged(moveId, 17133 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 17134 } 17135 } 17136 }); 17137 return moveId; 17138 } 17139 17140 private void movePackageInternal(final String packageName, final String volumeUuid, 17141 final int moveId) throws PackageManagerException { 17142 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 17143 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17144 final PackageManager pm = mContext.getPackageManager(); 17145 17146 final boolean currentAsec; 17147 final String currentVolumeUuid; 17148 final File codeFile; 17149 final String installerPackageName; 17150 final String packageAbiOverride; 17151 final int appId; 17152 final String seinfo; 17153 final String label; 17154 final int targetSdkVersion; 17155 17156 // reader 17157 synchronized (mPackages) { 17158 final PackageParser.Package pkg = mPackages.get(packageName); 17159 final PackageSetting ps = mSettings.mPackages.get(packageName); 17160 if (pkg == null || ps == null) { 17161 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 17162 } 17163 17164 if (pkg.applicationInfo.isSystemApp()) { 17165 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 17166 "Cannot move system application"); 17167 } 17168 17169 if (pkg.applicationInfo.isExternalAsec()) { 17170 currentAsec = true; 17171 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 17172 } else if (pkg.applicationInfo.isForwardLocked()) { 17173 currentAsec = true; 17174 currentVolumeUuid = "forward_locked"; 17175 } else { 17176 currentAsec = false; 17177 currentVolumeUuid = ps.volumeUuid; 17178 17179 final File probe = new File(pkg.codePath); 17180 final File probeOat = new File(probe, "oat"); 17181 if (!probe.isDirectory() || !probeOat.isDirectory()) { 17182 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17183 "Move only supported for modern cluster style installs"); 17184 } 17185 } 17186 17187 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 17188 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17189 "Package already moved to " + volumeUuid); 17190 } 17191 17192 if (ps.frozen) { 17193 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 17194 "Failed to move already frozen package"); 17195 } 17196 ps.frozen = true; 17197 17198 codeFile = new File(pkg.codePath); 17199 installerPackageName = ps.installerPackageName; 17200 packageAbiOverride = ps.cpuAbiOverrideString; 17201 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 17202 seinfo = pkg.applicationInfo.seinfo; 17203 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 17204 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 17205 } 17206 17207 // Now that we're guarded by frozen state, kill app during move 17208 final long token = Binder.clearCallingIdentity(); 17209 try { 17210 killApplication(packageName, appId, "move pkg"); 17211 } finally { 17212 Binder.restoreCallingIdentity(token); 17213 } 17214 17215 final Bundle extras = new Bundle(); 17216 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 17217 extras.putString(Intent.EXTRA_TITLE, label); 17218 mMoveCallbacks.notifyCreated(moveId, extras); 17219 17220 int installFlags; 17221 final boolean moveCompleteApp; 17222 final File measurePath; 17223 17224 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 17225 installFlags = INSTALL_INTERNAL; 17226 moveCompleteApp = !currentAsec; 17227 measurePath = Environment.getDataAppDirectory(volumeUuid); 17228 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 17229 installFlags = INSTALL_EXTERNAL; 17230 moveCompleteApp = false; 17231 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 17232 } else { 17233 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 17234 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 17235 || !volume.isMountedWritable()) { 17236 unfreezePackage(packageName); 17237 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17238 "Move location not mounted private volume"); 17239 } 17240 17241 Preconditions.checkState(!currentAsec); 17242 17243 installFlags = INSTALL_INTERNAL; 17244 moveCompleteApp = true; 17245 measurePath = Environment.getDataAppDirectory(volumeUuid); 17246 } 17247 17248 final PackageStats stats = new PackageStats(null, -1); 17249 synchronized (mInstaller) { 17250 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 17251 unfreezePackage(packageName); 17252 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17253 "Failed to measure package size"); 17254 } 17255 } 17256 17257 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 17258 + stats.dataSize); 17259 17260 final long startFreeBytes = measurePath.getFreeSpace(); 17261 final long sizeBytes; 17262 if (moveCompleteApp) { 17263 sizeBytes = stats.codeSize + stats.dataSize; 17264 } else { 17265 sizeBytes = stats.codeSize; 17266 } 17267 17268 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 17269 unfreezePackage(packageName); 17270 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17271 "Not enough free space to move"); 17272 } 17273 17274 mMoveCallbacks.notifyStatusChanged(moveId, 10); 17275 17276 final CountDownLatch installedLatch = new CountDownLatch(1); 17277 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 17278 @Override 17279 public void onUserActionRequired(Intent intent) throws RemoteException { 17280 throw new IllegalStateException(); 17281 } 17282 17283 @Override 17284 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 17285 Bundle extras) throws RemoteException { 17286 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 17287 + PackageManager.installStatusToString(returnCode, msg)); 17288 17289 installedLatch.countDown(); 17290 17291 // Regardless of success or failure of the move operation, 17292 // always unfreeze the package 17293 unfreezePackage(packageName); 17294 17295 final int status = PackageManager.installStatusToPublicStatus(returnCode); 17296 switch (status) { 17297 case PackageInstaller.STATUS_SUCCESS: 17298 mMoveCallbacks.notifyStatusChanged(moveId, 17299 PackageManager.MOVE_SUCCEEDED); 17300 break; 17301 case PackageInstaller.STATUS_FAILURE_STORAGE: 17302 mMoveCallbacks.notifyStatusChanged(moveId, 17303 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 17304 break; 17305 default: 17306 mMoveCallbacks.notifyStatusChanged(moveId, 17307 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 17308 break; 17309 } 17310 } 17311 }; 17312 17313 final MoveInfo move; 17314 if (moveCompleteApp) { 17315 // Kick off a thread to report progress estimates 17316 new Thread() { 17317 @Override 17318 public void run() { 17319 while (true) { 17320 try { 17321 if (installedLatch.await(1, TimeUnit.SECONDS)) { 17322 break; 17323 } 17324 } catch (InterruptedException ignored) { 17325 } 17326 17327 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 17328 final int progress = 10 + (int) MathUtils.constrain( 17329 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 17330 mMoveCallbacks.notifyStatusChanged(moveId, progress); 17331 } 17332 } 17333 }.start(); 17334 17335 final String dataAppName = codeFile.getName(); 17336 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 17337 dataAppName, appId, seinfo, targetSdkVersion); 17338 } else { 17339 move = null; 17340 } 17341 17342 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 17343 17344 final Message msg = mHandler.obtainMessage(INIT_COPY); 17345 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 17346 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 17347 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 17348 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 17349 msg.obj = params; 17350 17351 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 17352 System.identityHashCode(msg.obj)); 17353 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 17354 System.identityHashCode(msg.obj)); 17355 17356 mHandler.sendMessage(msg); 17357 } 17358 17359 @Override 17360 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 17361 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 17362 17363 final int realMoveId = mNextMoveId.getAndIncrement(); 17364 final Bundle extras = new Bundle(); 17365 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 17366 mMoveCallbacks.notifyCreated(realMoveId, extras); 17367 17368 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 17369 @Override 17370 public void onCreated(int moveId, Bundle extras) { 17371 // Ignored 17372 } 17373 17374 @Override 17375 public void onStatusChanged(int moveId, int status, long estMillis) { 17376 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 17377 } 17378 }; 17379 17380 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17381 storage.setPrimaryStorageUuid(volumeUuid, callback); 17382 return realMoveId; 17383 } 17384 17385 @Override 17386 public int getMoveStatus(int moveId) { 17387 mContext.enforceCallingOrSelfPermission( 17388 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 17389 return mMoveCallbacks.mLastStatus.get(moveId); 17390 } 17391 17392 @Override 17393 public void registerMoveCallback(IPackageMoveObserver callback) { 17394 mContext.enforceCallingOrSelfPermission( 17395 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 17396 mMoveCallbacks.register(callback); 17397 } 17398 17399 @Override 17400 public void unregisterMoveCallback(IPackageMoveObserver callback) { 17401 mContext.enforceCallingOrSelfPermission( 17402 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 17403 mMoveCallbacks.unregister(callback); 17404 } 17405 17406 @Override 17407 public boolean setInstallLocation(int loc) { 17408 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 17409 null); 17410 if (getInstallLocation() == loc) { 17411 return true; 17412 } 17413 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 17414 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 17415 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 17416 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 17417 return true; 17418 } 17419 return false; 17420 } 17421 17422 @Override 17423 public int getInstallLocation() { 17424 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 17425 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 17426 PackageHelper.APP_INSTALL_AUTO); 17427 } 17428 17429 /** Called by UserManagerService */ 17430 void cleanUpUser(UserManagerService userManager, int userHandle) { 17431 synchronized (mPackages) { 17432 mDirtyUsers.remove(userHandle); 17433 mUserNeedsBadging.delete(userHandle); 17434 mSettings.removeUserLPw(userHandle); 17435 mPendingBroadcasts.remove(userHandle); 17436 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 17437 } 17438 synchronized (mInstallLock) { 17439 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17440 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 17441 final String volumeUuid = vol.getFsUuid(); 17442 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 17443 try { 17444 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 17445 } catch (InstallerException e) { 17446 Slog.w(TAG, "Failed to remove user data", e); 17447 } 17448 } 17449 synchronized (mPackages) { 17450 removeUnusedPackagesLILPw(userManager, userHandle); 17451 } 17452 } 17453 } 17454 17455 /** 17456 * We're removing userHandle and would like to remove any downloaded packages 17457 * that are no longer in use by any other user. 17458 * @param userHandle the user being removed 17459 */ 17460 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 17461 final boolean DEBUG_CLEAN_APKS = false; 17462 int [] users = userManager.getUserIds(); 17463 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 17464 while (psit.hasNext()) { 17465 PackageSetting ps = psit.next(); 17466 if (ps.pkg == null) { 17467 continue; 17468 } 17469 final String packageName = ps.pkg.packageName; 17470 // Skip over if system app 17471 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 17472 continue; 17473 } 17474 if (DEBUG_CLEAN_APKS) { 17475 Slog.i(TAG, "Checking package " + packageName); 17476 } 17477 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 17478 if (keep) { 17479 if (DEBUG_CLEAN_APKS) { 17480 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 17481 } 17482 } else { 17483 for (int i = 0; i < users.length; i++) { 17484 if (users[i] != userHandle && ps.getInstalled(users[i])) { 17485 keep = true; 17486 if (DEBUG_CLEAN_APKS) { 17487 Slog.i(TAG, " Keeping package " + packageName + " for user " 17488 + users[i]); 17489 } 17490 break; 17491 } 17492 } 17493 } 17494 if (!keep) { 17495 if (DEBUG_CLEAN_APKS) { 17496 Slog.i(TAG, " Removing package " + packageName); 17497 } 17498 mHandler.post(new Runnable() { 17499 public void run() { 17500 deletePackageX(packageName, userHandle, 0); 17501 } //end run 17502 }); 17503 } 17504 } 17505 } 17506 17507 /** Called by UserManagerService */ 17508 void createNewUser(int userHandle) { 17509 synchronized (mInstallLock) { 17510 try { 17511 mInstaller.createUserConfig(userHandle); 17512 } catch (InstallerException e) { 17513 Slog.w(TAG, "Failed to create user config", e); 17514 } 17515 mSettings.createNewUserLI(this, mInstaller, userHandle); 17516 } 17517 synchronized (mPackages) { 17518 applyFactoryDefaultBrowserLPw(userHandle); 17519 primeDomainVerificationsLPw(userHandle); 17520 } 17521 } 17522 17523 void newUserCreated(final int userHandle) { 17524 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 17525 // If permission review for legacy apps is required, we represent 17526 // dagerous permissions for such apps as always granted runtime 17527 // permissions to keep per user flag state whether review is needed. 17528 // Hence, if a new user is added we have to propagate dangerous 17529 // permission grants for these legacy apps. 17530 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 17531 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 17532 | UPDATE_PERMISSIONS_REPLACE_ALL); 17533 } 17534 } 17535 17536 @Override 17537 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 17538 mContext.enforceCallingOrSelfPermission( 17539 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 17540 "Only package verification agents can read the verifier device identity"); 17541 17542 synchronized (mPackages) { 17543 return mSettings.getVerifierDeviceIdentityLPw(); 17544 } 17545 } 17546 17547 @Override 17548 public void setPermissionEnforced(String permission, boolean enforced) { 17549 // TODO: Now that we no longer change GID for storage, this should to away. 17550 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 17551 "setPermissionEnforced"); 17552 if (READ_EXTERNAL_STORAGE.equals(permission)) { 17553 synchronized (mPackages) { 17554 if (mSettings.mReadExternalStorageEnforced == null 17555 || mSettings.mReadExternalStorageEnforced != enforced) { 17556 mSettings.mReadExternalStorageEnforced = enforced; 17557 mSettings.writeLPr(); 17558 } 17559 } 17560 // kill any non-foreground processes so we restart them and 17561 // grant/revoke the GID. 17562 final IActivityManager am = ActivityManagerNative.getDefault(); 17563 if (am != null) { 17564 final long token = Binder.clearCallingIdentity(); 17565 try { 17566 am.killProcessesBelowForeground("setPermissionEnforcement"); 17567 } catch (RemoteException e) { 17568 } finally { 17569 Binder.restoreCallingIdentity(token); 17570 } 17571 } 17572 } else { 17573 throw new IllegalArgumentException("No selective enforcement for " + permission); 17574 } 17575 } 17576 17577 @Override 17578 @Deprecated 17579 public boolean isPermissionEnforced(String permission) { 17580 return true; 17581 } 17582 17583 @Override 17584 public boolean isStorageLow() { 17585 final long token = Binder.clearCallingIdentity(); 17586 try { 17587 final DeviceStorageMonitorInternal 17588 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 17589 if (dsm != null) { 17590 return dsm.isMemoryLow(); 17591 } else { 17592 return false; 17593 } 17594 } finally { 17595 Binder.restoreCallingIdentity(token); 17596 } 17597 } 17598 17599 @Override 17600 public IPackageInstaller getPackageInstaller() { 17601 return mInstallerService; 17602 } 17603 17604 private boolean userNeedsBadging(int userId) { 17605 int index = mUserNeedsBadging.indexOfKey(userId); 17606 if (index < 0) { 17607 final UserInfo userInfo; 17608 final long token = Binder.clearCallingIdentity(); 17609 try { 17610 userInfo = sUserManager.getUserInfo(userId); 17611 } finally { 17612 Binder.restoreCallingIdentity(token); 17613 } 17614 final boolean b; 17615 if (userInfo != null && userInfo.isManagedProfile()) { 17616 b = true; 17617 } else { 17618 b = false; 17619 } 17620 mUserNeedsBadging.put(userId, b); 17621 return b; 17622 } 17623 return mUserNeedsBadging.valueAt(index); 17624 } 17625 17626 @Override 17627 public KeySet getKeySetByAlias(String packageName, String alias) { 17628 if (packageName == null || alias == null) { 17629 return null; 17630 } 17631 synchronized(mPackages) { 17632 final PackageParser.Package pkg = mPackages.get(packageName); 17633 if (pkg == null) { 17634 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17635 throw new IllegalArgumentException("Unknown package: " + packageName); 17636 } 17637 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17638 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 17639 } 17640 } 17641 17642 @Override 17643 public KeySet getSigningKeySet(String packageName) { 17644 if (packageName == null) { 17645 return null; 17646 } 17647 synchronized(mPackages) { 17648 final PackageParser.Package pkg = mPackages.get(packageName); 17649 if (pkg == null) { 17650 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17651 throw new IllegalArgumentException("Unknown package: " + packageName); 17652 } 17653 if (pkg.applicationInfo.uid != Binder.getCallingUid() 17654 && Process.SYSTEM_UID != Binder.getCallingUid()) { 17655 throw new SecurityException("May not access signing KeySet of other apps."); 17656 } 17657 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17658 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 17659 } 17660 } 17661 17662 @Override 17663 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 17664 if (packageName == null || ks == null) { 17665 return false; 17666 } 17667 synchronized(mPackages) { 17668 final PackageParser.Package pkg = mPackages.get(packageName); 17669 if (pkg == null) { 17670 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17671 throw new IllegalArgumentException("Unknown package: " + packageName); 17672 } 17673 IBinder ksh = ks.getToken(); 17674 if (ksh instanceof KeySetHandle) { 17675 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17676 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 17677 } 17678 return false; 17679 } 17680 } 17681 17682 @Override 17683 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 17684 if (packageName == null || ks == null) { 17685 return false; 17686 } 17687 synchronized(mPackages) { 17688 final PackageParser.Package pkg = mPackages.get(packageName); 17689 if (pkg == null) { 17690 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17691 throw new IllegalArgumentException("Unknown package: " + packageName); 17692 } 17693 IBinder ksh = ks.getToken(); 17694 if (ksh instanceof KeySetHandle) { 17695 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17696 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 17697 } 17698 return false; 17699 } 17700 } 17701 17702 private void deletePackageIfUnusedLPr(final String packageName) { 17703 PackageSetting ps = mSettings.mPackages.get(packageName); 17704 if (ps == null) { 17705 return; 17706 } 17707 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 17708 // TODO Implement atomic delete if package is unused 17709 // It is currently possible that the package will be deleted even if it is installed 17710 // after this method returns. 17711 mHandler.post(new Runnable() { 17712 public void run() { 17713 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 17714 } 17715 }); 17716 } 17717 } 17718 17719 /** 17720 * Check and throw if the given before/after packages would be considered a 17721 * downgrade. 17722 */ 17723 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 17724 throws PackageManagerException { 17725 if (after.versionCode < before.mVersionCode) { 17726 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17727 "Update version code " + after.versionCode + " is older than current " 17728 + before.mVersionCode); 17729 } else if (after.versionCode == before.mVersionCode) { 17730 if (after.baseRevisionCode < before.baseRevisionCode) { 17731 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17732 "Update base revision code " + after.baseRevisionCode 17733 + " is older than current " + before.baseRevisionCode); 17734 } 17735 17736 if (!ArrayUtils.isEmpty(after.splitNames)) { 17737 for (int i = 0; i < after.splitNames.length; i++) { 17738 final String splitName = after.splitNames[i]; 17739 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 17740 if (j != -1) { 17741 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 17742 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17743 "Update split " + splitName + " revision code " 17744 + after.splitRevisionCodes[i] + " is older than current " 17745 + before.splitRevisionCodes[j]); 17746 } 17747 } 17748 } 17749 } 17750 } 17751 } 17752 17753 private static class MoveCallbacks extends Handler { 17754 private static final int MSG_CREATED = 1; 17755 private static final int MSG_STATUS_CHANGED = 2; 17756 17757 private final RemoteCallbackList<IPackageMoveObserver> 17758 mCallbacks = new RemoteCallbackList<>(); 17759 17760 private final SparseIntArray mLastStatus = new SparseIntArray(); 17761 17762 public MoveCallbacks(Looper looper) { 17763 super(looper); 17764 } 17765 17766 public void register(IPackageMoveObserver callback) { 17767 mCallbacks.register(callback); 17768 } 17769 17770 public void unregister(IPackageMoveObserver callback) { 17771 mCallbacks.unregister(callback); 17772 } 17773 17774 @Override 17775 public void handleMessage(Message msg) { 17776 final SomeArgs args = (SomeArgs) msg.obj; 17777 final int n = mCallbacks.beginBroadcast(); 17778 for (int i = 0; i < n; i++) { 17779 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 17780 try { 17781 invokeCallback(callback, msg.what, args); 17782 } catch (RemoteException ignored) { 17783 } 17784 } 17785 mCallbacks.finishBroadcast(); 17786 args.recycle(); 17787 } 17788 17789 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 17790 throws RemoteException { 17791 switch (what) { 17792 case MSG_CREATED: { 17793 callback.onCreated(args.argi1, (Bundle) args.arg2); 17794 break; 17795 } 17796 case MSG_STATUS_CHANGED: { 17797 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 17798 break; 17799 } 17800 } 17801 } 17802 17803 private void notifyCreated(int moveId, Bundle extras) { 17804 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 17805 17806 final SomeArgs args = SomeArgs.obtain(); 17807 args.argi1 = moveId; 17808 args.arg2 = extras; 17809 obtainMessage(MSG_CREATED, args).sendToTarget(); 17810 } 17811 17812 private void notifyStatusChanged(int moveId, int status) { 17813 notifyStatusChanged(moveId, status, -1); 17814 } 17815 17816 private void notifyStatusChanged(int moveId, int status, long estMillis) { 17817 Slog.v(TAG, "Move " + moveId + " status " + status); 17818 17819 final SomeArgs args = SomeArgs.obtain(); 17820 args.argi1 = moveId; 17821 args.argi2 = status; 17822 args.arg3 = estMillis; 17823 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 17824 17825 synchronized (mLastStatus) { 17826 mLastStatus.put(moveId, status); 17827 } 17828 } 17829 } 17830 17831 private final static class OnPermissionChangeListeners extends Handler { 17832 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 17833 17834 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 17835 new RemoteCallbackList<>(); 17836 17837 public OnPermissionChangeListeners(Looper looper) { 17838 super(looper); 17839 } 17840 17841 @Override 17842 public void handleMessage(Message msg) { 17843 switch (msg.what) { 17844 case MSG_ON_PERMISSIONS_CHANGED: { 17845 final int uid = msg.arg1; 17846 handleOnPermissionsChanged(uid); 17847 } break; 17848 } 17849 } 17850 17851 public void addListenerLocked(IOnPermissionsChangeListener listener) { 17852 mPermissionListeners.register(listener); 17853 17854 } 17855 17856 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 17857 mPermissionListeners.unregister(listener); 17858 } 17859 17860 public void onPermissionsChanged(int uid) { 17861 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 17862 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 17863 } 17864 } 17865 17866 private void handleOnPermissionsChanged(int uid) { 17867 final int count = mPermissionListeners.beginBroadcast(); 17868 try { 17869 for (int i = 0; i < count; i++) { 17870 IOnPermissionsChangeListener callback = mPermissionListeners 17871 .getBroadcastItem(i); 17872 try { 17873 callback.onPermissionsChanged(uid); 17874 } catch (RemoteException e) { 17875 Log.e(TAG, "Permission listener is dead", e); 17876 } 17877 } 17878 } finally { 17879 mPermissionListeners.finishBroadcast(); 17880 } 17881 } 17882 } 17883 17884 private class PackageManagerInternalImpl extends PackageManagerInternal { 17885 @Override 17886 public void setLocationPackagesProvider(PackagesProvider provider) { 17887 synchronized (mPackages) { 17888 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 17889 } 17890 } 17891 17892 @Override 17893 public void setImePackagesProvider(PackagesProvider provider) { 17894 synchronized (mPackages) { 17895 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 17896 } 17897 } 17898 17899 @Override 17900 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 17901 synchronized (mPackages) { 17902 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 17903 } 17904 } 17905 17906 @Override 17907 public void setSmsAppPackagesProvider(PackagesProvider provider) { 17908 synchronized (mPackages) { 17909 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 17910 } 17911 } 17912 17913 @Override 17914 public void setDialerAppPackagesProvider(PackagesProvider provider) { 17915 synchronized (mPackages) { 17916 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 17917 } 17918 } 17919 17920 @Override 17921 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 17922 synchronized (mPackages) { 17923 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 17924 } 17925 } 17926 17927 @Override 17928 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 17929 synchronized (mPackages) { 17930 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 17931 } 17932 } 17933 17934 @Override 17935 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 17936 synchronized (mPackages) { 17937 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 17938 packageName, userId); 17939 } 17940 } 17941 17942 @Override 17943 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 17944 synchronized (mPackages) { 17945 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 17946 packageName, userId); 17947 } 17948 } 17949 17950 @Override 17951 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 17952 synchronized (mPackages) { 17953 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 17954 packageName, userId); 17955 } 17956 } 17957 17958 @Override 17959 public void setKeepUninstalledPackages(final List<String> packageList) { 17960 Preconditions.checkNotNull(packageList); 17961 List<String> removedFromList = null; 17962 synchronized (mPackages) { 17963 if (mKeepUninstalledPackages != null) { 17964 final int packagesCount = mKeepUninstalledPackages.size(); 17965 for (int i = 0; i < packagesCount; i++) { 17966 String oldPackage = mKeepUninstalledPackages.get(i); 17967 if (packageList != null && packageList.contains(oldPackage)) { 17968 continue; 17969 } 17970 if (removedFromList == null) { 17971 removedFromList = new ArrayList<>(); 17972 } 17973 removedFromList.add(oldPackage); 17974 } 17975 } 17976 mKeepUninstalledPackages = new ArrayList<>(packageList); 17977 if (removedFromList != null) { 17978 final int removedCount = removedFromList.size(); 17979 for (int i = 0; i < removedCount; i++) { 17980 deletePackageIfUnusedLPr(removedFromList.get(i)); 17981 } 17982 } 17983 } 17984 } 17985 17986 @Override 17987 public boolean isPermissionsReviewRequired(String packageName, int userId) { 17988 synchronized (mPackages) { 17989 // If we do not support permission review, done. 17990 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 17991 return false; 17992 } 17993 17994 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 17995 if (packageSetting == null) { 17996 return false; 17997 } 17998 17999 // Permission review applies only to apps not supporting the new permission model. 18000 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 18001 return false; 18002 } 18003 18004 // Legacy apps have the permission and get user consent on launch. 18005 PermissionsState permissionsState = packageSetting.getPermissionsState(); 18006 return permissionsState.isPermissionReviewRequired(userId); 18007 } 18008 } 18009 } 18010 18011 @Override 18012 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 18013 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 18014 synchronized (mPackages) { 18015 final long identity = Binder.clearCallingIdentity(); 18016 try { 18017 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 18018 packageNames, userId); 18019 } finally { 18020 Binder.restoreCallingIdentity(identity); 18021 } 18022 } 18023 } 18024 18025 private static void enforceSystemOrPhoneCaller(String tag) { 18026 int callingUid = Binder.getCallingUid(); 18027 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 18028 throw new SecurityException( 18029 "Cannot call " + tag + " from UID " + callingUid); 18030 } 18031 } 18032} 18033